Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>
@load_model('papaye.evolve.models.snapshot1')
def evolve(root, config=None):
context = context_from_root(root)
<|code_end|>
. Use current file imports:
(from papaye.evolve.managers import load_model, context_from_root)
and context including class names, function names, or small code snippets from other files:
# Path: papaye/evolve/managers.py
# def load_model(model_name):
# def decorated(func):
# func.load_model = importlib.import_module(model_name)
# return func
# return decorated
#
# def context_from_root(root):
# return root[APP_ROOT_NAME]
. Output only the next line. | repository = context.get('repository', tuple()) |
Next line prediction: <|code_start|>
@load_model('papaye.evolve.models.snapshot1')
def evolve(root, config=None):
context = context_from_root(root)
repository = context.get('repository', tuple())
for package_name in repository:
package = repository[package_name]
package.__parent__ = repository
print('Upgrade {} package'.format(package.__name__))
for release_name in package.releases:
release = package[release_name]
<|code_end|>
. Use current file imports:
(from papaye.evolve.managers import load_model, context_from_root)
and context including class names, function names, or small code snippets from other files:
# Path: papaye/evolve/managers.py
# def load_model(model_name):
# def decorated(func):
# func.load_model = importlib.import_module(model_name)
# return func
# return decorated
#
# def context_from_root(root):
# return root[APP_ROOT_NAME]
. Output only the next line. | release.__parent__ = package |
Predict the next line after this snippet: <|code_start|>
def get_sentinel_user():
users = get_user_model().objects
return users.get_or_create(username='[deleted]', is_active=False)[0]
@receiver(pre_delete, sender=User)
def soft_delete_user_dweets(instance, **kwargs):
for dweet in Dweet.objects.filter(author=instance):
dweet.delete()
class NotDeletedDweetManager(models.Manager):
def get_queryset(self):
<|code_end|>
using the current file's imports:
import re
from django.db import models
from django.utils.functional import cached_property
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import pre_delete, post_save, m2m_changed
from math import log
from datetime import datetime
from .utils import length_of_code
and any relevant context from other files:
# Path: dwitter/utils.py
# def length_of_code(code):
# """
# Centralize the character counting to one place
# """
# return len(code.replace('\r\n', '\n'))
. Output only the next line. | base_queryset = super(NotDeletedDweetManager, self).get_queryset() |
Predict the next line after this snippet: <|code_start|>
urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
url(r'^d/(?P<dweet_id>\d+)/reply$',
<|code_end|>
using the current file's imports:
from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed
and any relevant context from other files:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
. Output only the next line. | views.dweet_reply, name='dweet_reply'), |
Given the code snippet: <|code_start|>
urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
url(r'^d/(?P<dweet_id>\d+)/reply$',
views.dweet_reply, name='dweet_reply'),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed
and context (functions, classes, or occasionally code) from other files:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
. Output only the next line. | url(r'^d/(?P<dweet_id>\d+)/delete$', |
Given snippet: <|code_start|>
urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
url(r'^d/(?P<dweet_id>\d+)/reply$',
views.dweet_reply, name='dweet_reply'),
url(r'^d/(?P<dweet_id>\d+)/delete$',
views.dweet_delete, name='dweet_delete'),
url(r'^d/(?P<dweet_id>\d+)/like$', views.like, name='like'),
url(r'^d/(?P<dweet_id>\d+)/report$', views.report_dweet, name='report_dweet'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed
and context:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
which might include code, classes, or functions. Output only the next line. | url(r'^c/(?P<comment_id>\d+)/report$', views.report_comment, name='report_comment'), |
Here is a snippet: <|code_start|>
urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
url(r'^d/(?P<dweet_id>\d+)/reply$',
views.dweet_reply, name='dweet_reply'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed
and context from other files:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
, which may include functions, classes, or code. Output only the next line. | url(r'^d/(?P<dweet_id>\d+)/delete$', |
Next line prediction: <|code_start|>
urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
. Output only the next line. | url(r'^d/(?P<dweet_id>\d+)/reply$', |
Based on the snippet: <|code_start|>
urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
url(r'^d/(?P<dweet_id>\d+)/reply$',
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed
and context (classes, functions, sometimes code) from other files:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
. Output only the next line. | views.dweet_reply, name='dweet_reply'), |
Next line prediction: <|code_start|>
urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
url(r'^d/(?P<dweet_id>\d+)/reply$',
views.dweet_reply, name='dweet_reply'),
url(r'^d/(?P<dweet_id>\d+)/delete$',
views.dweet_delete, name='dweet_delete'),
url(r'^d/(?P<dweet_id>\d+)/like$', views.like, name='like'),
url(r'^d/(?P<dweet_id>\d+)/report$', views.report_dweet, name='report_dweet'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
. Output only the next line. | url(r'^c/(?P<comment_id>\d+)/report$', views.report_comment, name='report_comment'), |
Next line prediction: <|code_start|>
urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
url(r'^d/(?P<dweet_id>\d+)/reply$',
views.dweet_reply, name='dweet_reply'),
url(r'^d/(?P<dweet_id>\d+)/delete$',
views.dweet_delete, name='dweet_delete'),
url(r'^d/(?P<dweet_id>\d+)/like$', views.like, name='like'),
url(r'^d/(?P<dweet_id>\d+)/report$', views.report_dweet, name='report_dweet'),
url(r'^c/(?P<comment_id>\d+)/report$', views.report_comment, name='report_comment'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
. Output only the next line. | url(r'^e/(?P<dweet_id>\d+)$', |
Continue the code snippet: <|code_start|>urlpatterns = [
url(r'^test/', HotDweetFeed.as_view()),
url(r'^$', HotDweetFeed.as_view(), name='root'),
url(r'^hot$', HotDweetFeed.as_view(), name='hot_feed'),
# Default top to top of the month
url(r'^top$', TopMonthDweetFeed.as_view(), name='top_feed'),
url(r'^top/week$', TopWeekDweetFeed.as_view(), name='top_feed_week'),
url(r'^top/month$', TopMonthDweetFeed.as_view(), name='top_feed_month'),
url(r'^top/year$', TopYearDweetFeed.as_view(), name='top_feed_year'),
url(r'^top/all$', TopAllDweetFeed.as_view(), name='top_feed_all'),
url(r'^new$', NewDweetFeed.as_view(), name='new_feed'),
url(r'^random$', RandomDweetFeed.as_view(), name='random_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)$', NewHashtagFeed.as_view(), name='hashtag_feed'),
url(r'^h/(?P<hashtag_name>[\w._]+)/top$', TopHashtagFeed.as_view(), name='top_hashtag_feed'),
url(r'^d/(?P<dweet_id>\d+)$',
views.dweet_show, name='dweet_show'),
url(r'^d/(?P<dweet_id>\d+)/reply$',
views.dweet_reply, name='dweet_reply'),
url(r'^d/(?P<dweet_id>\d+)/delete$',
views.dweet_delete, name='dweet_delete'),
url(r'^d/(?P<dweet_id>\d+)/like$', views.like, name='like'),
url(r'^d/(?P<dweet_id>\d+)/report$', views.report_dweet, name='report_dweet'),
url(r'^c/(?P<comment_id>\d+)/report$', views.report_comment, name='report_comment'),
url(r'^e/(?P<dweet_id>\d+)$',
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from . import views
from .views import HotDweetFeed, NewDweetFeed, RandomDweetFeed
from .views import TopWeekDweetFeed, TopMonthDweetFeed, TopYearDweetFeed, TopAllDweetFeed
from .views import NewHashtagFeed, TopHashtagFeed
and context (classes, functions, or code) from other files:
# Path: dwitter/feed/views.py
# class HotDweetFeed(AllDweetFeed):
# title = "Dwitter - javascript demos in 140 characters"
# sort = SortMethod.HOT
# feed_name = "hot"
#
# class NewDweetFeed(AllDweetFeed):
# title = "New dweets | Dwitter"
# sort = SortMethod.NEW
# feed_name = "new"
#
# class RandomDweetFeed(AllDweetFeed):
# title = "Random dweets | Dwitter"
# sort = SortMethod.RANDOM
# feed_name = "random"
#
# Path: dwitter/feed/views.py
# class TopWeekDweetFeed(TopDweetFeedBase):
# title = "Top dweets this week | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-week"
# top_name = "week"
# days = 7
#
# class TopMonthDweetFeed(TopDweetFeedBase):
# title = "Top dweets this month | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-month"
# top_name = "month"
# days = 30
#
# class TopYearDweetFeed(TopDweetFeedBase):
# title = "Top dweets this year | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-year"
# top_name = "year"
# days = 365
#
# class TopAllDweetFeed(AllDweetFeed):
# title = "Top dweets of all time | Dwitter"
# sort = SortMethod.TOP
# feed_name = "top-all"
# top_name = "all time"
#
# def get_context_data(self, **kwargs):
# context = super(TopAllDweetFeed, self).get_context_data(**kwargs)
# context['top_name'] = self.top_name
# return context
#
# def get_dweet_list(self):
# return Dweet.objects.annotate(num_likes=Count('likes'))
#
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
. Output only the next line. | views.dweet_embed, name='dweet_embed'), |
Based on the snippet: <|code_start|> self.assertContains(response, "Dweet code too long!", status_code=400)
# shorter code should go through!
response = self.client.post('/dweet', {'code': 'test code that is a lot shorter,' +
'wow this looks long in code.' +
'And BAM not tooo long!'}, follow=True)
self.assertEqual(response.status_code, 200)
dweets = Dweet.objects.filter(author=user)
self.assertEqual(dweets.count(), 2)
def test_post_dweet_reply(self):
user = self.login()
response = self.client.post('/d/1000/reply', {'code': 'test_code'}, follow=True)
self.assertEqual(response.status_code, 200,
"Posting dweet return 200. Status code " + str(response.status_code))
dweet = Dweet.objects.get(code='test_code')
self.assertEqual(dweet.code, 'test_code')
self.assertEqual(dweet.author, user)
self.assertEqual(dweet.reply_to, self.dweet)
def test_post_dweet_reply_with_first_comment(self):
user = self.login()
response = self.client.post('/d/1000/reply',
{'code': 'test_code', 'first-comment': 'hello there'},
follow=True)
self.assertEqual(response.status_code, 200,
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TransactionTestCase, Client
from django.contrib.auth.models import User
from django.contrib import auth
from dwitter.models import Dweet, Comment, Hashtag
from django.utils import timezone
and context (classes, functions, sometimes code) from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Hashtag(models.Model):
# name = models.CharField(max_length=30, unique=True, db_index=True)
# dweets = models.ManyToManyField(Dweet, related_name="hashtag", blank=True)
#
# def __str__(self):
# return '#' + self.name
. Output only the next line. | "Posting dweet return 200. Status code " + str(response.status_code)) |
Using the snippet: <|code_start|> self.assertEqual(dweet.code, 'test_code')
self.assertEqual(dweet.author, user)
comment = Comment.objects.get(reply_to=dweet)
self.assertEqual(comment.text, 'hello there #woo')
self.assertEqual(comment.author, user)
hashtag = Hashtag.objects.get(name='woo')
self.assertEqual(dweet in hashtag.dweets.all(), True)
def test_too_long_dweet_post(self):
user = self.login()
response = self.client.post('/dweet', {'code': 'test code that is way too long,' +
'wow this looks long in code.' +
'We could fit so much in here.' +
'oh wow. mooooooooooooooooar text.' +
'Getting there.' +
'And BAM tooo long!'}, follow=True)
self.assertContains(response, "Dweet code too long!", status_code=400)
# shorter code should go through!
response = self.client.post('/dweet', {'code': 'test code that is a lot shorter,' +
'wow this looks long in code.' +
'And BAM not tooo long!'}, follow=True)
self.assertEqual(response.status_code, 200)
dweets = Dweet.objects.filter(author=user)
self.assertEqual(dweets.count(), 2)
<|code_end|>
, determine the next line of code. You have imports:
from django.test import TransactionTestCase, Client
from django.contrib.auth.models import User
from django.contrib import auth
from dwitter.models import Dweet, Comment, Hashtag
from django.utils import timezone
and context (class names, function names, or code) available:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Hashtag(models.Model):
# name = models.CharField(max_length=30, unique=True, db_index=True)
# dweets = models.ManyToManyField(Dweet, related_name="hashtag", blank=True)
#
# def __str__(self):
# return '#' + self.name
. Output only the next line. | def test_post_dweet_reply(self): |
Using the snippet: <|code_start|> def test_post_dweet_reply_with_first_comment(self):
user = self.login()
response = self.client.post('/d/1000/reply',
{'code': 'test_code', 'first-comment': 'hello there'},
follow=True)
self.assertEqual(response.status_code, 200,
"Posting dweet return 200. Status code " + str(response.status_code))
dweet = Dweet.objects.get(code='test_code')
self.assertEqual(dweet.code, 'test_code')
self.assertEqual(dweet.author, user)
self.assertEqual(dweet.reply_to, self.dweet)
comment = Comment.objects.get(reply_to=dweet)
self.assertEqual(comment.text, 'hello there')
self.assertEqual(comment.author, user)
def test_post_dweet_reply_with_first_comment_with_hashtag(self):
user = self.login()
response = self.client.post('/d/1000/reply',
{'code': 'test_code', 'first-comment': 'hello there #woo'},
follow=True)
self.assertEqual(response.status_code, 200,
"Posting dweet return 200. Status code " + str(response.status_code))
dweet = Dweet.objects.get(code='test_code')
self.assertEqual(dweet.code, 'test_code')
<|code_end|>
, determine the next line of code. You have imports:
from django.test import TransactionTestCase, Client
from django.contrib.auth.models import User
from django.contrib import auth
from dwitter.models import Dweet, Comment, Hashtag
from django.utils import timezone
and context (class names, function names, or code) available:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Hashtag(models.Model):
# name = models.CharField(max_length=30, unique=True, db_index=True)
# dweets = models.ManyToManyField(Dweet, related_name="hashtag", blank=True)
#
# def __str__(self):
# return '#' + self.name
. Output only the next line. | self.assertEqual(dweet.author, user) |
Next line prediction: <|code_start|>
def handler404(request, *args, **kwargs):
response = render(request, '404_dweet.html')
response.status_code = 404
return response
@xframe_options_exempt
@cache_page(3600)
def fullscreen_dweet(request, dweet_id):
dweet = get_object_or_404(Dweet, id=dweet_id)
context = {
'code': dweet.code,
'newDweet': 'false',
}
return render(request, 'dweet/dweet.html', context)
@xframe_options_exempt
<|code_end|>
. Use current file imports:
(from django.shortcuts import get_object_or_404, render
from dwitter.models import Dweet
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.cache import cache_page)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | @cache_page(3600) |
Next line prediction: <|code_start|>
urlpatterns = [
url(r'^(?P<url_username>[\w.@+-]+)$', NewUserFeed.as_view(), name='user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/hot$', HotUserFeed.as_view(), name='hot_user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/top$', TopUserFeed.as_view(), name='top_user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/awesome$', NewLikedFeed.as_view(), name='user_liked'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from . import views
from ..feed.views import NewUserFeed, HotUserFeed, TopUserFeed, NewLikedFeed)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
. Output only the next line. | url(r'^(?P<url_username>[\w.@+-]+)/settings$', views.user_settings, name='user_settings'), |
Predict the next line after this snippet: <|code_start|>
urlpatterns = [
url(r'^(?P<url_username>[\w.@+-]+)$', NewUserFeed.as_view(), name='user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/hot$', HotUserFeed.as_view(), name='hot_user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/top$', TopUserFeed.as_view(), name='top_user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/awesome$', NewLikedFeed.as_view(), name='user_liked'),
url(r'^(?P<url_username>[\w.@+-]+)/settings$', views.user_settings, name='user_settings'),
<|code_end|>
using the current file's imports:
from django.conf.urls import url
from . import views
from ..feed.views import NewUserFeed, HotUserFeed, TopUserFeed, NewLikedFeed
and any relevant context from other files:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
. Output only the next line. | ] |
Given the code snippet: <|code_start|>
urlpatterns = [
url(r'^(?P<url_username>[\w.@+-]+)$', NewUserFeed.as_view(), name='user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/hot$', HotUserFeed.as_view(), name='hot_user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/top$', TopUserFeed.as_view(), name='top_user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/awesome$', NewLikedFeed.as_view(), name='user_liked'),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import url
from . import views
from ..feed.views import NewUserFeed, HotUserFeed, TopUserFeed, NewLikedFeed
and context (functions, classes, or occasionally code) from other files:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
. Output only the next line. | url(r'^(?P<url_username>[\w.@+-]+)/settings$', views.user_settings, name='user_settings'), |
Next line prediction: <|code_start|>
urlpatterns = [
url(r'^(?P<url_username>[\w.@+-]+)$', NewUserFeed.as_view(), name='user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/hot$', HotUserFeed.as_view(), name='hot_user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/top$', TopUserFeed.as_view(), name='top_user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/awesome$', NewLikedFeed.as_view(), name='user_liked'),
url(r'^(?P<url_username>[\w.@+-]+)/settings$', views.user_settings, name='user_settings'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from . import views
from ..feed.views import NewUserFeed, HotUserFeed, TopUserFeed, NewLikedFeed)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
. Output only the next line. | ] |
Next line prediction: <|code_start|>
class DweetAdmin(admin.ModelAdmin):
raw_id_fields = ('author', 'reply_to', 'likes',)
class CommentAdmin(admin.ModelAdmin):
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from .models import Comment
from .models import Dweet)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | raw_id_fields = ('author', 'reply_to',) |
Here is a snippet: <|code_start|>
dweet1 = Dweet.objects.create(id=1,
code="dweet1 code",
posted=now - timedelta(minutes=1),
author=user1)
dweet2 = Dweet.objects.create(id=2,
code="dweet2 code",
posted=now,
reply_to=dweet1,
author=user2)
Comment.objects.create(id=1,
text="comment1 text",
posted=now - timedelta(minutes=1),
reply_to=dweet2,
author=user1)
Comment.objects.create(id=2,
text="comment2 text",
posted=now,
reply_to=dweet1,
author=user2)
def test_comment_renders_to_string_correctly(self):
self.assertEqual(Comment.objects.get(id=1).__str__(),
"c/1 (user1) to d/2 (user2)")
self.assertEqual(Comment.objects.get(id=2).__str__(),
"c/2 (user2) to d/1 (user1)")
<|code_end|>
. Write the next line using the current file imports:
from django.test import TestCase
from django.contrib.auth.models import User
from dwitter.models import Dweet
from dwitter.models import Comment
from django.utils import timezone
from datetime import timedelta
and context from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
, which may include functions, classes, or code. Output only the next line. | def test_comment_reply_to_do_nothing_on_soft_delete(self): |
Predict the next line for this snippet: <|code_start|>
def user_settings(request, url_username):
user = get_object_or_404(User, username=url_username)
if request.user != user:
return HttpResponse(status=403)
if request.method == 'POST':
user_settings_form = UserSettingsForm(request.POST, instance=user)
if user_settings_form.is_valid():
user = user_settings_form.save()
messages.add_message(request, messages.INFO, 'Saved!')
<|code_end|>
with the help of current file imports:
from django.contrib import messages
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render, redirect
from dwitter.user.forms import UserSettingsForm
and context from other files:
# Path: dwitter/user/forms.py
# class UserSettingsForm(ModelForm):
# class Meta:
# model = get_user_model()
# fields = ('email',)
, which may contain function names, class names, or code. Output only the next line. | return redirect('user_settings', url_username=request.user.username) |
Next line prediction: <|code_start|>
class DweetTestCase(TransactionTestCase):
def setUp(self):
self.client = Client()
self.user = User.objects.create(username="user", password="")
self.dweet = Dweet.objects.create(
id=1,
code="dweet code",
posted=timezone.now(),
author=self.user)
def create_comment(self, text):
return Comment.objects.create(
text=text,
posted=timezone.now(),
reply_to=self.dweet,
author=self.user)
def get_dweet(self):
response = self.client.get('/d/%d' % self.dweet.id)
self.assertEqual(response.status_code, 200)
return response
def get_comments_ajax(self):
response = self.client.get('/api/comments/?format=json&reply_to=%d' % self.dweet.id)
self.assertEqual(response.status_code, 200)
return json.loads(response.content)['results']
def test_comment(self):
<|code_end|>
. Use current file imports:
(import json
from django.contrib.auth.models import User
from django.test import Client, TransactionTestCase
from django.utils import timezone
from django.utils.html import escape
from dwitter.models import Comment, Dweet)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | comment = self.create_comment('this is a comment!') |
Using the snippet: <|code_start|> def create_comment(self, text):
return Comment.objects.create(
text=text,
posted=timezone.now(),
reply_to=self.dweet,
author=self.user)
def get_dweet(self):
response = self.client.get('/d/%d' % self.dweet.id)
self.assertEqual(response.status_code, 200)
return response
def get_comments_ajax(self):
response = self.client.get('/api/comments/?format=json&reply_to=%d' % self.dweet.id)
self.assertEqual(response.status_code, 200)
return json.loads(response.content)['results']
def test_comment(self):
comment = self.create_comment('this is a comment!')
response = self.get_dweet()
self.assertContains(response, comment.text)
def test_comment_xss(self):
comment = self.create_comment('<test>this is a comment!</test>')
response = self.get_dweet()
self.assertNotContains(response, '<test>')
self.assertContains(response, escape(comment.text))
def test_comment_code_blocks(self):
comment = self.create_comment('`this is a comment!`')
<|code_end|>
, determine the next line of code. You have imports:
import json
from django.contrib.auth.models import User
from django.test import Client, TransactionTestCase
from django.utils import timezone
from django.utils.html import escape
from dwitter.models import Comment, Dweet
and context (class names, function names, or code) available:
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | response = self.get_dweet() |
Using the snippet: <|code_start|>
class UserFeedTestCase(): # Not inheriting from TestCase, an abstract test class if you will
request_factory = RequestFactory()
def setUp(self):
self.users = []
for i in range(10):
self.users.append(User.objects.create(username="arrayuser" + str(i), password=""))
now = timezone.now()
d_id = 0
dweets = []
for user in self.users:
for i in range(10):
dweets.append(Dweet.objects.create(id=d_id,
code="filler "+str(i),
<|code_end|>
, determine the next line of code. You have imports:
import random
from django.test import TestCase
from dwitter.feed.views import NewUserFeed, TopUserFeed, HotUserFeed, NewLikedFeed
from dwitter.models import Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
and context (class names, function names, or code) available:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | posted=now - timedelta(minutes=i), |
Predict the next line after this snippet: <|code_start|>
def test_queryset_size(self):
self.dweetFeed.kwargs = {'url_username': self.users[1].username}
queryset = self.dweetFeed.get_queryset()
# Each user have 10 dweets from setUp
self.assertEqual(queryset.count(), 10)
class NewUserFeedTests(UserFeedTestCase, TestCase):
dweetFeed = NewUserFeed()
class TopUserFeedTests(UserFeedTestCase, TestCase):
dweetFeed = TopUserFeed()
def test_annotation(self):
self.dweetFeed.kwargs = {'url_username': self.users[1].username}
queryset = self.dweetFeed.get_queryset()
for dweet in queryset:
num_likes = dweet.num_likes
self.assertEqual(num_likes, dweet.likes.count())
class HotUserFeedTests(UserFeedTestCase, TestCase):
dweetFeed = HotUserFeed()
class NewLikedFeedTests(UserFeedTestCase, TestCase):
dweetFeed = NewLikedFeed()
<|code_end|>
using the current file's imports:
import random
from django.test import TestCase
from dwitter.feed.views import NewUserFeed, TopUserFeed, HotUserFeed, NewLikedFeed
from dwitter.models import Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
and any relevant context from other files:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | def test_queryset_objects(self): |
Based on the snippet: <|code_start|>
class UserFeedTestCase(): # Not inheriting from TestCase, an abstract test class if you will
request_factory = RequestFactory()
def setUp(self):
self.users = []
for i in range(10):
self.users.append(User.objects.create(username="arrayuser" + str(i), password=""))
now = timezone.now()
d_id = 0
dweets = []
for user in self.users:
for i in range(10):
dweets.append(Dweet.objects.create(id=d_id,
code="filler "+str(i),
posted=now - timedelta(minutes=i),
author=user))
d_id += 1
random.seed(1337)
# add random likes between 0 and 5
for i in range(random.randrange(0, 5)):
dweets[-1].likes.add(self.users[i])
# Guarantee that all users have at least two liked dweets
for i in range(10):
dweets[0].likes.add(self.users[i])
dweets[2].likes.add(self.users[i])
<|code_end|>
, predict the immediate next line with the help of imports:
import random
from django.test import TestCase
from dwitter.feed.views import NewUserFeed, TopUserFeed, HotUserFeed, NewLikedFeed
from dwitter.models import Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
and context (classes, functions, sometimes code) from other files:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | def test_all_dweet_author(self): |
Using the snippet: <|code_start|>
def setUp(self):
self.users = []
for i in range(10):
self.users.append(User.objects.create(username="arrayuser" + str(i), password=""))
now = timezone.now()
d_id = 0
dweets = []
for user in self.users:
for i in range(10):
dweets.append(Dweet.objects.create(id=d_id,
code="filler "+str(i),
posted=now - timedelta(minutes=i),
author=user))
d_id += 1
random.seed(1337)
# add random likes between 0 and 5
for i in range(random.randrange(0, 5)):
dweets[-1].likes.add(self.users[i])
# Guarantee that all users have at least two liked dweets
for i in range(10):
dweets[0].likes.add(self.users[i])
dweets[2].likes.add(self.users[i])
def test_all_dweet_author(self):
self.dweetFeed.kwargs = {'url_username': self.users[3].username}
queryset = self.dweetFeed.get_queryset()
<|code_end|>
, determine the next line of code. You have imports:
import random
from django.test import TestCase
from dwitter.feed.views import NewUserFeed, TopUserFeed, HotUserFeed, NewLikedFeed
from dwitter.models import Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
and context (class names, function names, or code) available:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | for dweet in queryset: |
Given snippet: <|code_start|>
class UserFeedTestCase(): # Not inheriting from TestCase, an abstract test class if you will
request_factory = RequestFactory()
def setUp(self):
self.users = []
for i in range(10):
self.users.append(User.objects.create(username="arrayuser" + str(i), password=""))
now = timezone.now()
d_id = 0
dweets = []
for user in self.users:
for i in range(10):
dweets.append(Dweet.objects.create(id=d_id,
code="filler "+str(i),
posted=now - timedelta(minutes=i),
author=user))
d_id += 1
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
from django.test import TestCase
from dwitter.feed.views import NewUserFeed, TopUserFeed, HotUserFeed, NewLikedFeed
from dwitter.models import Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
and context:
# Path: dwitter/feed/views.py
# class NewUserFeed(UserFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# return "Dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class TopUserFeed(UserFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# return "Top dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class HotUserFeed(UserFeed):
# sort = SortMethod.HOT
# feed_name = "hot"
#
# def get_title(self):
# return "Hot dweets by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# class NewLikedFeed(LikedFeed):
# sort = SortMethod.NEW
# feed_name = "awesome"
#
# def get_title(self):
# return "Dweets awesomed by u/" + self.kwargs['url_username'] + " | Dwitter"
#
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
which might include code, classes, or functions. Output only the next line. | random.seed(1337) |
Predict the next line for this snippet: <|code_start|> dweet1 = Dweet.objects.get(id=1)
dweet2 = Dweet.objects.get(id=2)
user1 = User.objects.get(username="user1")
user2 = User.objects.get(username="user2")
self.assertNotEqual(dweet1.hotness, 1.0, "Hotness not set correctly for new dweet")
self.assertEqual(dweet1.likes.count(), 0, "Fresh dweet doesn't start with 0 likes")
hotness = dweet2.hotness
dweet2.calculate_hotness(is_new=False)
self.assertEqual(hotness, dweet2.hotness, "hotness should not change with manual calc")
# Add a like and see that the hotness increases
hotness = dweet1.hotness
dweet1.likes.add(user1, user2) # note 0 and 1 like gives equal hotness
self.assertTrue(dweet1.hotness > hotness, "Hotness didn't increase when adding like")
# Remove a like and see that the hotness decreases
hotness = dweet1.hotness
dweet1.likes.remove(user2)
self.assertTrue(dweet1.hotness < hotness, "Hotness didn't decrease when removing like")
# Clear all likes and see that the hotness decreases
dweet1.likes.add(user1, user2) # note 0 and 1 like gives equal hotness
hotness = dweet1.hotness
dweet1.likes.clear()
self.assertTrue(dweet1.hotness < hotness, "Hotness didn't decrease when clearing likes")
# Newer dweets are hotter
dweet1.likes.add(user1, user2)
<|code_end|>
with the help of current file imports:
from django.test import TestCase
from django.contrib.auth.models import User
from dwitter.models import Dweet
from django.utils import timezone
from datetime import timedelta
and context from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(dweet1.likes.count(), dweet2.likes.count(), "test not set up correctly") |
Next line prediction: <|code_start|> def test_no_default_title(self):
request = self.request_factory.get('/')
request.session = {}
response = self.dweetFeed.__class__.as_view()(request, hashtag_name='everyone')
response.render()
html = response.content.decode('utf8')
self.assertNotIn('<title>' + self.dweetFeed.title + '</title>', html)
def test_got_title(self):
self.dweetFeed.kwargs = {'hashtag_name': 'everyone'}
request = self.request_factory.get('/')
request.session = {}
response = self.dweetFeed.__class__.as_view()(request, hashtag_name='everyone')
response.render()
html = response.content.decode('utf8')
self.assertIn('<title>' + self.dweetFeed.get_title() + '</title>', html)
def test_html_response(self):
request = self.request_factory.get('/')
request.session = {}
response = self.dweetFeed.__class__.as_view()(request, hashtag_name='everyone')
response.render()
html = response.content.decode('utf8')
self.assertIn('<title>', html)
class TopHashtagFeedTests(HashtagFeedTestCase, TestCase):
dweetFeed = TopHashtagFeed()
def test_top_sort(self):
<|code_end|>
. Use current file imports:
(import random
from django.http import Http404
from django.test import TestCase
from dwitter.feed.views import NewHashtagFeed, TopHashtagFeed
from dwitter.models import Comment, Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
#
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | self.dweetFeed.kwargs = {'hashtag_name': 'everyone'} |
Next line prediction: <|code_start|>
class HashtagFeedTestCase(): # Not inheriting from TestCase, an abstract test class if you will
request_factory = RequestFactory()
dweetFeed = {}
def setUp(self):
<|code_end|>
. Use current file imports:
(import random
from django.http import Http404
from django.test import TestCase
from dwitter.feed.views import NewHashtagFeed, TopHashtagFeed
from dwitter.models import Comment, Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
#
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | users = [] |
Given snippet: <|code_start|> response.render()
html = response.content.decode('utf8')
self.assertIn('<title>', html)
class TopHashtagFeedTests(HashtagFeedTestCase, TestCase):
dweetFeed = TopHashtagFeed()
def test_top_sort(self):
self.dweetFeed.kwargs = {'hashtag_name': 'everyone'}
queryset = self.dweetFeed.get_queryset()
first_dweet = queryset.first()
prev_score = first_dweet.num_likes
for dweet in queryset:
self.assertTrue(prev_score >= dweet.num_likes, "Should sort by num likes")
prev_score = dweet.num_likes
def test_annotation(self):
self.dweetFeed.kwargs = {'hashtag_name': 'everyone'}
queryset = self.dweetFeed.get_queryset()
for dweet in queryset:
num_likes = dweet.num_likes
self.assertTrue(num_likes >= 0)
class NewHashtagFeedTests(HashtagFeedTestCase, TestCase):
dweetFeed = NewHashtagFeed()
def test_new_sort(self):
self.dweetFeed.kwargs = {'hashtag_name': 'everyone'}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
from django.http import Http404
from django.test import TestCase
from dwitter.feed.views import NewHashtagFeed, TopHashtagFeed
from dwitter.models import Comment, Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
and context:
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
#
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
which might include code, classes, or functions. Output only the next line. | queryset = self.dweetFeed.get_queryset() |
Given snippet: <|code_start|>
# Add comments with some #hashtags
Comment.objects.create(id=1+i,
text="#everyone #has #this #hashtag",
posted=now - timedelta(minutes=i-1),
reply_to=dweets[i],
author=users[0])
random.seed(1337)
# add random likes between 0 and 9
for like in range(random.randrange(0, 9)):
dweets[i].likes.add(users[like])
Comment.objects.create(id=2432,
text="#Special #comment #hashtag #hash1",
posted=now,
reply_to=dweets[3],
author=users[2])
def test_404_empty_hashtag(self):
request = self.request_factory.get('/')
request.session = {}
with self.assertRaises(Http404):
self.dweetFeed.__class__.as_view()(request, hashtag_name='empty')
def test_queryset_count(self):
self.dweetFeed.kwargs = {'hashtag_name': 'everyone'}
queryset = self.dweetFeed.get_queryset()
self.assertEqual(queryset.count(), 10)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
from django.http import Http404
from django.test import TestCase
from dwitter.feed.views import NewHashtagFeed, TopHashtagFeed
from dwitter.models import Comment, Dweet
from django.test.client import RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
and context:
# Path: dwitter/feed/views.py
# class NewHashtagFeed(HashtagFeed):
# sort = SortMethod.NEW
# feed_name = "new"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "New #" + hashtag_name + " dweets | Dwitter"
#
# class TopHashtagFeed(HashtagFeed):
# sort = SortMethod.TOP
# feed_name = "top"
#
# def get_title(self):
# hashtag_name = self.kwargs['hashtag_name']
# return "Top #" + hashtag_name + " dweets | Dwitter"
#
# def get_dweet_list(self):
# return super().get_dweet_list().annotate(num_likes=Count('likes'))
#
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
which might include code, classes, or functions. Output only the next line. | self.dweetFeed.kwargs = {'hashtag_name': 'special'} |
Given the following code snippet before the placeholder: <|code_start|>
# Some automatic based on
# https://stackoverflow.com/questions/14454001/list-all-suburls-and-check-if-broken-in-python
class UrlsTest(test.TestCase):
def setUp(self):
user1 = User.objects.create(username="user1", password="qwertypw")
user1.set_password('qwertypw') # Properly hash the password
user1.save()
user2 = User.objects.create(username="user2", password="qwertypw")
<|code_end|>
, predict the next line using imports from the current file:
from django import test
from django.urls import reverse
from django.conf import settings
from django.contrib.auth.models import User
from dwitter.models import Dweet, Comment
from django.utils import timezone
from datetime import timedelta
from django.contrib import auth
import importlib
and context including class names, function names, and sometimes code from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
. Output only the next line. | user2.set_password('qwertypw') # Properly hash the password |
Next line prediction: <|code_start|>
# Some automatic based on
# https://stackoverflow.com/questions/14454001/list-all-suburls-and-check-if-broken-in-python
class UrlsTest(test.TestCase):
def setUp(self):
user1 = User.objects.create(username="user1", password="qwertypw")
user1.set_password('qwertypw') # Properly hash the password
user1.save()
user2 = User.objects.create(username="user2", password="qwertypw")
user2.set_password('qwertypw') # Properly hash the password
user2.save()
now = timezone.now()
dweet1 = Dweet.objects.create(id=1,
code="dweet1 code",
posted=now - timedelta(hours=1),
author=user1)
dweet2 = Dweet.objects.create(id=2,
<|code_end|>
. Use current file imports:
(from django import test
from django.urls import reverse
from django.conf import settings
from django.contrib.auth.models import User
from dwitter.models import Dweet, Comment
from django.utils import timezone
from datetime import timedelta
from django.contrib import auth
import importlib)
and context including class names, function names, or small code snippets from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
. Output only the next line. | code="dweet2 code", |
Given the following code snippet before the placeholder: <|code_start|>
class UserSerializer(serializers.ModelSerializer):
avatar = serializers.SerializerMethodField()
# Confirmation password, only for validation
password2 = serializers.CharField(allow_blank=False, write_only=True)
class Meta:
model = User
fields = ('id', 'avatar', 'username', 'password', 'password2', 'email')
<|code_end|>
, predict the next line using imports from the current file:
from rest_framework import serializers
from dwitter.models import Comment, Dweet
from dwitter.templatetags.to_gravatar_url import to_gravatar_url
from django.contrib.auth.models import User
from rest_framework.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
and context including class names, function names, and sometimes code from other files:
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# Path: dwitter/templatetags/to_gravatar_url.py
# @register.filter
# def to_gravatar_url(email):
# return ('https://gravatar.com/avatar/%s?d=retro' %
# hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
. Output only the next line. | extra_kwargs = { |
Here is a snippet: <|code_start|>
class UserSerializer(serializers.ModelSerializer):
avatar = serializers.SerializerMethodField()
# Confirmation password, only for validation
password2 = serializers.CharField(allow_blank=False, write_only=True)
class Meta:
model = User
fields = ('id', 'avatar', 'username', 'password', 'password2', 'email')
extra_kwargs = {
<|code_end|>
. Write the next line using the current file imports:
from rest_framework import serializers
from dwitter.models import Comment, Dweet
from dwitter.templatetags.to_gravatar_url import to_gravatar_url
from django.contrib.auth.models import User
from rest_framework.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
and context from other files:
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# Path: dwitter/templatetags/to_gravatar_url.py
# @register.filter
# def to_gravatar_url(email):
# return ('https://gravatar.com/avatar/%s?d=retro' %
# hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
, which may include functions, classes, or code. Output only the next line. | 'id': {'read_only': True}, |
Here is a snippet: <|code_start|>
class UserSerializer(serializers.ModelSerializer):
avatar = serializers.SerializerMethodField()
# Confirmation password, only for validation
password2 = serializers.CharField(allow_blank=False, write_only=True)
class Meta:
model = User
fields = ('id', 'avatar', 'username', 'password', 'password2', 'email')
extra_kwargs = {
'id': {'read_only': True},
'avatar': {'read_only': True},
'password': {'write_only': True},
'password2': {'write_only': True},
# email is not required in the database, so need to be set explicitly here
<|code_end|>
. Write the next line using the current file imports:
from rest_framework import serializers
from dwitter.models import Comment, Dweet
from dwitter.templatetags.to_gravatar_url import to_gravatar_url
from django.contrib.auth.models import User
from rest_framework.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
and context from other files:
# Path: dwitter/models.py
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# Path: dwitter/templatetags/to_gravatar_url.py
# @register.filter
# def to_gravatar_url(email):
# return ('https://gravatar.com/avatar/%s?d=retro' %
# hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
, which may include functions, classes, or code. Output only the next line. | 'email': {'write_only': True, 'required': True, |
Based on the snippet: <|code_start|>
class HashtagTestCase(TestCase):
def setUp(self):
user1 = User.objects.create(username="user1", password="")
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase
from django.contrib.auth.models import User
from dwitter.models import Dweet, Comment, Hashtag
from django.utils import timezone
from datetime import timedelta
and context (classes, functions, sometimes code) from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Hashtag(models.Model):
# name = models.CharField(max_length=30, unique=True, db_index=True)
# dweets = models.ManyToManyField(Dweet, related_name="hashtag", blank=True)
#
# def __str__(self):
# return '#' + self.name
. Output only the next line. | self.user2 = User.objects.create(username="user2", password="") |
Continue the code snippet: <|code_start|> h1 = Hashtag.objects.get(name='hash1')
h2 = Hashtag.objects.get(name='hash2')
with self.assertRaises(Hashtag.DoesNotExist):
illegal1 = Hashtag.objects.get(name='1hash')
self.assertEqual(illegal1, True)
with self.assertRaises(Hashtag.DoesNotExist):
illegal2 = Hashtag.objects.get(name='2hash')
self.assertEqual(illegal2, True)
self.assertEqual(h is None, False)
self.assertEqual(h1 is None, False)
self.assertEqual(h2 is None, False)
self.assertEqual(h.dweets.count(), 2)
self.assertEqual(h1.dweets.all()[0], self.dweet1)
self.assertEqual(h2.dweets.all()[0], self.dweet2)
def test_same_hashtag(self):
self.dweet3 = Dweet(id=3,
code="dweet3 code",
posted=timezone.now(),
reply_to=None,
author=self.user2)
self.dweet3.save()
c = Comment(id=3,
text="comment3 text #hashtag #h_3 #_3",
posted=timezone.now(),
reply_to=self.dweet3,
<|code_end|>
. Use current file imports:
from django.test import TestCase
from django.contrib.auth.models import User
from dwitter.models import Dweet, Comment, Hashtag
from django.utils import timezone
from datetime import timedelta
and context (classes, functions, or code) from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Hashtag(models.Model):
# name = models.CharField(max_length=30, unique=True, db_index=True)
# dweets = models.ManyToManyField(Dweet, related_name="hashtag", blank=True)
#
# def __str__(self):
# return '#' + self.name
. Output only the next line. | author=self.user2) |
Given the following code snippet before the placeholder: <|code_start|> with self.assertRaises(Hashtag.DoesNotExist):
illegal2 = Hashtag.objects.get(name='2hash')
self.assertEqual(illegal2, True)
self.assertEqual(h is None, False)
self.assertEqual(h1 is None, False)
self.assertEqual(h2 is None, False)
self.assertEqual(h.dweets.count(), 2)
self.assertEqual(h1.dweets.all()[0], self.dweet1)
self.assertEqual(h2.dweets.all()[0], self.dweet2)
def test_same_hashtag(self):
self.dweet3 = Dweet(id=3,
code="dweet3 code",
posted=timezone.now(),
reply_to=None,
author=self.user2)
self.dweet3.save()
c = Comment(id=3,
text="comment3 text #hashtag #h_3 #_3",
posted=timezone.now(),
reply_to=self.dweet3,
author=self.user2)
c.save()
h = Hashtag.objects.get(name='hashtag')
h3 = Hashtag.objects.get(name='h_3')
h_3 = Hashtag.objects.get(name='_3')
self.assertEqual(h is None, False)
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase
from django.contrib.auth.models import User
from dwitter.models import Dweet, Comment, Hashtag
from django.utils import timezone
from datetime import timedelta
and context including class names, function names, and sometimes code from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
#
# class Comment(models.Model):
# text = models.TextField()
# posted = models.DateTimeField()
# reply_to = models.ForeignKey(Dweet, on_delete=models.CASCADE,
# related_name="comments")
# author = models.ForeignKey(User, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('posted',)
#
# def __str__(self):
# return ('c/' +
# str(self.id) +
# ' (' +
# self.author.username +
# ') to ' +
# str(self.reply_to))
#
# class Hashtag(models.Model):
# name = models.CharField(max_length=30, unique=True, db_index=True)
# dweets = models.ManyToManyField(Dweet, related_name="hashtag", blank=True)
#
# def __str__(self):
# return '#' + self.name
. Output only the next line. | self.assertEqual(h3 is None, False) |
Based on the snippet: <|code_start|> )
def test_insert_magic_replaces_hashtag_prefix_no_space(self):
self.assertEqual(
'prefix<a href="/h/test">#test</a>',
insert_magic_links('prefix#test')
)
def test_insert_magic_replaces_hashtag_paren(self):
self.assertEqual(
'prefix(<a href="/h/test">#test</a>)',
insert_magic_links('prefix(#test)')
)
def test_insert_magic_replaces_hashtag_underscore(self):
self.assertEqual(
'Dwitter is just <a href="/h/amazing_underscore">#amazing_underscore</a>, right?',
insert_magic_links('Dwitter is just #amazing_underscore, right?')
)
def test_insert_magic_replaces_hashtag_illegal_hyphen(self):
self.assertEqual(
'Dwitter is just <a href="/h/amaze">#amaze</a>-balls, right?',
insert_magic_links('Dwitter is just #amaze-balls, right?')
)
def test_insert_magic_hashtag_not_start_with_digit(self):
self.assertEqual(
'Dwitter is just #1337 or <a href="/h/super1337">#super1337</a>?',
insert_magic_links('Dwitter is just #1337 or #super1337?')
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase
from dwitter.templatetags.insert_magic_links import insert_magic_links
and context (classes, functions, sometimes code) from other files:
# Path: dwitter/templatetags/insert_magic_links.py
# @register.filter(is_safe=True)
# def insert_magic_links(text):
# text = re.sub(
# r'(?:^|(?<=\s))' # start of string or whitespace
# r'/?' # optional /
# r'(?P<text>' # capture original pattern
# r'[^a-zA-Z\d]?d/(?P<dweet_id>\d+)[^a-zA-Z]?' # dweet reference
# r'|' # or
# r'[^a-zA-Z\d]?u/(?P<username>[\w.@+-]+)[^a-zA-Z\d]?)' # user reference
# r'(?=$|\s|#)', # end of string, whitespace or hashtag
# user_dweet_to_link,
# text
# )
# text = re.sub(
# r'(?P<text>' # capture original pattern
# # (?:^|\s) # go to the start of the line or the next space
# # (?=\S*#) # lookahead to see is there a '#' after a bunch of non-whitespace characters?
# # (?!\S*:) # lookahead to check aren't any ':' characters there
# # (otherwise it's likely an anchor)
# # \S*# # skip any of the characters leading up to the '#'
# # then do the hashtag grouping that was there before:
# # (?P<hashtag>[_a-zA-Z][_a-zA-Z\d]*)
# r'(?:^|\s)(?=\S*#)(?!\S*:)\S*#(?P<hashtag>[_a-zA-Z][_a-zA-Z\d]*))',
# hashtag_to_link,
# text
# )
# return text
. Output only the next line. | ) |
Based on the snippet: <|code_start|> return self.client.post(f'{APIV2_PATH}/dweets/',
{'code': code, 'first-comment': comment},
content_type='application/json',
HTTP_AUTHORIZATION='token ' + token)
def post_comment(self, token, dweet_id, comment):
return self.client.post(f'{APIV2_PATH}/dweets/{dweet_id}/add_comment/',
{'text': comment},
content_type='application/json',
HTTP_AUTHORIZATION='token ' + token)
def set_like(self, token, dweet_id, like):
return self.client.post(f'{APIV2_PATH}/dweets/{dweet_id}/set_like/',
{'like': like},
content_type='application/json',
HTTP_AUTHORIZATION='token ' + token)
def get_dweet(self, dweet_id):
return self.client.get(f'{APIV2_PATH}/dweets/{dweet_id}/',
content_type='application/json')
def get_dweets(self):
return self.client.get(f'{APIV2_PATH}/dweets/',
content_type='application/json')
class Api2DweetAndCommentCreateTestCase(Api2BaseTestCase):
def setUp(self):
self.client = Client()
self.user1 = User.objects.create_user(
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import Client, TransactionTestCase
from django.contrib.auth.models import User
from django.utils import timezone
from dwitter.models import Dweet
import json
and context (classes, functions, sometimes code) from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | username='user1', |
Given the code snippet: <|code_start|>
def assertResponse(self, response=None, status_code=None, templates=None):
self.assertEqual(response.status_code, status_code)
self.assertEqual([template.name for template in response.templates],
templates)
class DweetTestCase(TransactionTestCase):
def setUp(self):
self.client = Client(HTTP_HOST='dweet.localhost:8000')
self.user = User.objects.create(username="user", password="")
self.dweet = Dweet.objects.create(id=1,
code="dweet code",
posted=timezone.now(),
<|code_end|>
, generate the next line using the imports in this file:
from django.test import TransactionTestCase, Client
from django.contrib.auth.models import User
from dwitter.models import Dweet
from django.utils import timezone
and context (functions, classes, or occasionally code) from other files:
# Path: dwitter/models.py
# class Dweet(models.Model):
# code = models.TextField()
# posted = models.DateTimeField(db_index=True)
# reply_to = models.ForeignKey("self", on_delete=models.DO_NOTHING,
# related_name="remixes", null=True, blank=True)
#
# likes = models.ManyToManyField(User, related_name="liked", blank=True)
# hotness = models.FloatField(default=1.0, db_index=True)
# deleted = models.BooleanField(default=False)
#
# author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user),
# null=True, blank=True)
#
# objects = NotDeletedDweetManager()
# with_deleted = models.Manager()
#
# class Meta:
# ordering = ('-posted',)
#
# def delete(self):
# self.deleted = True
# self.save()
#
# def save(self, *args, **kwargs):
# self.calculate_hotness((self.pk is None))
# super(Dweet, self).save(*args, **kwargs)
#
# @cached_property
# def top_comment(self):
# """
# Return the top comment. This is mainly a caching optimization to avoid queries
# """
# return self.comments.first()
#
# @cached_property
# def dweet_length(self):
# return length_of_code(self.code)
#
# @cached_property
# def has_sticky_comment(self):
# """
# True when first comment should be stickied (first comment author == dweet author)
# """
# if self.top_comment is None:
# return False
# return self.top_comment.author == self.author
#
# def __str__(self):
# return 'd/' + str(self.id) + ' (' + self.author.username + ')'
#
# def calculate_hotness(self, is_new):
# """
# Hotness is inspired by the Hackernews ranking algorithm
# Read more here:
# https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
# """
# def epoch_seconds(date):
# epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
# naive = date.replace(tzinfo=None)
# td = naive - epoch
# return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
#
# likes = 1
# if not is_new:
# likes = max(self.likes.count(), 1)
#
# order = log(likes, 2)
# # 86400 seconds = 24 hours.
# # So for every log(2) likes on a dweet, its effective
# # "posted time" moves 24 forward
# # In other words, it takes log2(likes) * 24hrs before
# # a dweet with a single like beat yours
# self.hotness = round(order + epoch_seconds(self.posted)/86400, 7)
. Output only the next line. | author=self.user) |
Given snippet: <|code_start|>
class DweetTestCase(TestCase):
def test_insert_code_blocks_wraps_stuff_inside_backticks(self):
self.assertEqual(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from dwitter.templatetags.insert_code_blocks import insert_code_blocks
and context:
# Path: dwitter/templatetags/insert_code_blocks.py
# @register.filter
# def insert_code_blocks(text):
# result = re.sub(
# r'`' # start with `
# r'(?P<code>.*?)' # capture code block
# r'(?<!\\)' # not preceded by \
# r'`', # end with `
# to_code_block,
# text
# )
# return mark_safe(result)
which might include code, classes, or functions. Output only the next line. | '<code>a</code>', |
Given the following code snippet before the placeholder: <|code_start|>"Commonly-used date structures"
WEEKDAYS = {
0:_('Monday'), 1:_('Tuesday'), 2:_('Wednesday'), 3:_('Thursday'), 4:_('Friday'),
5:_('Saturday'), 6:_('Sunday')
}
WEEKDAYS_ABBR = {
0:_('Mon'), 1:_('Tue'), 2:_('Wed'), 3:_('Thu'), 4:_('Fri'),
5:_('Sat'), 6:_('Sun')
}
WEEKDAYS_REV = {
'monday':0, 'tuesday':1, 'wednesday':2, 'thursday':3, 'friday':4,
'saturday':5, 'sunday':6
}
MONTHS = {
1:_('January'), 2:_('February'), 3:_('March'), 4:_('April'), 5:_('May'), 6:_('June'),
7:_('July'), 8:_('August'), 9:_('September'), 10:_('October'), 11:_('November'),
12:_('December')
}
MONTHS_3 = {
1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'), 5:_('may'), 6:_('jun'),
7:_('jul'), 8:_('aug'), 9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec')
}
MONTHS_3_REV = {
'jan':1, 'feb':2, 'mar':3, 'apr':4, 'may':5, 'jun':6, 'jul':7, 'aug':8,
'sep':9, 'oct':10, 'nov':11, 'dec':12
}
<|code_end|>
, predict the next line using imports from the current file:
from floyd.util.translation import ugettext as _
and context including class names, function names, and sometimes code from other files:
# Path: floyd/util/translation.py
# def ugettext(str, format=unicode):
# return force_unicode(str)
. Output only the next line. | MONTHS_AP = { # month names in Associated Press style |
Given the following code snippet before the placeholder: <|code_start|>"""
base_tasks.py: Contains the Task classes that interface between the LSST/HSC pipeline and the systematics tests
described by Stile. At the moment, we use some functionality that is only available on the HSC
side of the pipeline, but eventually this will be usable for both.
"""
# So we can cut too-long path names. This assumes that the machine where the code is stored has the
# same settings as the machine where the files will be placed, but I think this is a safe assumption
# for most HSC use cases.
max_path_length = os.pathconf('.', 'PC_NAME_MAX')
parser_description = """
This is a script to run Stile through the LSST/HSC pipeline.
You can configure which systematic tests to run by setting the following option.
From command line, add ::
-c "sys_tests.names=['TEST_NAME1', 'TEST_NAME2', ...]"
You can also specify this option by writing a file, e.g., ::
====================== config.py ======================
import stile.lsst.base_tasks
root.sys_tests.names=['TEST_NAME1', 'TEST_NAME2', ...]
<|code_end|>
, predict the next line using imports from the current file:
import os
import lsst.pex.config
import lsst.pipe.base
import lsst.meas.mosaic
import lsst.afw.geom as afwGeom
import lsst.afw.image as afwImage
import lsst.afw.table as afwTable
import lsst.afw.cameraGeom as cameraGeom
import lsst.afw.cameraGeom.utils as cameraGeomUtils
import numpy
import re
import stile
from lsst.meas.mosaic.mosaicTask import MosaicTask
from lsst.pipe.tasks.dataIds import PerTractCcdDataIdContainer
from lsst.pipe.tasks.coaddBase import ExistingCoaddDataIdContainer
from lsst.pex.exceptions import LsstCppException
from .sys_test_adapters import adapter_registry
and context including class names, function names, and sometimes code from other files:
# Path: stile/hsc/sys_test_adapters.py
# def MaskGalaxy(data, config):
# def MaskStar(data, config):
# def MaskBrightStar(data, config):
# def MaskPSFStar(data, config):
# def setupMasks(self, objects_list=None):
# def getMasks(self, data, config):
# def getRequiredColumns(self):
# def __call__(self, task_config, *data, **kwargs):
# def getRequiredColumns(self):
# def fixArray(self, array):
# def __call__(self, task_config, *data, **kwargs):
# def __init__(self, config):
# def __init__(self, config):
# def __init__(self, config):
# def __init__(self, config):
# def __init__(self, config):
# def __init__(self, config):
# def __init__(self, config):
# def MaskPSFFlux(self, data, config):
# def getRequiredColumns(self):
# def __call__(self, task_config, *data, **kwargs):
# def __init__(self, config):
# def __call__(self, task_config, *data):
# def __init__(self, config):
# def __call__(self, task_config, *data):
# def __init__(self, config):
# def __call__(self, task_config, *data):
# def __init__(self, config):
# def __call__(self, task_config, *data, **kwargs):
# def __init__(self, config):
# def __call__(self, task_config, *data, **kwargs):
# def __init__(self, config):
# def __call__(self, task_config, *data, **kwargs):
# def __init__(self, config):
# def __call__(self, task_config, *data, **kwargs):
# def __init__(self, config):
# def __call__(self, task_config, *data, **kwargs):
# def __init__(self, config):
# def __call__(self, task_config, *data, **kwargs):
# def __init__(self, config):
# def __call__(self, task_config, *data, **kwargs):
# class BaseSysTestAdapter(object):
# class ShapeSysTestAdapter(BaseSysTestAdapter):
# class GalaxyShearAdapter(ShapeSysTestAdapter):
# class BrightStarShearAdapter(ShapeSysTestAdapter):
# class StarXGalaxyShearAdapter(ShapeSysTestAdapter):
# class StarXStarShearAdapter(ShapeSysTestAdapter):
# class StarXStarSizeResidualAdapter(ShapeSysTestAdapter):
# class Rho1Adapter(ShapeSysTestAdapter):
# class StatsPSFFluxAdapter(ShapeSysTestAdapter):
# class WhiskerPlotStarAdapter(ShapeSysTestAdapter):
# class WhiskerPlotPSFAdapter(ShapeSysTestAdapter):
# class WhiskerPlotResidualAdapter(ShapeSysTestAdapter):
# class ScatterPlotStarVsPSFG1Adapter(ShapeSysTestAdapter):
# class ScatterPlotStarVsPSFG2Adapter(ShapeSysTestAdapter):
# class ScatterPlotStarVsPSFSigmaAdapter(ShapeSysTestAdapter):
# class ScatterPlotResidualVsPSFG1Adapter(ShapeSysTestAdapter):
# class ScatterPlotResidualVsPSFG2Adapter(ShapeSysTestAdapter):
# class ScatterPlotResidualVsPSFSigmaAdapter(ShapeSysTestAdapter):
# class ScatterPlotResidualSigmaVsPSFMagAdapter(ShapeSysTestAdapter):
. Output only the next line. | ======================================================= |
Predict the next line for this snippet: <|code_start|> data_server_group = OptionGroup(parser,
"Data Server Options",
"These options control various aspects of the data server, which serves data to the UI server.")
ui_server_group = OptionGroup(parser,
"UI Server Options",
"These options control various aspects of the UI server, which serves the frontend of Firefly.")
test_mode_help = """\
Runs in test mode:
1. Add a test data server and data source.
2. Making code changes will automatically restart the server."""
parser.add_option('-c',
'--config',
dest='config_file',
default=None,
help="Specify a configuration file to read from.")
parser.add_option('--loggingconf',
dest='loggingconf',
default=None,
help="Specify a configuration file for logging.")
parser.add_option('--testing',
dest='testing',
action='store_true',
default=False,
help=test_mode_help)
parser.add_option('--no-data-server',
dest="omit_data_server",
action="store_true",
default=config.get('omit_data_server', False),
help="Disable the data server.")
<|code_end|>
with the help of current file imports:
from collections import defaultdict
from optparse import OptionGroup, OptionParser
from firefly.data_server import initialize_data_server
from firefly.ui_server import initialize_ui_server
import logging
import os
import socket
import sys
import util
import tornado.ioloop
import yaml
and context from other files:
# Path: firefly/data_server.py
# def initialize_data_server(config_global, secret_key=None):
# config = config_global["data_server"]
#
# # connect to the database to store annotation in
# # I kind of hate having the schema for this DB here, but I'm going to leave it for to retain parity with ui_server.py
# db_conn = sqlite3.connect(config['db_file'], isolation_level=None)
# db_conn.execute("""
# create table if not exists annotations (
# id integer primary key autoincrement,
# type integer not null,
# description text not null,
# time float not null
# )""")
# db_conn.execute("create index if not exists time on annotations(time)")
#
# config['db'] = db_conn
# config["secret_key"] = secret_key
#
# # init the application instance
# application = tornado.web.Application([
# (r"/data", DataHandler),
# (r"/legend", GraphLegendHandler),
# (r"/title", GraphTitleHandler),
# (r"/ping", PingHandler),
# (r"/annotations", AnnotationsHandler),
# (r"/add_annotation", AddAnnotationHandler),
# (r"/sources", SourcesHandler)], **config)
#
# # start the main server
# http_server = tornado.httpserver.HTTPServer(application)
# http_server.bind(config["port"])
# http_server.start(0)
#
# # setup logging
# util.setup_logging(config_global)
#
# log.info('Firefly data server started on port %d' % config["port"])
#
# Path: firefly/ui_server.py
# def initialize_ui_server(config_global, secret_key=None):
# config = config_global["ui_server"]
#
# # connect to the database
# conn = sqlite3.connect(config['db_file'], isolation_level=None)
# conn.execute("create table if not exists states (id integer primary key autoincrement, state text not null, state_hash blob not null)")
# conn.execute("create index if not exists hash_idx on states(state_hash)")
# conn.execute("create table if not exists names (id integer primary key autoincrement, name text not null, stateid integer not null)")
# conn.execute("create unique index if not exists name_idx on names (name)")
#
# config["static_path"] = os.path.join(os.path.join(*os.path.split(__file__)[:-1]), 'static')
# config["db_connection"] = conn
# config["static_url_prefix"] = os.path.join(config["url_path_prefix"], "static") + "/"
# config["secret_key"] = secret_key
# config['autoescape'] = None
#
# # init the application instance
# application = tornado.web.Application([
# (r"/", IndexHandler),
# (r"/token", TokenHandler),
# (r"/shorten", ShortenHandler),
# (r"/expand/(.*)", ExpandHandler),
# (r"/redirect/(.*)", RedirectHandler),
# (r"/named/(.*)", NameHandler),
# (r"/dashboards", DashboardListHandler),
# (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": config['static_path']}),
# ], **config)
#
# # start the main server
# http_server = tornado.httpserver.HTTPServer(application)
# http_server.listen(config["port"])
#
# # setup logging
# util.setup_logging(config_global)
#
# log.info('Firefly UI server started on port %d' % config["port"])
, which may contain function names, class names, or code. Output only the next line. | parser.add_option('--no-ui-server', |
Given the following code snippet before the placeholder: <|code_start|> dest='dataserver_db_file',
default=default_data_server_opts.get('db_file', os.path.join('data', 'data_server.sqlite')),
help='SQLite database file to keep data server information in')
ui_server_group.add_option('--uiserver-port',
dest='uiserver_port',
default=default_ui_server_opts.get('port', 8889),
help='Port to listen on (default %default)')
ui_server_group.add_option('--uiserver-db-file',
dest='uiserver_db_file',
default=default_ui_server_opts.get('db_file', os.path.join('data', 'ui_server.sqlite')),
help='SQLite database file to keep UI server information in')
ui_server_group.add_option('--url-path-prefix',
dest='url_path_prefix',
default=default_ui_server_opts.get('url_path_prefix', '/firefly/'),
help="URL prefix to use")
parser.add_option_group(data_server_group)
parser.add_option_group(ui_server_group)
options, args = parser.parse_args()
# Make sure we don't get some weird conditions, like disabling
# both the UI and the data server
if options.omit_data_server and options.omit_ui_server:
parser.error("--no-data-server and --no-ui-server both specified!")
if options.config_file:
config = load_config_from_file(options.config_file)
else:
<|code_end|>
, predict the next line using imports from the current file:
from collections import defaultdict
from optparse import OptionGroup, OptionParser
from firefly.data_server import initialize_data_server
from firefly.ui_server import initialize_ui_server
import logging
import os
import socket
import sys
import util
import tornado.ioloop
import yaml
and context including class names, function names, and sometimes code from other files:
# Path: firefly/data_server.py
# def initialize_data_server(config_global, secret_key=None):
# config = config_global["data_server"]
#
# # connect to the database to store annotation in
# # I kind of hate having the schema for this DB here, but I'm going to leave it for to retain parity with ui_server.py
# db_conn = sqlite3.connect(config['db_file'], isolation_level=None)
# db_conn.execute("""
# create table if not exists annotations (
# id integer primary key autoincrement,
# type integer not null,
# description text not null,
# time float not null
# )""")
# db_conn.execute("create index if not exists time on annotations(time)")
#
# config['db'] = db_conn
# config["secret_key"] = secret_key
#
# # init the application instance
# application = tornado.web.Application([
# (r"/data", DataHandler),
# (r"/legend", GraphLegendHandler),
# (r"/title", GraphTitleHandler),
# (r"/ping", PingHandler),
# (r"/annotations", AnnotationsHandler),
# (r"/add_annotation", AddAnnotationHandler),
# (r"/sources", SourcesHandler)], **config)
#
# # start the main server
# http_server = tornado.httpserver.HTTPServer(application)
# http_server.bind(config["port"])
# http_server.start(0)
#
# # setup logging
# util.setup_logging(config_global)
#
# log.info('Firefly data server started on port %d' % config["port"])
#
# Path: firefly/ui_server.py
# def initialize_ui_server(config_global, secret_key=None):
# config = config_global["ui_server"]
#
# # connect to the database
# conn = sqlite3.connect(config['db_file'], isolation_level=None)
# conn.execute("create table if not exists states (id integer primary key autoincrement, state text not null, state_hash blob not null)")
# conn.execute("create index if not exists hash_idx on states(state_hash)")
# conn.execute("create table if not exists names (id integer primary key autoincrement, name text not null, stateid integer not null)")
# conn.execute("create unique index if not exists name_idx on names (name)")
#
# config["static_path"] = os.path.join(os.path.join(*os.path.split(__file__)[:-1]), 'static')
# config["db_connection"] = conn
# config["static_url_prefix"] = os.path.join(config["url_path_prefix"], "static") + "/"
# config["secret_key"] = secret_key
# config['autoescape'] = None
#
# # init the application instance
# application = tornado.web.Application([
# (r"/", IndexHandler),
# (r"/token", TokenHandler),
# (r"/shorten", ShortenHandler),
# (r"/expand/(.*)", ExpandHandler),
# (r"/redirect/(.*)", RedirectHandler),
# (r"/named/(.*)", NameHandler),
# (r"/dashboards", DashboardListHandler),
# (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": config['static_path']}),
# ], **config)
#
# # start the main server
# http_server = tornado.httpserver.HTTPServer(application)
# http_server.listen(config["port"])
#
# # setup logging
# util.setup_logging(config_global)
#
# log.info('Firefly UI server started on port %d' % config["port"])
. Output only the next line. | config = { |
Given the following code snippet before the placeholder: <|code_start|> "context": {},
"text" : "io_wait",
"expandable": 0,
"id": "io_wait",
"allowChildren": 0
}
]
"""
mock_urlopen.return_value = mock_response
result = self.ds.list_path(path=['a','b','c'])
T.assert_equal(1, len(result))
expected_servers_dict = {'type': 'file', 'name': u'io_wait'}
T.assert_dicts_equal(expected_servers_dict, result[0])
mock_urlopen.assert_called_with(match(starts_with('http://dontcare.com:8080/metrics/find')))
mock_urlopen.assert_called_with(match(contains_string('query=a.b.c.*')))
def test_list_path_with_non_leaf(self):
"""
Given
a path that contains a single non-leaf child node
When
path is listed
Then
return a single non-leaf node
"""
with patch_urlopen() as mock_urlopen:
mock_response = Mock()
mock_response.read.return_value = """
[
{
<|code_end|>
, predict the next line using imports from the current file:
from contextlib import contextmanager
from cStringIO import StringIO
from mock import Mock
from firefly.data_sources.graphite_http import GraphiteHTTP
from firefly import util
from hamcrest import starts_with
from hamcrest import contains_string
import json
import hamcrest
import mock
import urllib2
import urlparse
import testify as T
and context including class names, function names, and sometimes code from other files:
# Path: firefly/data_sources/graphite_http.py
# class GraphiteHTTP(firefly.data_source.DataSource):
# """
# Stats from graphite-web's HTTP endpoint
#
# :param graphite_url: Graphite-web URL
# """
# DESC = "GraphiteHTTP"
#
# def __init__(self, *args, **kwargs):
# super(GraphiteHTTP, self).__init__(*args, **kwargs)
# self.graphite_url = kwargs['graphite_url']
#
# def list_path(self, path):
# """
# Given a graphite metric name split up into it's segments,
# return a list of the next possible segments.
#
# Sample input entry from graphite:
# {
# "leaf": 0,
# "context": {},
# "text": "activemq",
# "expandable": 1,
# "id": "activemq",
# "allowChildren": 1
# }
#
# Sample output entry to firely:
# {
# 'type': 'dir',
# 'name': name,
# 'children': None
# }
#
# :param path: list of path components as strings
# :return: list of dicts containing the path entries
# """
# params = {
# 'query' : '.'.join(path + ['*']),
# 'format': 'treejson',
# }
# find_url = urljoin(self.graphite_url, 'metrics/find/?%s' % '&'.join(['%s=%s' % (k,v) for k,v in params.items()]))
# find_json = urlopen(find_url).read()
# find_results = json.loads(find_json)
#
# contents = list()
# for result in sorted(find_results, key=lambda result: result['text']):
# if result['leaf'] == 0:
# contents.extend(self._form_entries_from_dir(result['text']))
# elif result['leaf'] == 1:
# contents.extend(self._form_entries_from_file(result['text']))
# else:
# raise Exception('Unexpected value for leaf in result: %s' % result)
# return contents
#
# def _form_entries_from_dir(self, name):
# return [{'type': 'dir', 'name': name, 'children': None}]
#
# def _form_entries_from_file(self, name):
# return [{'type': 'file', 'name': name}]
#
# def data(self, sources, start, end, width):
# """
# :param sources: list of list of path segments
# :param start: timestamp like 1391044540
# :param end: timestamp like 1391048200
# :param width: ignored
# :return: json string
# """
# # Unfortunately, the most granular unit of time that graphite supports via this API is minute.
# fmt = '%H:%M_%Y%m%d'
# from_str = datetime.fromtimestamp(start).strftime(fmt)
# until_str = datetime.fromtimestamp(end).strftime(fmt)
#
# serieses = []
# step = None
#
# # TODO: Minimize the number of http calls -- handle multiple sources in a single call
# for metric_segments in sources:
# metric_name = '.'.join(metric_segments)
# params = {
# 'target': metric_name,
# 'format': 'json',
# 'from' : from_str,
# 'until': until_str,
# }
# render_url = urljoin(self.graphite_url, 'render/?%s' % '&'.join(['%s=%s' % (k,v) for k,v in params.items()]))
# render_json = urlopen(render_url).read()
# render_results = json.loads(render_json)
#
# values = []
# for result in render_results:
# for datapoint in result['datapoints']:
# values.append(datapoint[0])
#
# # Compute step and make sure it is consistent across all metrics
# current_step = (end - start) / (len(values) - 1)
# if step is None:
# step = current_step
# elif current_step != step:
# self.logger.error('Number of values from two different serieses does not match! %s != %s' % (step, current_step))
# serieses.append(values)
#
# out = []
# for timestamp, values in izip(xrange(start, end+step, step), izip(*serieses)):
# out.append({'t': timestamp, 'v': [v for v in values]})
# return json.dumps(out)
#
# def legend(self, sources):
# return self._svc(sources)
#
# def title(self, sources):
# return ["graphite_http"]
#
# Path: firefly/util.py
# def last_dot_splitter(dotted_path):
# def import_module_class(dotted_path):
# def import_module(dotted_path):
# def setup_logging(config):
# def verify_access_token(token, key):
# def generate_access_token(key, duration=60):
# def generate_ds_key(ds):
# def b58encode(value):
# def b58decode(encoded):
. Output only the next line. | "leaf": 0, |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: bucket.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-05-13 16:36:36 (CST)
# Last Update: Monday 2019-09-23 17:11:18 (CST)
# By:
# Description:
# ********************************************************************************
class BucketListView(AuthMethodView):
def get(self):
data = request.data
user = request.user
page, number = self.pageinfo
params = filter_maybe(data, {"name": "name__contains"})
ins = user.buckets.filter_by(**params).paginate(page, number)
serializer = BucketSerializer(ins)
return HTTP.OK(data=serializer.data)
@check_params(["name"])
<|code_end|>
using the current file's imports:
from flask import request
from flask_maple.response import HTTP
from maple.utils import AuthMethodView
from maple.storage.db import Bucket
from maple.storage.serializer import BucketSerializer
from maple.utils import check_params, filter_maybe, update_maybe
and any relevant context from other files:
# Path: maple/utils.py
# class AuthMethodView(MethodView):
# decorators = (login_required, )
#
# Path: maple/storage/db.py
# class Bucket(ModelUserMixin, db.Model):
# __tablename__ = 'bucket'
#
# name = db.Column(db.String(108), nullable=False, unique=True)
# description = db.Column(db.String(1024), default='default')
#
# def get_root_path(self, path, create=False):
# filepath = self.rootpath
# for name in path.split("/"):
# if name == "":
# continue
# childpath = filepath.child_paths.filter_by(
# name=name,
# bucket_id=self.id,
# ).first()
# if not childpath and not create:
# return
#
# if not childpath and create:
# childpath = FilePath(
# name=name,
# bucket_id=self.id,
# parent_id=filepath.id,
# )
# childpath.save()
# filepath = childpath
# return filepath
#
# @property
# def rootpath(self):
# filepath = self.paths.filter_by(name="/").first()
# if not filepath:
# filepath = FilePath(name="/", bucket_id=self.id)
# filepath.save()
# return filepath
#
# @property
# def abspath(self):
# return os.path.join(config.UPLOAD_FOLDER, self.name)
#
# @property
# def relpath(self):
# return os.path.join(self.name)
#
# def __repr__(self):
# return '<Bucket %r>' % self.name
#
# def __str__(self):
# return self.name
#
# Path: maple/storage/serializer.py
# class BucketSerializer(Serializer):
# class Meta:
# exclude = ["paths"]
#
# Path: maple/utils.py
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# def update_maybe(ins, request_data, columns):
# for column in columns:
# value = request_data.get(column)
# if value:
# setattr(ins, column, value)
# return ins
. Output only the next line. | def post(self): |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: bucket.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-05-13 16:36:36 (CST)
# Last Update: Monday 2019-09-23 17:11:18 (CST)
# By:
# Description:
# ********************************************************************************
class BucketListView(AuthMethodView):
def get(self):
data = request.data
user = request.user
page, number = self.pageinfo
params = filter_maybe(data, {"name": "name__contains"})
<|code_end|>
. Use current file imports:
(from flask import request
from flask_maple.response import HTTP
from maple.utils import AuthMethodView
from maple.storage.db import Bucket
from maple.storage.serializer import BucketSerializer
from maple.utils import check_params, filter_maybe, update_maybe)
and context including class names, function names, or small code snippets from other files:
# Path: maple/utils.py
# class AuthMethodView(MethodView):
# decorators = (login_required, )
#
# Path: maple/storage/db.py
# class Bucket(ModelUserMixin, db.Model):
# __tablename__ = 'bucket'
#
# name = db.Column(db.String(108), nullable=False, unique=True)
# description = db.Column(db.String(1024), default='default')
#
# def get_root_path(self, path, create=False):
# filepath = self.rootpath
# for name in path.split("/"):
# if name == "":
# continue
# childpath = filepath.child_paths.filter_by(
# name=name,
# bucket_id=self.id,
# ).first()
# if not childpath and not create:
# return
#
# if not childpath and create:
# childpath = FilePath(
# name=name,
# bucket_id=self.id,
# parent_id=filepath.id,
# )
# childpath.save()
# filepath = childpath
# return filepath
#
# @property
# def rootpath(self):
# filepath = self.paths.filter_by(name="/").first()
# if not filepath:
# filepath = FilePath(name="/", bucket_id=self.id)
# filepath.save()
# return filepath
#
# @property
# def abspath(self):
# return os.path.join(config.UPLOAD_FOLDER, self.name)
#
# @property
# def relpath(self):
# return os.path.join(self.name)
#
# def __repr__(self):
# return '<Bucket %r>' % self.name
#
# def __str__(self):
# return self.name
#
# Path: maple/storage/serializer.py
# class BucketSerializer(Serializer):
# class Meta:
# exclude = ["paths"]
#
# Path: maple/utils.py
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# def update_maybe(ins, request_data, columns):
# for column in columns:
# value = request_data.get(column)
# if value:
# setattr(ins, column, value)
# return ins
. Output only the next line. | ins = user.buckets.filter_by(**params).paginate(page, number) |
Using the snippet: <|code_start|>
params = filter_maybe(data, {"name": "name__contains"})
ins = user.buckets.filter_by(**params).paginate(page, number)
serializer = BucketSerializer(ins)
return HTTP.OK(data=serializer.data)
@check_params(["name"])
def post(self):
data = request.data
name = data.get('name')
description = data.get('description')
if Bucket.query.filter_by(name=name).exists():
return HTTP.BAD_REQUEST(message="bucket is exists")
bucket = Bucket(name=name)
if description:
bucket.description = description
bucket.save()
rep = BucketSerializer(bucket).data
return HTTP.OK(data=rep)
class BucketView(AuthMethodView):
def get(self, pk):
user = request.user
ins = user.buckets.filter_by(id=pk).get_or_404("bucket not found")
rep = BucketSerializer(ins).data
return HTTP.OK(data=rep)
<|code_end|>
, determine the next line of code. You have imports:
from flask import request
from flask_maple.response import HTTP
from maple.utils import AuthMethodView
from maple.storage.db import Bucket
from maple.storage.serializer import BucketSerializer
from maple.utils import check_params, filter_maybe, update_maybe
and context (class names, function names, or code) available:
# Path: maple/utils.py
# class AuthMethodView(MethodView):
# decorators = (login_required, )
#
# Path: maple/storage/db.py
# class Bucket(ModelUserMixin, db.Model):
# __tablename__ = 'bucket'
#
# name = db.Column(db.String(108), nullable=False, unique=True)
# description = db.Column(db.String(1024), default='default')
#
# def get_root_path(self, path, create=False):
# filepath = self.rootpath
# for name in path.split("/"):
# if name == "":
# continue
# childpath = filepath.child_paths.filter_by(
# name=name,
# bucket_id=self.id,
# ).first()
# if not childpath and not create:
# return
#
# if not childpath and create:
# childpath = FilePath(
# name=name,
# bucket_id=self.id,
# parent_id=filepath.id,
# )
# childpath.save()
# filepath = childpath
# return filepath
#
# @property
# def rootpath(self):
# filepath = self.paths.filter_by(name="/").first()
# if not filepath:
# filepath = FilePath(name="/", bucket_id=self.id)
# filepath.save()
# return filepath
#
# @property
# def abspath(self):
# return os.path.join(config.UPLOAD_FOLDER, self.name)
#
# @property
# def relpath(self):
# return os.path.join(self.name)
#
# def __repr__(self):
# return '<Bucket %r>' % self.name
#
# def __str__(self):
# return self.name
#
# Path: maple/storage/serializer.py
# class BucketSerializer(Serializer):
# class Meta:
# exclude = ["paths"]
#
# Path: maple/utils.py
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# def update_maybe(ins, request_data, columns):
# for column in columns:
# value = request_data.get(column)
# if value:
# setattr(ins, column, value)
# return ins
. Output only the next line. | def put(self, pk): |
Using the snippet: <|code_start|> ins = user.buckets.filter_by(**params).paginate(page, number)
serializer = BucketSerializer(ins)
return HTTP.OK(data=serializer.data)
@check_params(["name"])
def post(self):
data = request.data
name = data.get('name')
description = data.get('description')
if Bucket.query.filter_by(name=name).exists():
return HTTP.BAD_REQUEST(message="bucket is exists")
bucket = Bucket(name=name)
if description:
bucket.description = description
bucket.save()
rep = BucketSerializer(bucket).data
return HTTP.OK(data=rep)
class BucketView(AuthMethodView):
def get(self, pk):
user = request.user
ins = user.buckets.filter_by(id=pk).get_or_404("bucket not found")
rep = BucketSerializer(ins).data
return HTTP.OK(data=rep)
def put(self, pk):
user = request.user
<|code_end|>
, determine the next line of code. You have imports:
from flask import request
from flask_maple.response import HTTP
from maple.utils import AuthMethodView
from maple.storage.db import Bucket
from maple.storage.serializer import BucketSerializer
from maple.utils import check_params, filter_maybe, update_maybe
and context (class names, function names, or code) available:
# Path: maple/utils.py
# class AuthMethodView(MethodView):
# decorators = (login_required, )
#
# Path: maple/storage/db.py
# class Bucket(ModelUserMixin, db.Model):
# __tablename__ = 'bucket'
#
# name = db.Column(db.String(108), nullable=False, unique=True)
# description = db.Column(db.String(1024), default='default')
#
# def get_root_path(self, path, create=False):
# filepath = self.rootpath
# for name in path.split("/"):
# if name == "":
# continue
# childpath = filepath.child_paths.filter_by(
# name=name,
# bucket_id=self.id,
# ).first()
# if not childpath and not create:
# return
#
# if not childpath and create:
# childpath = FilePath(
# name=name,
# bucket_id=self.id,
# parent_id=filepath.id,
# )
# childpath.save()
# filepath = childpath
# return filepath
#
# @property
# def rootpath(self):
# filepath = self.paths.filter_by(name="/").first()
# if not filepath:
# filepath = FilePath(name="/", bucket_id=self.id)
# filepath.save()
# return filepath
#
# @property
# def abspath(self):
# return os.path.join(config.UPLOAD_FOLDER, self.name)
#
# @property
# def relpath(self):
# return os.path.join(self.name)
#
# def __repr__(self):
# return '<Bucket %r>' % self.name
#
# def __str__(self):
# return self.name
#
# Path: maple/storage/serializer.py
# class BucketSerializer(Serializer):
# class Meta:
# exclude = ["paths"]
#
# Path: maple/utils.py
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# def update_maybe(ins, request_data, columns):
# for column in columns:
# value = request_data.get(column)
# if value:
# setattr(ins, column, value)
# return ins
. Output only the next line. | data = request.data |
Continue the code snippet: <|code_start|>class BucketListView(AuthMethodView):
def get(self):
data = request.data
user = request.user
page, number = self.pageinfo
params = filter_maybe(data, {"name": "name__contains"})
ins = user.buckets.filter_by(**params).paginate(page, number)
serializer = BucketSerializer(ins)
return HTTP.OK(data=serializer.data)
@check_params(["name"])
def post(self):
data = request.data
name = data.get('name')
description = data.get('description')
if Bucket.query.filter_by(name=name).exists():
return HTTP.BAD_REQUEST(message="bucket is exists")
bucket = Bucket(name=name)
if description:
bucket.description = description
bucket.save()
rep = BucketSerializer(bucket).data
return HTTP.OK(data=rep)
class BucketView(AuthMethodView):
def get(self, pk):
<|code_end|>
. Use current file imports:
from flask import request
from flask_maple.response import HTTP
from maple.utils import AuthMethodView
from maple.storage.db import Bucket
from maple.storage.serializer import BucketSerializer
from maple.utils import check_params, filter_maybe, update_maybe
and context (classes, functions, or code) from other files:
# Path: maple/utils.py
# class AuthMethodView(MethodView):
# decorators = (login_required, )
#
# Path: maple/storage/db.py
# class Bucket(ModelUserMixin, db.Model):
# __tablename__ = 'bucket'
#
# name = db.Column(db.String(108), nullable=False, unique=True)
# description = db.Column(db.String(1024), default='default')
#
# def get_root_path(self, path, create=False):
# filepath = self.rootpath
# for name in path.split("/"):
# if name == "":
# continue
# childpath = filepath.child_paths.filter_by(
# name=name,
# bucket_id=self.id,
# ).first()
# if not childpath and not create:
# return
#
# if not childpath and create:
# childpath = FilePath(
# name=name,
# bucket_id=self.id,
# parent_id=filepath.id,
# )
# childpath.save()
# filepath = childpath
# return filepath
#
# @property
# def rootpath(self):
# filepath = self.paths.filter_by(name="/").first()
# if not filepath:
# filepath = FilePath(name="/", bucket_id=self.id)
# filepath.save()
# return filepath
#
# @property
# def abspath(self):
# return os.path.join(config.UPLOAD_FOLDER, self.name)
#
# @property
# def relpath(self):
# return os.path.join(self.name)
#
# def __repr__(self):
# return '<Bucket %r>' % self.name
#
# def __str__(self):
# return self.name
#
# Path: maple/storage/serializer.py
# class BucketSerializer(Serializer):
# class Meta:
# exclude = ["paths"]
#
# Path: maple/utils.py
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# def update_maybe(ins, request_data, columns):
# for column in columns:
# value = request_data.get(column)
# if value:
# setattr(ins, column, value)
# return ins
. Output only the next line. | user = request.user |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: bucket.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-05-13 16:36:36 (CST)
# Last Update: Monday 2019-09-23 17:11:18 (CST)
# By:
# Description:
# ********************************************************************************
class BucketListView(AuthMethodView):
def get(self):
data = request.data
user = request.user
page, number = self.pageinfo
params = filter_maybe(data, {"name": "name__contains"})
ins = user.buckets.filter_by(**params).paginate(page, number)
serializer = BucketSerializer(ins)
return HTTP.OK(data=serializer.data)
@check_params(["name"])
def post(self):
data = request.data
name = data.get('name')
description = data.get('description')
if Bucket.query.filter_by(name=name).exists():
<|code_end|>
with the help of current file imports:
from flask import request
from flask_maple.response import HTTP
from maple.utils import AuthMethodView
from maple.storage.db import Bucket
from maple.storage.serializer import BucketSerializer
from maple.utils import check_params, filter_maybe, update_maybe
and context from other files:
# Path: maple/utils.py
# class AuthMethodView(MethodView):
# decorators = (login_required, )
#
# Path: maple/storage/db.py
# class Bucket(ModelUserMixin, db.Model):
# __tablename__ = 'bucket'
#
# name = db.Column(db.String(108), nullable=False, unique=True)
# description = db.Column(db.String(1024), default='default')
#
# def get_root_path(self, path, create=False):
# filepath = self.rootpath
# for name in path.split("/"):
# if name == "":
# continue
# childpath = filepath.child_paths.filter_by(
# name=name,
# bucket_id=self.id,
# ).first()
# if not childpath and not create:
# return
#
# if not childpath and create:
# childpath = FilePath(
# name=name,
# bucket_id=self.id,
# parent_id=filepath.id,
# )
# childpath.save()
# filepath = childpath
# return filepath
#
# @property
# def rootpath(self):
# filepath = self.paths.filter_by(name="/").first()
# if not filepath:
# filepath = FilePath(name="/", bucket_id=self.id)
# filepath.save()
# return filepath
#
# @property
# def abspath(self):
# return os.path.join(config.UPLOAD_FOLDER, self.name)
#
# @property
# def relpath(self):
# return os.path.join(self.name)
#
# def __repr__(self):
# return '<Bucket %r>' % self.name
#
# def __str__(self):
# return self.name
#
# Path: maple/storage/serializer.py
# class BucketSerializer(Serializer):
# class Meta:
# exclude = ["paths"]
#
# Path: maple/utils.py
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# def update_maybe(ins, request_data, columns):
# for column in columns:
# value = request_data.get(column)
# if value:
# setattr(ins, column, value)
# return ins
, which may contain function names, class names, or code. Output only the next line. | return HTTP.BAD_REQUEST(message="bucket is exists") |
Predict the next line for this snippet: <|code_start|># Email: mail@honmaple.com
# Created: 2019-07-09 01:32:22 (CST)
# Last Update: Wednesday 2019-07-10 00:11:03 (CST)
# By:
# Description:
# ********************************************************************************
class Shell(_Shell):
def __init__(self, host, token, bucket, path="/"):
self.host = host
self.token = token
self.bucket = bucket
self.path = path
super(Shell, self).__init__()
def _headers(self):
return {
'MapleToken': self.token,
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'
}
def prompt(self):
return "[{0}]-{1}: ".format(self.bucket, self.path)
def do_pwd(self, args):
self.echo(self.path)
def do_ls(self, args):
url = self.host + "/api/file/" + self.bucket
<|code_end|>
with the help of current file imports:
from maple.shell import Shell as _Shell
import requests
import os
and context from other files:
# Path: maple/shell.py
# class Shell(object):
# def __init__(self):
# self._exit = False
# self._action = [
# i.split("do_")[1] for i in dir(self) if i.startswith('do_')
# ]
# self._help = [
# i.split("help_")[1] for i in dir(self) if i.startswith('help_')
# ]
#
# def echo(self, message, color=None):
# print(message)
#
# def prompt(self):
# return ">> "
#
# def default(self, args):
# self.echo("*** Unknown syntax: " + args)
#
# def emptyline(self):
# pass
#
# def do_exit(self, args):
# "Exit shell"
# self._exit = True
#
# def do_help(self, args):
# "Show help"
# for action in self._action:
# hp = getattr(self, "do_" + action).__doc__
# if action in self._help:
# hp = getattr(self, "help_" + action)
# self.echo("{0}\t{1}".format(action, hp))
#
# def start(self):
# while self._exit == False:
# message = input(self.prompt())
# message = message.strip()
# if not message:
# self.emptyline()
# continue
#
# s = message.split(" ")
# keyword = s[0]
# if keyword == "?":
# keyword = "help"
#
# args = ""
# if len(s) > 1:
# args = " ".join(s[1:])
#
# if keyword in self._action:
# getattr(self, "do_" + keyword)(args)
# else:
# self.default(message)
, which may contain function names, class names, or code. Output only the next line. | r = requests.get( |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: article.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-07-12 10:18:31 (CST)
# Last Update: Monday 2019-09-23 17:06:31 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleAPI(AuthMethodView):
def get(self):
data = request.data
<|code_end|>
, generate the next line using the imports in this file:
from flask import request
from flask_maple.response import HTTP
from maple.assertion import assert_request
from maple.blog.assertion import ArticleAssert
from maple.blog.db import Article
from maple.blog.serializer import ArticleSerializer
from maple.utils import filter_maybe, AuthMethodView
and context (functions, classes, or occasionally code) from other files:
# Path: maple/assertion.py
# def assert_request(assertion, include=[], exclude=[]):
# def _assert_request(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# data = request.data
# resp = assertion(data, include, exclude)()
# if resp is not None:
# return resp
# return func(*args, **kwargs)
#
# return decorator
#
# return _assert_request
#
# Path: maple/blog/assertion.py
# class ArticleAssert(Assert):
# def assert_title(self, value):
# self.assertRequire(value, "title is required")
#
# def assert_content(self, value):
# self.assertRequire(value, "content is required")
#
# def assert_content_type(self, value):
# self.assertIn(value, ["0", "1"])
#
# def assert_category(self, value):
# pass
#
# def assert_tags(self, value):
# pass
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# Path: maple/blog/serializer.py
# class ArticleSerializer(Serializer):
# class Meta:
# exclude = ["user", "user_id"]
# extra = ["htmlcontent"]
#
# Path: maple/utils.py
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# class AuthMethodView(MethodView):
# decorators = (login_required, )
. Output only the next line. | page, number = self.pageinfo |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: article.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-07-12 10:18:31 (CST)
# Last Update: Monday 2019-09-23 17:06:31 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleAPI(AuthMethodView):
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
"category": "category__name",
"title": "title__contains",
"year": "created_at__year",
"month": "created_at__month"
<|code_end|>
with the help of current file imports:
from flask import request
from flask_maple.response import HTTP
from maple.assertion import assert_request
from maple.blog.assertion import ArticleAssert
from maple.blog.db import Article
from maple.blog.serializer import ArticleSerializer
from maple.utils import filter_maybe, AuthMethodView
and context from other files:
# Path: maple/assertion.py
# def assert_request(assertion, include=[], exclude=[]):
# def _assert_request(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# data = request.data
# resp = assertion(data, include, exclude)()
# if resp is not None:
# return resp
# return func(*args, **kwargs)
#
# return decorator
#
# return _assert_request
#
# Path: maple/blog/assertion.py
# class ArticleAssert(Assert):
# def assert_title(self, value):
# self.assertRequire(value, "title is required")
#
# def assert_content(self, value):
# self.assertRequire(value, "content is required")
#
# def assert_content_type(self, value):
# self.assertIn(value, ["0", "1"])
#
# def assert_category(self, value):
# pass
#
# def assert_tags(self, value):
# pass
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# Path: maple/blog/serializer.py
# class ArticleSerializer(Serializer):
# class Meta:
# exclude = ["user", "user_id"]
# extra = ["htmlcontent"]
#
# Path: maple/utils.py
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# class AuthMethodView(MethodView):
# decorators = (login_required, )
, which may contain function names, class names, or code. Output only the next line. | }) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: article.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-07-12 10:18:31 (CST)
# Last Update: Monday 2019-09-23 17:06:31 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleAPI(AuthMethodView):
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
<|code_end|>
with the help of current file imports:
from flask import request
from flask_maple.response import HTTP
from maple.assertion import assert_request
from maple.blog.assertion import ArticleAssert
from maple.blog.db import Article
from maple.blog.serializer import ArticleSerializer
from maple.utils import filter_maybe, AuthMethodView
and context from other files:
# Path: maple/assertion.py
# def assert_request(assertion, include=[], exclude=[]):
# def _assert_request(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# data = request.data
# resp = assertion(data, include, exclude)()
# if resp is not None:
# return resp
# return func(*args, **kwargs)
#
# return decorator
#
# return _assert_request
#
# Path: maple/blog/assertion.py
# class ArticleAssert(Assert):
# def assert_title(self, value):
# self.assertRequire(value, "title is required")
#
# def assert_content(self, value):
# self.assertRequire(value, "content is required")
#
# def assert_content_type(self, value):
# self.assertIn(value, ["0", "1"])
#
# def assert_category(self, value):
# pass
#
# def assert_tags(self, value):
# pass
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# Path: maple/blog/serializer.py
# class ArticleSerializer(Serializer):
# class Meta:
# exclude = ["user", "user_id"]
# extra = ["htmlcontent"]
#
# Path: maple/utils.py
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# class AuthMethodView(MethodView):
# decorators = (login_required, )
, which may contain function names, class names, or code. Output only the next line. | "category": "category__name", |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: article.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-07-12 10:18:31 (CST)
# Last Update: Monday 2019-09-23 17:06:31 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleAPI(AuthMethodView):
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
"category": "category__name",
"title": "title__contains",
"year": "created_at__year",
<|code_end|>
. Write the next line using the current file imports:
from flask import request
from flask_maple.response import HTTP
from maple.assertion import assert_request
from maple.blog.assertion import ArticleAssert
from maple.blog.db import Article
from maple.blog.serializer import ArticleSerializer
from maple.utils import filter_maybe, AuthMethodView
and context from other files:
# Path: maple/assertion.py
# def assert_request(assertion, include=[], exclude=[]):
# def _assert_request(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# data = request.data
# resp = assertion(data, include, exclude)()
# if resp is not None:
# return resp
# return func(*args, **kwargs)
#
# return decorator
#
# return _assert_request
#
# Path: maple/blog/assertion.py
# class ArticleAssert(Assert):
# def assert_title(self, value):
# self.assertRequire(value, "title is required")
#
# def assert_content(self, value):
# self.assertRequire(value, "content is required")
#
# def assert_content_type(self, value):
# self.assertIn(value, ["0", "1"])
#
# def assert_category(self, value):
# pass
#
# def assert_tags(self, value):
# pass
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# Path: maple/blog/serializer.py
# class ArticleSerializer(Serializer):
# class Meta:
# exclude = ["user", "user_id"]
# extra = ["htmlcontent"]
#
# Path: maple/utils.py
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# class AuthMethodView(MethodView):
# decorators = (login_required, )
, which may include functions, classes, or code. Output only the next line. | "month": "created_at__month" |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: article.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-07-12 10:18:31 (CST)
# Last Update: Monday 2019-09-23 17:06:31 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleAPI(AuthMethodView):
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
<|code_end|>
using the current file's imports:
from flask import request
from flask_maple.response import HTTP
from maple.assertion import assert_request
from maple.blog.assertion import ArticleAssert
from maple.blog.db import Article
from maple.blog.serializer import ArticleSerializer
from maple.utils import filter_maybe, AuthMethodView
and any relevant context from other files:
# Path: maple/assertion.py
# def assert_request(assertion, include=[], exclude=[]):
# def _assert_request(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# data = request.data
# resp = assertion(data, include, exclude)()
# if resp is not None:
# return resp
# return func(*args, **kwargs)
#
# return decorator
#
# return _assert_request
#
# Path: maple/blog/assertion.py
# class ArticleAssert(Assert):
# def assert_title(self, value):
# self.assertRequire(value, "title is required")
#
# def assert_content(self, value):
# self.assertRequire(value, "content is required")
#
# def assert_content_type(self, value):
# self.assertIn(value, ["0", "1"])
#
# def assert_category(self, value):
# pass
#
# def assert_tags(self, value):
# pass
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# Path: maple/blog/serializer.py
# class ArticleSerializer(Serializer):
# class Meta:
# exclude = ["user", "user_id"]
# extra = ["htmlcontent"]
#
# Path: maple/utils.py
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# class AuthMethodView(MethodView):
# decorators = (login_required, )
. Output only the next line. | data, { |
Given snippet: <|code_start|># Email: mail@honmaple.com
# Created: 2019-07-12 10:18:31 (CST)
# Last Update: Monday 2019-09-23 17:06:31 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleAPI(AuthMethodView):
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
"category": "category__name",
"title": "title__contains",
"year": "created_at__year",
"month": "created_at__month"
})
order_by = ("-created_at", )
ins = Article.query.filter_by(**params).order_by(*order_by).paginate(
page, number)
serializer = ArticleSerializer(ins)
return HTTP.OK(data=serializer.data)
@assert_request(ArticleAssert)
def post(self):
data = request.data
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import request
from flask_maple.response import HTTP
from maple.assertion import assert_request
from maple.blog.assertion import ArticleAssert
from maple.blog.db import Article
from maple.blog.serializer import ArticleSerializer
from maple.utils import filter_maybe, AuthMethodView
and context:
# Path: maple/assertion.py
# def assert_request(assertion, include=[], exclude=[]):
# def _assert_request(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# data = request.data
# resp = assertion(data, include, exclude)()
# if resp is not None:
# return resp
# return func(*args, **kwargs)
#
# return decorator
#
# return _assert_request
#
# Path: maple/blog/assertion.py
# class ArticleAssert(Assert):
# def assert_title(self, value):
# self.assertRequire(value, "title is required")
#
# def assert_content(self, value):
# self.assertRequire(value, "content is required")
#
# def assert_content_type(self, value):
# self.assertIn(value, ["0", "1"])
#
# def assert_category(self, value):
# pass
#
# def assert_tags(self, value):
# pass
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# Path: maple/blog/serializer.py
# class ArticleSerializer(Serializer):
# class Meta:
# exclude = ["user", "user_id"]
# extra = ["htmlcontent"]
#
# Path: maple/utils.py
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# class AuthMethodView(MethodView):
# decorators = (login_required, )
which might include code, classes, or functions. Output only the next line. | user = request.user |
Here is a snippet: <|code_start|> created_at=_date,
tags=tags,
content_type='1' if file_type == 'org' else '0',
user_id=user.id)
blog.save()
return blog
def org_to_blog(filename):
filename = os.path.join(page_path, 'org', filename)
print(filename)
with open(filename, 'r') as f:
text = f.readlines()
lines = text[:15]
attr = {}
for name, regex in org_regex.items():
for line in lines:
if regex.match(line):
attr[name] = regex.match(line).group(1).strip()
break
for index, line in enumerate(text):
if not line.startswith("#+"):
break
attr['content'] = ''.join(text[index:])
with app.app_context():
blog = write_to_blog(attr)
return blog
<|code_end|>
. Write the next line using the current file imports:
import os
from datetime import datetime
from re import compile
from runserver import app
from maple.model import Blog, Category, Tag, User
and context from other files:
# Path: runserver.py
# DEFAULT_HOST = 'http://static.localhost:8001'
# DEFAULT_KEY = ''
# def shell_command():
# def runserver():
# def init():
# def random_sep(n=6):
# def random_word(n=20, sep=True):
# def clear_cache():
# def initdb():
# def babel_init(lang):
# def babel_update():
# def babel_compile():
# def create_user(username, email, password):
# def password(username, password):
# def token(username):
# def upload(host, bucket, path, key, files, force):
# def list_files(upath):
# def upload_shell(host, bucket, path, key):
# def list_routers():
#
# Path: maple/model.py
# class User(db.Model, UserMixin):
# class Group(db.Model, GroupMixin):
# class Permission(db.Model, PermissionMixin):
# def is_admin(self):
# def token(self):
# def check_token(cls, token, max_age=24 * 3600 * 30):
, which may include functions, classes, or code. Output only the next line. | def md_to_blog(): |
Continue the code snippet: <|code_start|>def write_to_blog(attr, file_type='org'):
_author = attr['author']
_category = attr['category']
_tags = attr['tags'].split(',')
_title = attr['title']
_date = attr['date']
_content = attr['content']
user = User.query.filter_by(username=_author).first()
if not user:
user = User(username=_author, email='mail@honmaple.com')
user.set_password('123123')
user.save()
category = Category.query.filter_by(name=_category).first()
if not category:
category = Category(name=_category)
category.save()
tags = []
for _tag in _tags:
tag = Tag.query.filter_by(name=_tag).first()
if not tag:
tag = Tag(name=_tag)
tag.save()
tags.append(tag)
try:
_date = datetime.strptime(_date, '%Y-%m-%d'),
except ValueError:
<|code_end|>
. Use current file imports:
import os
from datetime import datetime
from re import compile
from runserver import app
from maple.model import Blog, Category, Tag, User
and context (classes, functions, or code) from other files:
# Path: runserver.py
# DEFAULT_HOST = 'http://static.localhost:8001'
# DEFAULT_KEY = ''
# def shell_command():
# def runserver():
# def init():
# def random_sep(n=6):
# def random_word(n=20, sep=True):
# def clear_cache():
# def initdb():
# def babel_init(lang):
# def babel_update():
# def babel_compile():
# def create_user(username, email, password):
# def password(username, password):
# def token(username):
# def upload(host, bucket, path, key, files, force):
# def list_files(upath):
# def upload_shell(host, bucket, path, key):
# def list_routers():
#
# Path: maple/model.py
# class User(db.Model, UserMixin):
# class Group(db.Model, GroupMixin):
# class Permission(db.Model, PermissionMixin):
# def is_admin(self):
# def token(self):
# def check_token(cls, token, max_age=24 * 3600 * 30):
. Output only the next line. | _date = datetime.strptime(_date, '%Y-%m-%d %H:%M:%S'), |
Continue the code snippet: <|code_start|> tag.save()
tags.append(tag)
try:
_date = datetime.strptime(_date, '%Y-%m-%d'),
except ValueError:
_date = datetime.strptime(_date, '%Y-%m-%d %H:%M:%S'),
blog = Blog.query.filter_by(title=_title).first()
if not blog:
blog = Blog(
title=_title,
category_id=category.id,
content=_content,
created_at=_date,
tags=tags,
content_type='1' if file_type == 'org' else '0',
user_id=user.id)
blog.save()
return blog
def org_to_blog(filename):
filename = os.path.join(page_path, 'org', filename)
print(filename)
with open(filename, 'r') as f:
text = f.readlines()
lines = text[:15]
attr = {}
<|code_end|>
. Use current file imports:
import os
from datetime import datetime
from re import compile
from runserver import app
from maple.model import Blog, Category, Tag, User
and context (classes, functions, or code) from other files:
# Path: runserver.py
# DEFAULT_HOST = 'http://static.localhost:8001'
# DEFAULT_KEY = ''
# def shell_command():
# def runserver():
# def init():
# def random_sep(n=6):
# def random_word(n=20, sep=True):
# def clear_cache():
# def initdb():
# def babel_init(lang):
# def babel_update():
# def babel_compile():
# def create_user(username, email, password):
# def password(username, password):
# def token(username):
# def upload(host, bucket, path, key, files, force):
# def list_files(upath):
# def upload_shell(host, bucket, path, key):
# def list_routers():
#
# Path: maple/model.py
# class User(db.Model, UserMixin):
# class Group(db.Model, GroupMixin):
# class Permission(db.Model, PermissionMixin):
# def is_admin(self):
# def token(self):
# def check_token(cls, token, max_age=24 * 3600 * 30):
. Output only the next line. | for name, regex in org_regex.items(): |
Predict the next line for this snippet: <|code_start|># ********************************************************************************
org_regex = {
'title': compile(r'^#\+TITLE:(.*?)$'),
'date': compile(r'^#\+DATE:(.*?)$'),
'category': compile(r'^#\+CATEGORY:(.*?)$'),
'author': compile(r'^#\+AUTHOR:(.*?)$'),
'summary': compile(r'^#\+PROPERTY:\s+SUMMARY (.*?)$'),
'slug': compile(r'^#\+PROPERTY:\s+SLUG (.*?)$'),
'language': compile(r'^#\+PROPERTY:\s+LANGUAGE (.*?)$'),
'modified': compile(r'^#\+PROPERTY:\s+MODIFIED (.*?)$'),
'tags': compile(r'^#\+PROPERTY:\s+TAGS (.*?)$'),
'save_as': compile(r'^#\+PROPERTY:\s+SAVE_AS (.*?)$'),
'status': compile(r'^#\+PROPERTY:\s+STATUS (.*?)$')
}
def write_to_blog(attr, file_type='org'):
_author = attr['author']
_category = attr['category']
_tags = attr['tags'].split(',')
_title = attr['title']
_date = attr['date']
_content = attr['content']
user = User.query.filter_by(username=_author).first()
if not user:
user = User(username=_author, email='mail@honmaple.com')
user.set_password('123123')
<|code_end|>
with the help of current file imports:
import os
from datetime import datetime
from re import compile
from runserver import app
from maple.model import Blog, Category, Tag, User
and context from other files:
# Path: runserver.py
# DEFAULT_HOST = 'http://static.localhost:8001'
# DEFAULT_KEY = ''
# def shell_command():
# def runserver():
# def init():
# def random_sep(n=6):
# def random_word(n=20, sep=True):
# def clear_cache():
# def initdb():
# def babel_init(lang):
# def babel_update():
# def babel_compile():
# def create_user(username, email, password):
# def password(username, password):
# def token(username):
# def upload(host, bucket, path, key, files, force):
# def list_files(upath):
# def upload_shell(host, bucket, path, key):
# def list_routers():
#
# Path: maple/model.py
# class User(db.Model, UserMixin):
# class Group(db.Model, GroupMixin):
# class Permission(db.Model, PermissionMixin):
# def is_admin(self):
# def token(self):
# def check_token(cls, token, max_age=24 * 3600 * 30):
, which may contain function names, class names, or code. Output only the next line. | user.save() |
Next line prediction: <|code_start|> blog = Blog(
title=_title,
category_id=category.id,
content=_content,
created_at=_date,
tags=tags,
content_type='1' if file_type == 'org' else '0',
user_id=user.id)
blog.save()
return blog
def org_to_blog(filename):
filename = os.path.join(page_path, 'org', filename)
print(filename)
with open(filename, 'r') as f:
text = f.readlines()
lines = text[:15]
attr = {}
for name, regex in org_regex.items():
for line in lines:
if regex.match(line):
attr[name] = regex.match(line).group(1).strip()
break
for index, line in enumerate(text):
if not line.startswith("#+"):
break
attr['content'] = ''.join(text[index:])
with app.app_context():
<|code_end|>
. Use current file imports:
(import os
from datetime import datetime
from re import compile
from runserver import app
from maple.model import Blog, Category, Tag, User)
and context including class names, function names, or small code snippets from other files:
# Path: runserver.py
# DEFAULT_HOST = 'http://static.localhost:8001'
# DEFAULT_KEY = ''
# def shell_command():
# def runserver():
# def init():
# def random_sep(n=6):
# def random_word(n=20, sep=True):
# def clear_cache():
# def initdb():
# def babel_init(lang):
# def babel_update():
# def babel_compile():
# def create_user(username, email, password):
# def password(username, password):
# def token(username):
# def upload(host, bucket, path, key, files, force):
# def list_files(upath):
# def upload_shell(host, bucket, path, key):
# def list_routers():
#
# Path: maple/model.py
# class User(db.Model, UserMixin):
# class Group(db.Model, GroupMixin):
# class Permission(db.Model, PermissionMixin):
# def is_admin(self):
# def token(self):
# def check_token(cls, token, max_age=24 * 3600 * 30):
. Output only the next line. | blog = write_to_blog(attr) |
Given snippet: <|code_start|> if regex.match(line):
m = regex.match(line)
key, value = m.group(2), m.group(3)
if key == "PROPERTY":
value = value.split(" ", 1)
value.append("")
key, value = value[0], value[1]
self.attr.update(**{key.lower(): value})
return True
return False
class Markdown(Reader):
content_type = Article.CONTENT_TYPE_MARKDOWN
def parse(self, line):
regex = re.compile(r'^(.*): (.*)$')
if regex.match(line):
m = regex.match(line)
key, value = m.group(1), m.group(2)
self.attr.update(**{key.lower(): value})
return True
return False
def org_to_db(path):
files = [
os.path.join(path, f) for f in os.listdir(path)
if os.path.isfile(os.path.join(path, f)) and f.endswith(".org")
]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
from maple.model import User
from maple.blog.db import Article, Tag, Category
from getpass import getpass
from datetime import datetime
and context:
# Path: maple/model.py
# class User(db.Model, UserMixin):
# __tablename__ = 'user'
#
# @property
# def is_admin(self):
# return self.is_authenticated and self.is_superuser
#
# @property
# def token(self):
# return self.email_token
#
# @classmethod
# def check_token(cls, token, max_age=24 * 3600 * 30):
# return cls.check_email_token(token, max_age)
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class Tag(db.Model, ModelMixin):
# __tablename__ = 'tag'
#
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(50), nullable=False)
# articles = db.relationship(
# 'Article',
# secondary=article_tags,
# backref=db.backref('tags', lazy='dynamic'),
# lazy='dynamic')
#
# def __repr__(self):
# return '<Tags %r>' % self.name
#
# def __str__(self):
# return self.name
#
# class Category(db.Model, ModelMixin):
# __tablename__ = 'category'
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(64), nullable=False)
#
# def __repr__(self):
# return '<Category %r>' % self.name
#
# def __str__(self):
# return self.name
which might include code, classes, or functions. Output only the next line. | articles = [] |
Next line prediction: <|code_start|> "content": "\n".join(content),
"content_type": self.content_type
}
return attr
class Org(Reader):
def parse(self, line):
regex = re.compile(r'^(\s*)#\+(.*): (.*)$')
if regex.match(line):
m = regex.match(line)
key, value = m.group(2), m.group(3)
if key == "PROPERTY":
value = value.split(" ", 1)
value.append("")
key, value = value[0], value[1]
self.attr.update(**{key.lower(): value})
return True
return False
class Markdown(Reader):
content_type = Article.CONTENT_TYPE_MARKDOWN
def parse(self, line):
regex = re.compile(r'^(.*): (.*)$')
if regex.match(line):
m = regex.match(line)
key, value = m.group(1), m.group(2)
self.attr.update(**{key.lower(): value})
<|code_end|>
. Use current file imports:
(import os
import re
from maple.model import User
from maple.blog.db import Article, Tag, Category
from getpass import getpass
from datetime import datetime)
and context including class names, function names, or small code snippets from other files:
# Path: maple/model.py
# class User(db.Model, UserMixin):
# __tablename__ = 'user'
#
# @property
# def is_admin(self):
# return self.is_authenticated and self.is_superuser
#
# @property
# def token(self):
# return self.email_token
#
# @classmethod
# def check_token(cls, token, max_age=24 * 3600 * 30):
# return cls.check_email_token(token, max_age)
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class Tag(db.Model, ModelMixin):
# __tablename__ = 'tag'
#
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(50), nullable=False)
# articles = db.relationship(
# 'Article',
# secondary=article_tags,
# backref=db.backref('tags', lazy='dynamic'),
# lazy='dynamic')
#
# def __repr__(self):
# return '<Tags %r>' % self.name
#
# def __str__(self):
# return self.name
#
# class Category(db.Model, ModelMixin):
# __tablename__ = 'category'
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(64), nullable=False)
#
# def __repr__(self):
# return '<Category %r>' % self.name
#
# def __str__(self):
# return self.name
. Output only the next line. | return True |
Using the snippet: <|code_start|> category=add_category(category),
tags=add_tags(tags),
user=add_author(author),
created_at=date)
article.save()
return article
def time_format(date):
if ":" in date:
return datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
return datetime.strptime(date, "%Y-%m-%d")
class Reader(object):
content_type = Article.CONTENT_TYPE_ORGMODE
def __init__(self, filename):
self.filename = filename
self.attr = dict()
def parse(self, line):
return False
def run(self):
with open(self.filename) as f:
lines = f.read()
is_content = False
content = []
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
from maple.model import User
from maple.blog.db import Article, Tag, Category
from getpass import getpass
from datetime import datetime
and context (class names, function names, or code) available:
# Path: maple/model.py
# class User(db.Model, UserMixin):
# __tablename__ = 'user'
#
# @property
# def is_admin(self):
# return self.is_authenticated and self.is_superuser
#
# @property
# def token(self):
# return self.email_token
#
# @classmethod
# def check_token(cls, token, max_age=24 * 3600 * 30):
# return cls.check_email_token(token, max_age)
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class Tag(db.Model, ModelMixin):
# __tablename__ = 'tag'
#
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(50), nullable=False)
# articles = db.relationship(
# 'Article',
# secondary=article_tags,
# backref=db.backref('tags', lazy='dynamic'),
# lazy='dynamic')
#
# def __repr__(self):
# return '<Tags %r>' % self.name
#
# def __str__(self):
# return self.name
#
# class Category(db.Model, ModelMixin):
# __tablename__ = 'category'
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(64), nullable=False)
#
# def __repr__(self):
# return '<Category %r>' % self.name
#
# def __str__(self):
# return self.name
. Output only the next line. | for line in lines.splitlines(): |
Predict the next line after this snippet: <|code_start|>class Reader(object):
content_type = Article.CONTENT_TYPE_ORGMODE
def __init__(self, filename):
self.filename = filename
self.attr = dict()
def parse(self, line):
return False
def run(self):
with open(self.filename) as f:
lines = f.read()
is_content = False
content = []
for line in lines.splitlines():
if is_content:
content.append(line)
continue
if not self.parse(line) or not line.strip():
is_content = True
attr = {
"title": self.attr["title"],
"author": self.attr["title"],
"category": self.attr["category"],
"tags": self.attr["tags"].split(","),
"date": time_format(self.attr["date"]),
<|code_end|>
using the current file's imports:
import os
import re
from maple.model import User
from maple.blog.db import Article, Tag, Category
from getpass import getpass
from datetime import datetime
and any relevant context from other files:
# Path: maple/model.py
# class User(db.Model, UserMixin):
# __tablename__ = 'user'
#
# @property
# def is_admin(self):
# return self.is_authenticated and self.is_superuser
#
# @property
# def token(self):
# return self.email_token
#
# @classmethod
# def check_token(cls, token, max_age=24 * 3600 * 30):
# return cls.check_email_token(token, max_age)
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class Tag(db.Model, ModelMixin):
# __tablename__ = 'tag'
#
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(50), nullable=False)
# articles = db.relationship(
# 'Article',
# secondary=article_tags,
# backref=db.backref('tags', lazy='dynamic'),
# lazy='dynamic')
#
# def __repr__(self):
# return '<Tags %r>' % self.name
#
# def __str__(self):
# return self.name
#
# class Category(db.Model, ModelMixin):
# __tablename__ = 'category'
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(64), nullable=False)
#
# def __repr__(self):
# return '<Category %r>' % self.name
#
# def __str__(self):
# return self.name
. Output only the next line. | "content": "\n".join(content), |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2018 jianglin
# File Name: jinja.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2018-02-08 15:25:56 (CST)
# Last Update: Monday 2019-06-10 01:00:04 (CST)
# By:
# Description:
# ********************************************************************************
def timesince(dt, default=_("just now")):
now = datetime.utcnow()
diff = now - dt
if diff.days > 90:
return format_datetime(dt, 'Y-MM-dd')
if diff.days > 10:
<|code_end|>
, determine the next line of code. You have imports:
from flask_babel import format_datetime
from flask_babel import lazy_gettext as _
from datetime import datetime
from maple import default
and context (class names, function names, or code) available:
# Path: maple/default.py
# SITE = {
# 'title': _('honmaple'),
# 'subtitle': _('风落花语风落天,花落风雨花落田.'),
# "author": "lin.jiang",
# "header": "https://static.honmaple.com/images/header/header.png?type=mini"
# }
# EXTENSION = {"login": False}
# SUBDOMAIN = {"static": True}
# HEADER = [
# {
# "name": _("Poem"),
# "url": "https://poem.honmaple.com"
# },
# {
# "name": _("Cloud"),
# "url": "https://cloud.honmaple.com"
# },
# {
# "name": _("TimeLine"),
# "url": "blog.timelines"
# },
# {
# "name": _("Archives"),
# "url": "blog.archives"
# },
# {
# "name": _("About me"),
# "url": "about"
# },
# ]
# FOOTER = {
# "copyright":
# "© 2015-2019 honmaple",
# "links": [
# {
# "name": _("Friends"),
# "url": "friend"
# }, {
# "name": _("Contact"),
# "url": "contact"
# }, {
# "name": _("Poem"),
# "url": "https://poem.honmaple.com"
# }, {
# "name": _("TimeLine"),
# "url": "blog.timelines"
# }
# ],
# "socials": [
# {
# "name": "GitHub",
# "icon": "fa-github",
# "url": "https://github.com/honmaple"
# },
# {
# "name": "MINE",
# "icon": "fa-globe",
# "url": "https://honmaple.me"
# },
# {
# "name": "Mail",
# "icon": "fa-envelope",
# "url": "mailto:mail@honmaple.com"
# },
# ]
# }
# INFO = [
# {
# "name": "Rss",
# "icon": "fa-rss",
# "url": "/rss"
# }, {
# "name": "MINE",
# "icon": "fa-globe",
# "url": "https://honmaple.me"
# }, {
# "name": "GitHub",
# "icon": "fa-github",
# "url": "https://github.com/honmaple"
# }, {
# "name": "Mail",
# "icon": "fa-envelope",
# "url": "mailto:mail@honmaple.com"
# }
# ]
. Output only the next line. | return format_datetime(dt, 'Y-MM-dd HH:mm') |
Continue the code snippet: <|code_start|>class IndexView(MethodView):
def get(self):
return HTTP.HTML("index/index.html")
class AboutView(MethodView):
def get(self):
return HTTP.HTML("index/about.html")
class FriendView(MethodView):
def get(self):
return HTTP.HTML("index/friends.html")
class ContactView(MethodView):
def get(self):
return HTTP.HTML("index/contact.html")
class LoginView(MethodView):
@check_params(['username', 'password'])
def post(self):
data = request.data
username = data['username']
password = data['password']
remember = data.pop('remember', True)
user = User.query.filter_by(username=username).first()
if not user or not user.check_password(password):
return HTTP.BAD_REQUEST(message=_('Username or Password Error'))
<|code_end|>
. Use current file imports:
from flask import redirect, request
from flask_babel import gettext as _
from flask_maple.response import HTTP
from maple.model import User
from maple.utils import MethodView, check_params
and context (classes, functions, or code) from other files:
# Path: maple/model.py
# class User(db.Model, UserMixin):
# __tablename__ = 'user'
#
# @property
# def is_admin(self):
# return self.is_authenticated and self.is_superuser
#
# @property
# def token(self):
# return self.email_token
#
# @classmethod
# def check_token(cls, token, max_age=24 * 3600 * 30):
# return cls.check_email_token(token, max_age)
#
# Path: maple/utils.py
# class MethodView(_MethodView):
# cache_time = 180
#
# def dispatch_request(self, *args, **kwargs):
# f = super(MethodView, self).dispatch_request
# if self.cache_time and request.method in ["GET", "HEAD"]:
# return cache.cached(
# timeout=self.cache_time,
# key_prefix=cache_key,
# )(f)(*args, **kwargs)
# return f(*args, **kwargs)
#
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
. Output only the next line. | user.login(remember) |
Using the snippet: <|code_start|># Description:
# ********************************************************************************
class IndexView(MethodView):
def get(self):
return HTTP.HTML("index/index.html")
class AboutView(MethodView):
def get(self):
return HTTP.HTML("index/about.html")
class FriendView(MethodView):
def get(self):
return HTTP.HTML("index/friends.html")
class ContactView(MethodView):
def get(self):
return HTTP.HTML("index/contact.html")
class LoginView(MethodView):
@check_params(['username', 'password'])
def post(self):
data = request.data
username = data['username']
password = data['password']
<|code_end|>
, determine the next line of code. You have imports:
from flask import redirect, request
from flask_babel import gettext as _
from flask_maple.response import HTTP
from maple.model import User
from maple.utils import MethodView, check_params
and context (class names, function names, or code) available:
# Path: maple/model.py
# class User(db.Model, UserMixin):
# __tablename__ = 'user'
#
# @property
# def is_admin(self):
# return self.is_authenticated and self.is_superuser
#
# @property
# def token(self):
# return self.email_token
#
# @classmethod
# def check_token(cls, token, max_age=24 * 3600 * 30):
# return cls.check_email_token(token, max_age)
#
# Path: maple/utils.py
# class MethodView(_MethodView):
# cache_time = 180
#
# def dispatch_request(self, *args, **kwargs):
# f = super(MethodView, self).dispatch_request
# if self.cache_time and request.method in ["GET", "HEAD"]:
# return cache.cached(
# timeout=self.cache_time,
# key_prefix=cache_key,
# )(f)(*args, **kwargs)
# return f(*args, **kwargs)
#
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
. Output only the next line. | remember = data.pop('remember', True) |
Next line prediction: <|code_start|>
class FriendView(MethodView):
def get(self):
return HTTP.HTML("index/friends.html")
class ContactView(MethodView):
def get(self):
return HTTP.HTML("index/contact.html")
class LoginView(MethodView):
@check_params(['username', 'password'])
def post(self):
data = request.data
username = data['username']
password = data['password']
remember = data.pop('remember', True)
user = User.query.filter_by(username=username).first()
if not user or not user.check_password(password):
return HTTP.BAD_REQUEST(message=_('Username or Password Error'))
user.login(remember)
return HTTP.OK()
class LogoutView(MethodView):
cache_time = 0
def get(self):
<|code_end|>
. Use current file imports:
(from flask import redirect, request
from flask_babel import gettext as _
from flask_maple.response import HTTP
from maple.model import User
from maple.utils import MethodView, check_params)
and context including class names, function names, or small code snippets from other files:
# Path: maple/model.py
# class User(db.Model, UserMixin):
# __tablename__ = 'user'
#
# @property
# def is_admin(self):
# return self.is_authenticated and self.is_superuser
#
# @property
# def token(self):
# return self.email_token
#
# @classmethod
# def check_token(cls, token, max_age=24 * 3600 * 30):
# return cls.check_email_token(token, max_age)
#
# Path: maple/utils.py
# class MethodView(_MethodView):
# cache_time = 180
#
# def dispatch_request(self, *args, **kwargs):
# f = super(MethodView, self).dispatch_request
# if self.cache_time and request.method in ["GET", "HEAD"]:
# return cache.cached(
# timeout=self.cache_time,
# key_prefix=cache_key,
# )(f)(*args, **kwargs)
# return f(*args, **kwargs)
#
# def check_params(keys, req=None):
# '''
# only check is not NULL
# '''
# def _check_params(func):
# @wraps(func)
# def decorator(*args, **kwargs):
# if req is not None:
# request_data = req
# else:
# request_data = request.data
# for key in keys:
# if not request_data.get(key):
# return HTTP.BAD_REQUEST(message='{0} required'.format(key))
# return func(*args, **kwargs)
#
# return decorator
#
# return _check_params
. Output only the next line. | user = request.user |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: router.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-05-24 18:43:30 (CST)
# Last Update: Thursday 2019-07-11 18:06:49 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleListView(MethodView):
per_page = 10
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
"category": "category__name",
<|code_end|>
. Use current file imports:
from collections import OrderedDict
from urllib.parse import urljoin
from flask import request, url_for
from flask_maple.response import HTTP
from maple.default import SITE
from maple.utils import MethodView, filter_maybe
from werkzeug.contrib.atom import AtomFeed
from .db import Article, TimeLine
and context (classes, functions, or code) from other files:
# Path: maple/default.py
# SITE = {
# 'title': _('honmaple'),
# 'subtitle': _('风落花语风落天,花落风雨花落田.'),
# "author": "lin.jiang",
# "header": "https://static.honmaple.com/images/header/header.png?type=mini"
# }
#
# Path: maple/utils.py
# class MethodView(_MethodView):
# cache_time = 180
#
# def dispatch_request(self, *args, **kwargs):
# f = super(MethodView, self).dispatch_request
# if self.cache_time and request.method in ["GET", "HEAD"]:
# return cache.cached(
# timeout=self.cache_time,
# key_prefix=cache_key,
# )(f)(*args, **kwargs)
# return f(*args, **kwargs)
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class TimeLine(db.Model, ModelUserMixin):
# __tablename__ = 'timeline'
#
# id = db.Column(db.Integer, primary_key=True)
# content = db.Column(db.Text, nullable=False)
# is_hidden = db.Column(db.Boolean, nullable=True, default=False)
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<TimeLine %r>" % self.content[:10]
#
# def __str__(self):
# return self.content[:10]
#
# @property
# def datetime_format(self):
# return format_datetime(self.created_at, 'Y-M-d H:M')
#
# def to_json(self):
# return {'id': self.id, 'content': self.content, 'hide': self.hide}
. Output only the next line. | "title": "title__contains", |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: router.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-05-24 18:43:30 (CST)
# Last Update: Thursday 2019-07-11 18:06:49 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleListView(MethodView):
per_page = 10
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
"category": "category__name",
"title": "title__contains",
<|code_end|>
, generate the next line using the imports in this file:
from collections import OrderedDict
from urllib.parse import urljoin
from flask import request, url_for
from flask_maple.response import HTTP
from maple.default import SITE
from maple.utils import MethodView, filter_maybe
from werkzeug.contrib.atom import AtomFeed
from .db import Article, TimeLine
and context (functions, classes, or occasionally code) from other files:
# Path: maple/default.py
# SITE = {
# 'title': _('honmaple'),
# 'subtitle': _('风落花语风落天,花落风雨花落田.'),
# "author": "lin.jiang",
# "header": "https://static.honmaple.com/images/header/header.png?type=mini"
# }
#
# Path: maple/utils.py
# class MethodView(_MethodView):
# cache_time = 180
#
# def dispatch_request(self, *args, **kwargs):
# f = super(MethodView, self).dispatch_request
# if self.cache_time and request.method in ["GET", "HEAD"]:
# return cache.cached(
# timeout=self.cache_time,
# key_prefix=cache_key,
# )(f)(*args, **kwargs)
# return f(*args, **kwargs)
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class TimeLine(db.Model, ModelUserMixin):
# __tablename__ = 'timeline'
#
# id = db.Column(db.Integer, primary_key=True)
# content = db.Column(db.Text, nullable=False)
# is_hidden = db.Column(db.Boolean, nullable=True, default=False)
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<TimeLine %r>" % self.content[:10]
#
# def __str__(self):
# return self.content[:10]
#
# @property
# def datetime_format(self):
# return format_datetime(self.created_at, 'Y-M-d H:M')
#
# def to_json(self):
# return {'id': self.id, 'content': self.content, 'hide': self.hide}
. Output only the next line. | "year": "created_at__year", |
Predict the next line for this snippet: <|code_start|># Last Update: Thursday 2019-07-11 18:06:49 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleListView(MethodView):
per_page = 10
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
"category": "category__name",
"title": "title__contains",
"year": "created_at__year",
"month": "created_at__month"
})
order_by = ("-created_at", )
ins = Article.query.filter_by(**params).order_by(*order_by).paginate(
page, number)
return HTTP.HTML('articles.html', articles=ins)
class ArticleView(MethodView):
<|code_end|>
with the help of current file imports:
from collections import OrderedDict
from urllib.parse import urljoin
from flask import request, url_for
from flask_maple.response import HTTP
from maple.default import SITE
from maple.utils import MethodView, filter_maybe
from werkzeug.contrib.atom import AtomFeed
from .db import Article, TimeLine
and context from other files:
# Path: maple/default.py
# SITE = {
# 'title': _('honmaple'),
# 'subtitle': _('风落花语风落天,花落风雨花落田.'),
# "author": "lin.jiang",
# "header": "https://static.honmaple.com/images/header/header.png?type=mini"
# }
#
# Path: maple/utils.py
# class MethodView(_MethodView):
# cache_time = 180
#
# def dispatch_request(self, *args, **kwargs):
# f = super(MethodView, self).dispatch_request
# if self.cache_time and request.method in ["GET", "HEAD"]:
# return cache.cached(
# timeout=self.cache_time,
# key_prefix=cache_key,
# )(f)(*args, **kwargs)
# return f(*args, **kwargs)
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class TimeLine(db.Model, ModelUserMixin):
# __tablename__ = 'timeline'
#
# id = db.Column(db.Integer, primary_key=True)
# content = db.Column(db.Text, nullable=False)
# is_hidden = db.Column(db.Boolean, nullable=True, default=False)
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<TimeLine %r>" % self.content[:10]
#
# def __str__(self):
# return self.content[:10]
#
# @property
# def datetime_format(self):
# return format_datetime(self.created_at, 'Y-M-d H:M')
#
# def to_json(self):
# return {'id': self.id, 'content': self.content, 'hide': self.hide}
, which may contain function names, class names, or code. Output only the next line. | def get(self, pk): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: router.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-05-24 18:43:30 (CST)
# Last Update: Thursday 2019-07-11 18:06:49 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleListView(MethodView):
per_page = 10
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
"category": "category__name",
"title": "title__contains",
"year": "created_at__year",
<|code_end|>
, generate the next line using the imports in this file:
from collections import OrderedDict
from urllib.parse import urljoin
from flask import request, url_for
from flask_maple.response import HTTP
from maple.default import SITE
from maple.utils import MethodView, filter_maybe
from werkzeug.contrib.atom import AtomFeed
from .db import Article, TimeLine
and context (functions, classes, or occasionally code) from other files:
# Path: maple/default.py
# SITE = {
# 'title': _('honmaple'),
# 'subtitle': _('风落花语风落天,花落风雨花落田.'),
# "author": "lin.jiang",
# "header": "https://static.honmaple.com/images/header/header.png?type=mini"
# }
#
# Path: maple/utils.py
# class MethodView(_MethodView):
# cache_time = 180
#
# def dispatch_request(self, *args, **kwargs):
# f = super(MethodView, self).dispatch_request
# if self.cache_time and request.method in ["GET", "HEAD"]:
# return cache.cached(
# timeout=self.cache_time,
# key_prefix=cache_key,
# )(f)(*args, **kwargs)
# return f(*args, **kwargs)
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class TimeLine(db.Model, ModelUserMixin):
# __tablename__ = 'timeline'
#
# id = db.Column(db.Integer, primary_key=True)
# content = db.Column(db.Text, nullable=False)
# is_hidden = db.Column(db.Boolean, nullable=True, default=False)
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<TimeLine %r>" % self.content[:10]
#
# def __str__(self):
# return self.content[:10]
#
# @property
# def datetime_format(self):
# return format_datetime(self.created_at, 'Y-M-d H:M')
#
# def to_json(self):
# return {'id': self.id, 'content': self.content, 'hide': self.hide}
. Output only the next line. | "month": "created_at__month" |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: router.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-05-24 18:43:30 (CST)
# Last Update: Thursday 2019-07-11 18:06:49 (CST)
# By:
# Description:
# ********************************************************************************
class ArticleListView(MethodView):
per_page = 10
def get(self):
data = request.data
page, number = self.pageinfo
params = filter_maybe(
data, {
"tag": "tags__name",
<|code_end|>
. Use current file imports:
(from collections import OrderedDict
from urllib.parse import urljoin
from flask import request, url_for
from flask_maple.response import HTTP
from maple.default import SITE
from maple.utils import MethodView, filter_maybe
from werkzeug.contrib.atom import AtomFeed
from .db import Article, TimeLine)
and context including class names, function names, or small code snippets from other files:
# Path: maple/default.py
# SITE = {
# 'title': _('honmaple'),
# 'subtitle': _('风落花语风落天,花落风雨花落田.'),
# "author": "lin.jiang",
# "header": "https://static.honmaple.com/images/header/header.png?type=mini"
# }
#
# Path: maple/utils.py
# class MethodView(_MethodView):
# cache_time = 180
#
# def dispatch_request(self, *args, **kwargs):
# f = super(MethodView, self).dispatch_request
# if self.cache_time and request.method in ["GET", "HEAD"]:
# return cache.cached(
# timeout=self.cache_time,
# key_prefix=cache_key,
# )(f)(*args, **kwargs)
# return f(*args, **kwargs)
#
# def filter_maybe(request_data, columns, params=None):
# if params is None:
# params = dict()
# is_dict = isinstance(columns, dict)
# for column in columns:
# value = request_data.get(column)
# if not value:
# continue
# key = column if not is_dict else columns.get(column, column)
#
# if key in ["created_at__gte", "created_at__lte"]:
# value = datetime.strptime(value, '%Y-%m-%d')
# params.update({key: value})
# return params
#
# Path: maple/blog/db.py
# class Article(db.Model, ModelUserMixin):
# __tablename__ = 'article'
#
# CONTENT_TYPE_MARKDOWN = 0
# CONTENT_TYPE_ORGMODE = 1
#
# CONTENT_TYPE = ((0, 'markdown'), (1, 'org-mode'))
#
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(50), nullable=False)
# content = db.Column(db.Text, nullable=False)
# content_type = db.Column(
# db.Integer, nullable=False, default=CONTENT_TYPE_MARKDOWN)
#
# category_id = db.Column(
# db.Integer,
# db.ForeignKey('category.id', ondelete="CASCADE"),
# nullable=False)
# category = db.relationship(
# 'Category',
# backref=db.backref(
# 'articles', cascade='all,delete-orphan', lazy='dynamic'),
# uselist=False,
# lazy='joined')
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<Article %r>" % self.title
#
# def __str__(self):
# return self.title
#
# def to_json(self):
# return {
# 'id': self.id,
# 'title': self.title,
# 'category': self.category.name,
# 'tags': ','.join([tag.name for tag in self.tags]),
# }
#
# def to_html(self, length=None, truncate=False):
# length = length or current_app.config.get("SUMMARY_MAX_LENGTH")
# if not truncate:
# length = None
# if self.content_type == self.CONTENT_TYPE_MARKDOWN:
# return markdown_to_html(self.content, length)
# return orgmode_to_html(self.content, length)
#
# @property
# def htmlcontent(self):
# return self.to_html()
#
# @property
# def next_article(self):
# return Article.query.filter_by(id__lt=self.id).order_by("-id").first()
#
# @property
# def previous_article(self):
# return Article.query.filter_by(id__gt=self.id).order_by("id").first()
#
# @property
# def read_times(self):
# return Count.get('article:{}'.format(self.id))
#
# @read_times.setter
# def read_times(self, value):
# Count.set('article:{}'.format(self.id))
#
# class TimeLine(db.Model, ModelUserMixin):
# __tablename__ = 'timeline'
#
# id = db.Column(db.Integer, primary_key=True)
# content = db.Column(db.Text, nullable=False)
# is_hidden = db.Column(db.Boolean, nullable=True, default=False)
#
# __mapper_args__ = {"order_by": text("created_at desc")}
#
# def __repr__(self):
# return "<TimeLine %r>" % self.content[:10]
#
# def __str__(self):
# return self.content[:10]
#
# @property
# def datetime_format(self):
# return format_datetime(self.created_at, 'Y-M-d H:M')
#
# def to_json(self):
# return {'id': self.id, 'content': self.content, 'hide': self.hide}
. Output only the next line. | "category": "category__name", |
Using the snippet: <|code_start|>#!/usr/bin/env python3
topLevelPath = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, topLevelPath)
sys.path.insert(0, os.path.join(topLevelPath, 'build/lib.linux-x86_64-3.4/'))
sys.path.insert(0, os.path.join(topLevelPath, 'build/lib.linux-x86_64-3.5/'))
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import sys
import os.path
from qutepart.syntax.parser import StringDetect, RegExpr
and context (class names, function names, or code) available:
# Path: qutepart/syntax/parser.py
# class StringDetect(AbstractRule):
# """Public attributes:
# string
# """
# def __init__(self, abstractRuleParams, string):
# AbstractRule.__init__(self, abstractRuleParams)
# self.string = string
#
# def shortId(self):
# return 'StringDetect(%s)' % self.string
#
# def _tryMatch(self, textToMatchObject):
# if self.string is None:
# return None
#
# if self.dynamic:
# string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData)
# if not string:
# return None
# else:
# string = self.string
#
# if textToMatchObject.text.startswith(string):
# return RuleTryMatchResult(self, len(string))
#
# return None
#
# @staticmethod
# def _makeDynamicSubsctitutions(string, contextData):
# """For dynamic rules, replace %d patterns with actual strings
# Python function, which is used by C extension.
# """
# def _replaceFunc(escapeMatchObject):
# stringIndex = escapeMatchObject.group(0)[1]
# index = int(stringIndex)
# if index < len(contextData):
# return contextData[index]
# else:
# return escapeMatchObject.group(0) # no any replacements, return original value
#
# return _numSeqReplacer.sub(_replaceFunc, string)
#
# class RegExpr(AbstractRule):
# """ Public attributes:
# regExp
# wordStart
# lineStart
# """
# def __init__(self, abstractRuleParams,
# string, insensitive, minimal, wordStart, lineStart):
# AbstractRule.__init__(self, abstractRuleParams)
# self.string = string
# self.insensitive = insensitive
# self.minimal = minimal
# self.wordStart = wordStart
# self.lineStart = lineStart
#
# if self.dynamic:
# self.regExp = None
# else:
# self.regExp = self._compileRegExp(string, insensitive, minimal)
#
#
# def shortId(self):
# return 'RegExpr( %s )' % self.string
#
# def _tryMatch(self, textToMatchObject):
# """Tries to parse text. If matched - saves data for dynamic context
# """
# # Special case. if pattern starts with \b, we have to check it manually,
# # because string is passed to .match(..) without beginning
# if self.wordStart and \
# (not textToMatchObject.isWordStart):
# return None
#
# #Special case. If pattern starts with ^ - check column number manually
# if self.lineStart and \
# textToMatchObject.currentColumnIndex > 0:
# return None
#
# if self.dynamic:
# string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData)
# regExp = self._compileRegExp(string, self.insensitive, self.minimal)
# else:
# regExp = self.regExp
#
# if regExp is None:
# return None
#
# wholeMatch, groups = self._matchPattern(regExp, textToMatchObject.text)
# if wholeMatch is not None:
# count = len(wholeMatch)
# return RuleTryMatchResult(self, count, groups)
# else:
# return None
#
# @staticmethod
# def _makeDynamicSubsctitutions(string, contextData):
# """For dynamic rules, replace %d patterns with actual strings
# Escapes reg exp symbols in the pattern
# Python function, used by C code
# """
# def _replaceFunc(escapeMatchObject):
# stringIndex = escapeMatchObject.group(0)[1]
# index = int(stringIndex)
# if index < len(contextData):
# return re.escape(contextData[index])
# else:
# return escapeMatchObject.group(0) # no any replacements, return original value
#
# return _numSeqReplacer.sub(_replaceFunc, string)
#
# @staticmethod
# def _compileRegExp(string, insensitive, minimal):
# """Compile regular expression.
# Python function, used by C code
#
# NOTE minimal flag is not supported here, but supported on PCRE
# """
# flags = 0
# if insensitive:
# flags = re.IGNORECASE
#
# string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser
# string = string.replace('[:digit:]', '\\d')
# string = string.replace('[:blank:]', '\\s')
#
# try:
# return re.compile(string, flags)
# except (re.error, AssertionError) as ex:
# _logger.warning("Invalid pattern '%s': %s", string, str(ex))
# return None
#
# @staticmethod
# def _matchPattern(regExp, string):
# """Try to match pattern.
# Returns tuple (whole match, groups) or (None, None)
# Python function, used by C code
# """
# match = regExp.match(string)
# if match is not None and match.group(0):
# return match.group(0), (match.group(0), ) + match.groups()
# else:
# return None, None
. Output only the next line. | class TestCase(unittest.TestCase): |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
topLevelPath = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, topLevelPath)
sys.path.insert(0, os.path.join(topLevelPath, 'build/lib.linux-x86_64-3.4/'))
sys.path.insert(0, os.path.join(topLevelPath, 'build/lib.linux-x86_64-3.5/'))
class TestCase(unittest.TestCase):
def test_StringDetect(self):
self.assertEqual(StringDetect._makeDynamicSubsctitutions('a%1c%3', ['a', '|']),
'a|c%3')
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import sys
import os.path
from qutepart.syntax.parser import StringDetect, RegExpr
and context (classes, functions, sometimes code) from other files:
# Path: qutepart/syntax/parser.py
# class StringDetect(AbstractRule):
# """Public attributes:
# string
# """
# def __init__(self, abstractRuleParams, string):
# AbstractRule.__init__(self, abstractRuleParams)
# self.string = string
#
# def shortId(self):
# return 'StringDetect(%s)' % self.string
#
# def _tryMatch(self, textToMatchObject):
# if self.string is None:
# return None
#
# if self.dynamic:
# string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData)
# if not string:
# return None
# else:
# string = self.string
#
# if textToMatchObject.text.startswith(string):
# return RuleTryMatchResult(self, len(string))
#
# return None
#
# @staticmethod
# def _makeDynamicSubsctitutions(string, contextData):
# """For dynamic rules, replace %d patterns with actual strings
# Python function, which is used by C extension.
# """
# def _replaceFunc(escapeMatchObject):
# stringIndex = escapeMatchObject.group(0)[1]
# index = int(stringIndex)
# if index < len(contextData):
# return contextData[index]
# else:
# return escapeMatchObject.group(0) # no any replacements, return original value
#
# return _numSeqReplacer.sub(_replaceFunc, string)
#
# class RegExpr(AbstractRule):
# """ Public attributes:
# regExp
# wordStart
# lineStart
# """
# def __init__(self, abstractRuleParams,
# string, insensitive, minimal, wordStart, lineStart):
# AbstractRule.__init__(self, abstractRuleParams)
# self.string = string
# self.insensitive = insensitive
# self.minimal = minimal
# self.wordStart = wordStart
# self.lineStart = lineStart
#
# if self.dynamic:
# self.regExp = None
# else:
# self.regExp = self._compileRegExp(string, insensitive, minimal)
#
#
# def shortId(self):
# return 'RegExpr( %s )' % self.string
#
# def _tryMatch(self, textToMatchObject):
# """Tries to parse text. If matched - saves data for dynamic context
# """
# # Special case. if pattern starts with \b, we have to check it manually,
# # because string is passed to .match(..) without beginning
# if self.wordStart and \
# (not textToMatchObject.isWordStart):
# return None
#
# #Special case. If pattern starts with ^ - check column number manually
# if self.lineStart and \
# textToMatchObject.currentColumnIndex > 0:
# return None
#
# if self.dynamic:
# string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData)
# regExp = self._compileRegExp(string, self.insensitive, self.minimal)
# else:
# regExp = self.regExp
#
# if regExp is None:
# return None
#
# wholeMatch, groups = self._matchPattern(regExp, textToMatchObject.text)
# if wholeMatch is not None:
# count = len(wholeMatch)
# return RuleTryMatchResult(self, count, groups)
# else:
# return None
#
# @staticmethod
# def _makeDynamicSubsctitutions(string, contextData):
# """For dynamic rules, replace %d patterns with actual strings
# Escapes reg exp symbols in the pattern
# Python function, used by C code
# """
# def _replaceFunc(escapeMatchObject):
# stringIndex = escapeMatchObject.group(0)[1]
# index = int(stringIndex)
# if index < len(contextData):
# return re.escape(contextData[index])
# else:
# return escapeMatchObject.group(0) # no any replacements, return original value
#
# return _numSeqReplacer.sub(_replaceFunc, string)
#
# @staticmethod
# def _compileRegExp(string, insensitive, minimal):
# """Compile regular expression.
# Python function, used by C code
#
# NOTE minimal flag is not supported here, but supported on PCRE
# """
# flags = 0
# if insensitive:
# flags = re.IGNORECASE
#
# string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser
# string = string.replace('[:digit:]', '\\d')
# string = string.replace('[:blank:]', '\\s')
#
# try:
# return re.compile(string, flags)
# except (re.error, AssertionError) as ex:
# _logger.warning("Invalid pattern '%s': %s", string, str(ex))
# return None
#
# @staticmethod
# def _matchPattern(regExp, string):
# """Try to match pattern.
# Returns tuple (whole match, groups) or (None, None)
# Python function, used by C code
# """
# match = regExp.match(string)
# if match is not None and match.group(0):
# return match.group(0), (match.group(0), ) + match.groups()
# else:
# return None, None
. Output only the next line. | def test_RegExp(self): |
Predict the next line for this snippet: <|code_start|>MAX_VISIBLE_WORD_COUNT = 256
class _GlobalUpdateWordSetTimer:
"""Timer updates word set, when editor is idle. (5 sec. after last change)
Timer is global, for avoid situation, when all instances
update set simultaneously
"""
_IDLE_TIMEOUT_MS = 1000
def __init__(self):
self._timer = QTimer()
self._timer.setSingleShot(True)
self._timer.timeout.connect(self._onTimer)
self._scheduledMethods = []
def schedule(self, method):
if not method in self._scheduledMethods:
self._scheduledMethods.append(method)
self._timer.start(self._IDLE_TIMEOUT_MS)
def cancel(self, method):
"""Cancel scheduled method
Safe method, may be called with not-scheduled method"""
if method in self._scheduledMethods:
self._scheduledMethods.remove(method)
if not self._scheduledMethods:
self._timer.stop()
<|code_end|>
with the help of current file imports:
import re
import time
from PyQt5.QtCore import pyqtSignal, QAbstractItemModel, QEvent, QModelIndex, QObject, QSize, Qt, QTimer
from PyQt5.QtWidgets import QListView
from PyQt5.QtGui import QCursor
from qutepart.htmldelegate import HTMLDelegate
and context from other files:
# Path: qutepart/htmldelegate.py
# class HTMLDelegate(QStyledItemDelegate):
# """QStyledItemDelegate implementation. Draws HTML
#
# http://stackoverflow.com/questions/1956542/how-to-make-item-view-render-rich-html-text-in-qt/1956781#1956781
# """
#
# def paint(self, painter, option, index):
# """QStyledItemDelegate.paint implementation
# """
# option.state &= ~QStyle.State_HasFocus # never draw focus rect
#
# options = QStyleOptionViewItem(option)
# self.initStyleOption(options,index)
#
# style = QApplication.style() if options.widget is None else options.widget.style()
#
# doc = QTextDocument()
# doc.setDocumentMargin(1)
# doc.setHtml(options.text)
# if options.widget is not None:
# doc.setDefaultFont(options.widget.font())
# # bad long (multiline) strings processing doc.setTextWidth(options.rect.width())
#
# options.text = ""
# style.drawControl(QStyle.CE_ItemViewItem, options, painter);
#
# ctx = QAbstractTextDocumentLayout.PaintContext()
#
# # Highlighting text if item is selected
# if option.state & QStyle.State_Selected:
# ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText))
#
# textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options)
# painter.save()
# painter.translate(textRect.topLeft())
# """Original example contained line
# painter.setClipRect(textRect.translated(-textRect.topLeft()))
# but text is drawn clipped with it on kubuntu 12.04
# """
# doc.documentLayout().draw(painter, ctx)
#
# painter.restore()
#
# def sizeHint(self, option, index):
# """QStyledItemDelegate.sizeHint implementation
# """
# options = QStyleOptionViewItem(option)
# self.initStyleOption(options,index)
#
# doc = QTextDocument()
# doc.setDocumentMargin(1)
# # bad long (multiline) strings processing doc.setTextWidth(options.rect.width())
# doc.setHtml(options.text)
# return QSize(int(doc.idealWidth()),
# int(QStyledItemDelegate.sizeHint(self, option, index).height()))
, which may contain function names, class names, or code. Output only the next line. | def _onTimer(self): |
Given the code snippet: <|code_start|> elif cmd==HWCONTROLLIST[1]: # stoppulse
return MQTT_stoppulse(cmd, message, recdata)
elif cmd==HWCONTROLLIST[2]: # readinput
return readinput_MQTT(cmd, message, recdata)
elif cmd==HWCONTROLLIST[3]: # pinstate
return MQTT_pin_level(cmd, message, recdata)
elif cmd==HWCONTROLLIST[4]: #hbridge
return ""
else:
returnmsg(recdata,cmd,"Command not Found",0)
return False
return False
def execute_task_fake(cmd, message, recdata):
if cmd==HWCONTROLLIST[0]:
print("fake command")
return True
else:
<|code_end|>
, generate the next line using the imports in this file:
import time
import threading
import glob
import logging
import statusdataDBmod
import sys, os
import json
from datetime import datetime,date,timedelta
from math import sqrt
from mqtt import MQTTutils
and context (functions, classes, or occasionally code) from other files:
# Path: mqtt/MQTTutils.py
# def Create_connections_and_subscribe(CLIENTSLIST):
# def Disconnect_clients(CLIENTSLIST):
# def on_connect(self,mqttc, obj, flags, rc):
# def on_disconnect(self, mqttc, obj, rc):
# def on_message(self,mqttc, obj, msg):
# def on_publish(self,mqttc, obj, mid):
# def on_subscribe(self,mqttc, obj, mid, granted_qos):
# def on_log(self, mqttc, obj, level, string):
# def __init__(self, clientid, subtopic="" ,host="localhost", port=1883, cleanstart=True, keepalive=180, newsocket=True, protocolName=None,
# willFlag=False, willTopic=None, willMessage=None, willQoS=2, willRetain=False, username=None, password=None,
# properties=None, willProperties=None):
# def connect(self):
# def subscribe(self, topic="", options=None, properties=None, qos=2):
# def unsubscribe(self, topics):
# def publish(self, topic, payload, qos=0, retained=False, properties=None):
# def publish_wait_QoS2(self, topic, payload, retained=False, properties=None):
# def run_loop(self, timesec=1):
# def loop_start(self):
# def loop_stop(self):
# def disconnect(self, properties=None):
# class Client:
# CLIENTSLIST={}
. Output only the next line. | msg="no fake command available" + cmd |
Here is a snippet: <|code_start|> parser.add_argument('hexfiles', nargs='+', metavar='HEXFILE', action='append', default=[],
help='Filename(s) of HEX source code.')
parser.add_argument('--pluginpath', nargs='*', metavar='PATH', action='append', default=[],
help='Paths to search for python modules.')
parser.add_argument('--plugin', nargs='+', metavar=('MODULENAME', 'ARGUMENT'), action='append', default=[],
help='Python module to load as plugin, plus optional arguments for plugin. Can be given multiple times to load multiple plugins.')
config.add_common_arguments(parser)
args = parser.parse_args(argv)
config.process_arguments(args)
return args
def setPaths(paths):
for p in paths:
sys.path.append(p)
logging.info('sys.path='+repr(sys.path))
def loadPlugins(plugins):
ret = []
for p in plugins:
pi = loadPlugin(p)
logging.debug('for plugin {} got plugin info {}'.format(pi.mname, repr(pi)))
ret.append(pi)
return ret
def teardownPlugins(plugins):
for p in plugins:
p.teardown()
def main():
code = 1
<|code_end|>
. Write the next line using the current file imports:
import sys
import platform
import hexlite.app as app
import hexlite
import hexlite.rewriter as rewriter
import hexlite.ast.shallowparser as shp
import hexlite.ast as ast
import dlvhex
import os, argparse, traceback, pprint, logging
from hexlite.modelcallback import StandardModelCallback
and context from other files:
# Path: hexlite/modelcallback.py
# class StandardModelCallback:
# def __init__(self, stringifiedFacts, config):
# self.facts = stringifiedFacts
# self.config = config
#
# def __call__(self, model):
# assert(isinstance(model, dlvhex.Model))
# if not model.is_optimal:
# logging.info('not showing suboptimal answer set')
# return
# strsyms = [ str(x) for x in model.atoms ]
# if self.config.nofacts:
# strsyms = [ s for s in strsyms if s not in self.facts ]
# if not self.config.auxfacts:
# strsyms = [ s for s in strsyms if not s.startswith(aux.Aux.PREFIX) ]
# if len(model.cost) > 0:
# # first entry = highest priority level
# # last entry = lowest priority level (1)
# #logging.debug('got cost'+repr(model.cost))
# pairs = [ '[{}:{}]'.format(p[1], p[0]+1) for p in enumerate(reversed(model.cost)) if p[1] != 0 ]
# costs=' <{}>'.format(','.join(pairs))
# else:
# costs = ''
# logging.info('showing (optimal) answer set')
# sys.stdout.write('{'+','.join(strsyms)+'}'+costs+'\n')
, which may include functions, classes, or code. Output only the next line. | try: |
Given the following code snippet before the placeholder: <|code_start|> self.atoms = self.auxatoms | set(self.int2atom.keys())
# replatoms
self.extractReplAtoms()
# chatoms replrules chrules djrules
self.preliminaryToCategorizedRules()
# allrules
self.allrules = self.replrules + self.chrules + self.djrules
self.replrules_base = 0
self.chrules_base = len(self.replrules)
self.djrules_base = len(self.replrules)+len(self.chrules)
# done!
self.waitingForStuff = False
if __debug__:
self.printall()
def __getattr__(self, name):
return self.WarnMissing(name)
def rule(self, choice, head, body):
logging.debug("GPRule ch=%s hd=%s b=%s", repr(choice), repr(head), repr(body))
# it seems we cannot ignore "deterministic" rules
# sometimes they are necessary, and they concern atoms that have no symbol
# (for an example, see tests/choicerule4.hex)
self.preliminaryrules.append( (choice, head, body) )
def weight_rule(self, choice, head, lower_bound, body):
logging.debug("GPWeightRule ch=%s hd=%s lb=%s, b=%s", repr(choice), repr(head), repr(lower_bound), repr(body))
self.preliminaryweightrules.append( (choice, head, lower_bound, body) )
def output_atom(self, symbol, atom):
logging.debug("GPAtom symb=%s atm=%s", repr(symbol), repr(atom))
if atom == 0:
# this is not a literal but a signal that symbol is always true (i.e., a fact)
self.facts.append(symbol)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import sys
import clingo
from .auxiliary import Aux
and context including class names, function names, and sometimes code from other files:
# Path: hexlite/auxiliary.py
# class Aux:
# # prefix for all auxiliaries [just rename in case of conflicts in an application]
# PREFIX = 'aux_'
#
# # maxint
# MAXINT = PREFIX+'maxint'
#
# # relevance of external atoms + input tuple grounding
# EARELV = PREFIX+'r'
# # truth of external atoms (in the papers "external replacement atoms")
# EAREPL = PREFIX+'t'
#
# # auxiliary for rule heads in explicitflpcheck.RuleActivityProgram
# RHPRED = PREFIX+'h'
#
# # for explicitflpcheck.CheckOptimizedProgram
# # auxilary for unnamed clasp atoms
# CLATOM = PREFIX+'C'
# # auxiliary for atoms in compatible set
# CSATOM = PREFIX+'c'
# # auxiliary for atoms in choice heads
# CHATOM = PREFIX+'H'
# # auxiliary for smaller atom
# SMALLER = PREFIX+'smaller'
#
# # for acthex rewriting
# ACTREPL = PREFIX+'act'
. Output only the next line. | else: |
Next line prediction: <|code_start|> logging.debug('parseTerm {}'.format(repr(pinp)))
if len(pinp) == N+1:
otuple = [ shp.shallowprint(x) for x in pinp ]
dlvhex.output( tuple(otuple) )
def functionDecompose1(inp):
functionDecomposeN(inp, 1)
def functionDecompose2(inp):
functionDecomposeN(inp, 2)
def functionDecompose3(inp):
functionDecomposeN(inp, 3)
def getArity(term):
logging.debug('getArity got {}'.format(repr(term)))
pinp = shp.parseTerm(term.value())
logging.debug('parseTerm {}'.format(repr(pinp)))
dlvhex.output( (len(pinp)-1,) )
def isEmpty(assignment):
true = 0
false = 0
unknown = 0
premisse = ()
for x in dlvhex.getInputAtoms():
if x.isTrue():
true = true + 1
elif x.isFalse():
false = false + 1
<|code_end|>
. Use current file imports:
(import dlvhex
import hexlite.ast.shallowparser as shp
import logging, sys
from hexlite.modelcallback import JSONModelCallback)
and context including class names, function names, or small code snippets from other files:
# Path: hexlite/modelcallback.py
# class JSONModelCallback:
# def __init__(self, stringifiedFacts, config):
# self.facts = stringifiedFacts
# self.config = config
#
# def structify_r(self, tup, d=0):
# #logging.debug("%sstructify_r %s", ' '*d, tup)
# if isinstance(tup, (tuple,list)):
# # tuples
# if len(tup) == 1:
# return self.structify_r(tup[0], d+1)
# else:
# return { 'name': self.structify_r(tup[0], d+1), 'args': [ self.structify_r(x,d+1) for x in tup[1:] ] }
# else:
# x = tup
# assert(isinstance(x, hexlite.clingobackend.ClingoID))
# if x.symlit.sym.type == clingo.SymbolType.Function and len(x.symlit.sym.arguments) > 0:
# return self.structify_r(x.tuple(), d+1)
# elif x.isInteger():
# return x.intValue()
# else:
# return x.value()
#
# def structify(self, sym):
# assert(isinstance(sym, dlvhex.ID))
# atomtuple = sym.tuple()
# return self.structify_r(atomtuple)
#
# def __call__(self, model):
# assert(isinstance(model, dlvhex.Model))
# if not model.is_optimal:
# logging.info('not showing suboptimal answer set')
# return
# str_struc_syms = [ (x,str(x)) for x in model.atoms ]
# if self.config.nofacts:
# # filter out by matching string representation with stringified facts
# str_struc_syms = [ (sym, strsym) for sym, strsym in str_struc_syms if strsym not in self.facts ]
# if not self.config.auxfacts:
# str_struc_syms = [ (sym, strsym) for sym, strsym in str_struc_syms if not strsym.startswith(aux.Aux.PREFIX) ]
# out = {
# 'cost': [ { 'priority': p[0]+1, 'cost': p[1] } for p in enumerate(reversed(model.cost)) if p[1] != 0 ],
# 'atoms': [ self.structify(sym) for sym, strsym in str_struc_syms ],
# 'stratoms': [ strsym for sym, strsym in str_struc_syms ]
# }
# sys.stdout.write(json.dumps(out)+'\n')
# sys.stdout.flush()
. Output only the next line. | else: |
Using the snippet: <|code_start|>
class ProgramRewriter(hexlite.rewriter.ProgramRewriter):
def __init__(self, pcontext, shallowprogram, plugins, config):
# rewrite shallowprogram:
# * heads that are actions become auxiliary atoms AUXACTION(actionname,c(arguments),prio,cbp)
# then init original rewriter
newshallowprogram = self.__rewriteActionsToAuxiliaries(shallowprogram)
<|code_end|>
, determine the next line of code. You have imports:
import hexlite.rewriter
import hexlite.auxiliary as aux
import logging, pprint
from hexlite.ast import shallowparser as shp
and context (class names, function names, or code) available:
# Path: hexlite/ast/shallowparser.py
# def message(s):
# def t_newline(t):
# def t_COMMENT(t):
# def t_error(t):
# def p_content_1(p):
# def p_content_2(p):
# def p_statement(p):
# def p_rule(p):
# def p_disjlist(p):
# def p_semicollist_1(p):
# def p_semicollist_2(p):
# def p_expandlist(p):
# def p_collist_1(p):
# def p_collist_2(p):
# def p_conjlist(p):
# def p_commalist_1(p):
# def p_commalist_2(p):
# def p_commalist_3(p):
# def p_elist_1(p):
# def p_elist_2(p):
# def p_eterm_1(p):
# def p_eterm_2(p):
# def p_eterm_3(p):
# def p_eterm_4(p):
# def p_error(p):
# def parseTerm(content):
# def parse(content):
# def testparse():
# def shallowprint(x,sepspace=' ', listspace=' ',unaryTupleFinalComma=False):
# def testprint():
# def main():
# DEBUG=False
# TESTSDIR='../tests/'
# TESTSDIR='../tests/'
. Output only the next line. | hexlite.rewriter.ProgramRewriter.__init__(self, pcontext, newshallowprogram, plugins, config) |
Next line prediction: <|code_start|>
def test_initialization():
x = np.random.normal(size=(13, 5))
y = np.random.randint(2, size=(13, 3))
# no edges make independent model
model = MultiLabelClf()
model.initialize(x, y)
assert_equal(model.n_states, 2)
assert_equal(model.n_labels, 3)
assert_equal(model.n_features, 5)
<|code_end|>
. Use current file imports:
(import itertools
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from nose.tools import assert_almost_equal, assert_equal, assert_raises
from pystruct.models import MultiLabelClf
from pystruct.inference import compute_energy)
and context including class names, function names, or small code snippets from other files:
# Path: pystruct/models/multilabel_svm.py
# class MultiLabelClf(CRF):
# """Multi-label model for predicting several binary classes.
#
# Multi-label classification is a generalization of multi-class
# classification, in that multiple classes can be present in each
# example. This can also be thought of as predicting
# binary indicator per class.
#
# This class supports different models via the "edges" parameter.
# Giving no edges yields independent classifiers for each class. Giving
# "full" yields a fully connected graph over the labels, while "tree"
# yields the best tree-shaped graph (using the Chow-Liu algorithm).
# It is also possible to specify a custom connectivity structure.
#
# Parameters
# ----------
# n_labels : int (default=None)
# Number of labels. Inferred from data if not provided.
#
# n_features : int (default=None)
# Number of input features. Inferred from data if not provided.
#
# edges : array-like, string or None
# Either None, which yields independent models, 'tree',
# which yields the Chow-Liu tree over the labels, 'full',
# which yields a fully connected graph, or an array-like
# of edges for a custom dependency structure.
#
# inference_method :
# The inference method to be used.
#
# """
# def __init__(self, n_labels=None, n_features=None, edges=None,
# inference_method=None):
# self.n_labels = n_labels
# self.edges = edges
# CRF.__init__(self, 2, n_features, inference_method)
#
# def _set_size_joint_feature(self):
# # try to set the size of joint_feature if possible
# if self.n_features is not None and self.n_states is not None:
# if self.edges is None:
# self.edges = np.zeros(shape=(0, 2), dtype=np.int)
# self.size_joint_feature = (self.n_features * self.n_labels + 4 *
# self.edges.shape[0])
#
# def initialize(self, X, Y):
# n_features = X.shape[1]
# if self.n_features is None:
# self.n_features = n_features
# elif self.n_features != n_features:
# raise ValueError("Expected %d features, got %d"
# % (self.n_features, n_features))
#
# n_labels = Y.shape[1]
# if self.n_labels is None:
# self.n_labels = n_labels
# elif self.n_labels != n_labels:
# raise ValueError("Expected %d labels, got %d"
# % (self.n_labels, n_labels))
#
# self._set_size_joint_feature()
# self._set_class_weight()
#
# def _get_edges(self, x):
# return self.edges
#
# def _get_unary_potentials(self, x, w):
# unary_params = w[:self.n_labels * self.n_features].reshape(
# self.n_labels, self.n_features)
# unary_potentials = np.dot(x, unary_params.T)
# return np.vstack([-unary_potentials, unary_potentials]).T
#
# def _get_pairwise_potentials(self, x, w):
# pairwise_params = w[self.n_labels * self.n_features:].reshape(
# self.edges.shape[0], self.n_states, self.n_states)
# return pairwise_params
#
# def joint_feature(self, x, y):
# if isinstance(y, tuple):
# # continuous pairwise marginals
# y_cont, pairwise_marginals = y
# y_signs = 2 * y_cont[:, 1] - 1
# unary_marginals = np.repeat(x[np.newaxis, :], len(y_signs), axis=0)
# unary_marginals *= y_signs[:, np.newaxis]
# else:
# # discrete y
# y_signs = 2 * y - 1
# unary_marginals = np.repeat(x[np.newaxis, :], len(y_signs), axis=0)
# unary_marginals *= y_signs[:, np.newaxis]
# pairwise_marginals = []
# for edge in self.edges:
# # indicator of one of four possible states of the edge
# pw = np.zeros((2, 2))
# pw[y[edge[0]], y[edge[1]]] = 1
# pairwise_marginals.append(pw)
#
# if len(pairwise_marginals):
# pairwise_marginals = np.vstack(pairwise_marginals)
# return np.hstack([unary_marginals.ravel(),
# pairwise_marginals.ravel()])
# return unary_marginals.ravel()
#
# Path: pystruct/inference/common.py
# def compute_energy(unary_potentials, pairwise_potentials, edges, labels):
# """Compute energy of labels for given energy function.
#
# Convenience function with same interface as inference functions to easily
# compare solutions.
#
# Parameters
# ----------
# unary_potentials : nd-array
# Unary potentials of energy function.
#
# pairwise_potentials : nd-array
# Pairwise potentials of energy function.
#
# edges : nd-array
# Edges of energy function.
#
# labels : nd-array
# Variable assignment to evaluate.
#
# Returns
# -------
# energy : float
# Energy of assignment.
# """
#
# n_states, pairwise_potentials = \
# _validate_params(unary_potentials, pairwise_potentials, edges)
# energy = np.sum(unary_potentials[np.arange(len(labels)), labels])
# for edge, pw in zip(edges, pairwise_potentials):
# energy += pw[labels[edge[0]], labels[edge[1]]]
# return energy
. Output only the next line. | assert_equal(model.size_joint_feature, 5 * 3) |
Given snippet: <|code_start|>
def get_installed(method_filter=None):
if method_filter is None:
method_filter = ["max-product", 'ad3', 'ad3+', 'qpbo', 'ogm', 'lp']
installed = []
unary = np.zeros((1, 1))
pw = np.zeros((1, 1))
edges = np.empty((0, 2), dtype=np.int)
for method in method_filter:
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import opengm
import ad3
import ad3
from .linear_programming import lp_general_graph
from .maxprod import inference_max_product
from .common import _validate_params
from pyqpbo import alpha_expansion_general_graph
and context:
# Path: pystruct/inference/common.py
# def _validate_params(unary_potentials, pairwise_params, edges):
# n_states = unary_potentials.shape[-1]
# if pairwise_params.shape == (n_states, n_states):
# # only one matrix given
# pairwise_potentials = np.repeat(pairwise_params[np.newaxis, :, :],
# edges.shape[0], axis=0)
# else:
# if pairwise_params.shape != (edges.shape[0], n_states, n_states):
# raise ValueError("Expected pairwise_params either to "
# "be of shape n_states x n_states "
# "or n_edges x n_states x n_states, but"
# " got shape %s" % repr(pairwise_params.shape))
# pairwise_potentials = pairwise_params
# return n_states, pairwise_potentials
which might include code, classes, or functions. Output only the next line. | if method != 'ad3+': |
Given the code snippet: <|code_start|> 0., 0., 1.,
.4, # pairwise
-.3, .3,
-.5, -.1, .3])
for inference_method in get_installed():
#NOTE: ad3+ fails because it requires a different data structure
if inference_method == 'ad3+': continue
crf = GridCRF(inference_method=inference_method)
crf.initialize(X, Y)
y_hat = crf.inference(x, w)
assert_array_equal(y, y_hat)
def test_binary_grid_unaries():
# test handling on unaries for binary grid CRFs
for ds in binary:
X, Y = ds(n_samples=1)
x, y = X[0], Y[0]
for inference_method in get_installed():
#NOTE: ad3+ fails because it requires a different data structure
if inference_method == 'ad3+': continue
crf = GridCRF(inference_method=inference_method)
crf.initialize(X, Y)
w_unaries_only = np.zeros(7)
w_unaries_only[:4] = np.eye(2).ravel()
# test that inference with unaries only is the
# same as argmax
inf_unaries = crf.inference(x, w_unaries_only)
assert_array_equal(inf_unaries, np.argmax(x, axis=2),
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_almost_equal)
from pystruct.datasets import (generate_blocks, generate_blocks_multinomial,
binary, multinomial)
from pystruct.models import GridCRF
from pystruct.utils import (find_constraint, exhaustive_inference,
exhaustive_loss_augmented_inference)
from pystruct.inference import get_installed
and context (functions, classes, or occasionally code) from other files:
# Path: pystruct/models/grid_crf.py
# class GridCRF(GraphCRF):
# """Pairwise CRF on a 2d grid.
#
# Pairwise potentials are symmetric and the same for all edges.
# This leads to n_classes parameters for unary potentials and
# n_classes * (n_classes + 1) / 2 parameters for edge potentials.
#
# Unary evidence ``x`` is given as array of shape (width, height, n_features),
# labels ``y`` are given as array of shape (width, height). Grid sizes do not
# need to be constant over the dataset.
#
# Parameters
# ----------
# n_states : int, default=2
# Number of states for all variables.
#
# inference_method : string, default="ad3"
# Function to call do do inference and loss-augmented inference.
# Possible values are:
#
# - 'max-product' for max-product belief propagation.
# Recommended for chains an trees. Loopy belief propagation in
# case of a general graph.
# - 'lp' for Linear Programming relaxation using cvxopt.
# - 'ad3' for AD3 dual decomposition.
# - 'qpbo' for QPBO + alpha expansion.
# - 'ogm' for OpenGM inference algorithms.
#
# neighborhood : int, default=4
# Neighborhood defining connection for each variable in the grid.
# Possible choices are 4 and 8.
# """
# def __init__(self, n_states=None, n_features=None, inference_method=None,
# neighborhood=4):
# self.neighborhood = neighborhood
# GraphCRF.__init__(self, n_states=n_states, n_features=n_features,
# inference_method=inference_method)
#
# def _get_edges(self, x):
# return make_grid_edges(x, neighborhood=self.neighborhood)
#
# def _get_features(self, x):
# return x.reshape(-1, self.n_features)
#
# def _reshape_y(self, y, shape_x, return_energy):
# if return_energy:
# y, energy = y
#
# if isinstance(y, tuple):
# y = (y[0].reshape(shape_x[0], shape_x[1], y[0].shape[1]), y[1])
# else:
# y = y.reshape(shape_x[:-1])
#
# if return_energy:
# return y, energy
# return y
#
# def inference(self, x, w, relaxed=False, return_energy=False):
# y = GraphCRF.inference(self, x, w, relaxed=relaxed,
# return_energy=return_energy)
# return self._reshape_y(y, x.shape, return_energy)
#
# def loss_augmented_inference(self, x, y, w, relaxed=False,
# return_energy=False):
# y_hat = GraphCRF.loss_augmented_inference(self, x, y.ravel(), w,
# relaxed=relaxed,
# return_energy=return_energy)
# return self._reshape_y(y_hat, x.shape, return_energy)
#
# def continuous_loss(self, y, y_hat):
# # continuous version of the loss
# # y_hat is the result of linear programming
# return GraphCRF.continuous_loss(
# self, y.ravel(), y_hat.reshape(-1, y_hat.shape[-1]))
#
# Path: pystruct/inference/inference_methods.py
# def get_installed(method_filter=None):
# if method_filter is None:
# method_filter = ["max-product", 'ad3', 'ad3+', 'qpbo', 'ogm', 'lp']
#
# installed = []
# unary = np.zeros((1, 1))
# pw = np.zeros((1, 1))
# edges = np.empty((0, 2), dtype=np.int)
# for method in method_filter:
# try:
# if method != 'ad3+':
# inference_dispatch(unary, pw, edges, inference_method=method)
# else:
# inference_dispatch(unary, np.zeros((0,1,1))
# , np.zeros((0,2), dtype=np.int)
# , inference_method=method)
# installed.append(method)
# except ImportError:
# pass
# return installed
. Output only the next line. | "Wrong unary inference for %s" |
Predict the next line after this snippet: <|code_start|> #NOTE: ad3+ fails because it requires a different data structure
if inference_method == 'ad3+': continue
crf = GridCRF(inference_method=inference_method)
crf.initialize(X, Y)
y_hat = crf.inference(x, w)
assert_array_equal(y, y_hat)
def test_binary_grid_unaries():
# test handling on unaries for binary grid CRFs
for ds in binary:
X, Y = ds(n_samples=1)
x, y = X[0], Y[0]
for inference_method in get_installed():
#NOTE: ad3+ fails because it requires a different data structure
if inference_method == 'ad3+': continue
crf = GridCRF(inference_method=inference_method)
crf.initialize(X, Y)
w_unaries_only = np.zeros(7)
w_unaries_only[:4] = np.eye(2).ravel()
# test that inference with unaries only is the
# same as argmax
inf_unaries = crf.inference(x, w_unaries_only)
assert_array_equal(inf_unaries, np.argmax(x, axis=2),
"Wrong unary inference for %s"
% inference_method)
assert(np.mean(inf_unaries == y) > 0.5)
# check that the right thing happens on noise-free data
<|code_end|>
using the current file's imports:
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_almost_equal)
from pystruct.datasets import (generate_blocks, generate_blocks_multinomial,
binary, multinomial)
from pystruct.models import GridCRF
from pystruct.utils import (find_constraint, exhaustive_inference,
exhaustive_loss_augmented_inference)
from pystruct.inference import get_installed
and any relevant context from other files:
# Path: pystruct/models/grid_crf.py
# class GridCRF(GraphCRF):
# """Pairwise CRF on a 2d grid.
#
# Pairwise potentials are symmetric and the same for all edges.
# This leads to n_classes parameters for unary potentials and
# n_classes * (n_classes + 1) / 2 parameters for edge potentials.
#
# Unary evidence ``x`` is given as array of shape (width, height, n_features),
# labels ``y`` are given as array of shape (width, height). Grid sizes do not
# need to be constant over the dataset.
#
# Parameters
# ----------
# n_states : int, default=2
# Number of states for all variables.
#
# inference_method : string, default="ad3"
# Function to call do do inference and loss-augmented inference.
# Possible values are:
#
# - 'max-product' for max-product belief propagation.
# Recommended for chains an trees. Loopy belief propagation in
# case of a general graph.
# - 'lp' for Linear Programming relaxation using cvxopt.
# - 'ad3' for AD3 dual decomposition.
# - 'qpbo' for QPBO + alpha expansion.
# - 'ogm' for OpenGM inference algorithms.
#
# neighborhood : int, default=4
# Neighborhood defining connection for each variable in the grid.
# Possible choices are 4 and 8.
# """
# def __init__(self, n_states=None, n_features=None, inference_method=None,
# neighborhood=4):
# self.neighborhood = neighborhood
# GraphCRF.__init__(self, n_states=n_states, n_features=n_features,
# inference_method=inference_method)
#
# def _get_edges(self, x):
# return make_grid_edges(x, neighborhood=self.neighborhood)
#
# def _get_features(self, x):
# return x.reshape(-1, self.n_features)
#
# def _reshape_y(self, y, shape_x, return_energy):
# if return_energy:
# y, energy = y
#
# if isinstance(y, tuple):
# y = (y[0].reshape(shape_x[0], shape_x[1], y[0].shape[1]), y[1])
# else:
# y = y.reshape(shape_x[:-1])
#
# if return_energy:
# return y, energy
# return y
#
# def inference(self, x, w, relaxed=False, return_energy=False):
# y = GraphCRF.inference(self, x, w, relaxed=relaxed,
# return_energy=return_energy)
# return self._reshape_y(y, x.shape, return_energy)
#
# def loss_augmented_inference(self, x, y, w, relaxed=False,
# return_energy=False):
# y_hat = GraphCRF.loss_augmented_inference(self, x, y.ravel(), w,
# relaxed=relaxed,
# return_energy=return_energy)
# return self._reshape_y(y_hat, x.shape, return_energy)
#
# def continuous_loss(self, y, y_hat):
# # continuous version of the loss
# # y_hat is the result of linear programming
# return GraphCRF.continuous_loss(
# self, y.ravel(), y_hat.reshape(-1, y_hat.shape[-1]))
#
# Path: pystruct/inference/inference_methods.py
# def get_installed(method_filter=None):
# if method_filter is None:
# method_filter = ["max-product", 'ad3', 'ad3+', 'qpbo', 'ogm', 'lp']
#
# installed = []
# unary = np.zeros((1, 1))
# pw = np.zeros((1, 1))
# edges = np.empty((0, 2), dtype=np.int)
# for method in method_filter:
# try:
# if method != 'ad3+':
# inference_dispatch(unary, pw, edges, inference_method=method)
# else:
# inference_dispatch(unary, np.zeros((0,1,1))
# , np.zeros((0,2), dtype=np.int)
# , inference_method=method)
# installed.append(method)
# except ImportError:
# pass
# return installed
. Output only the next line. | X, Y = ds(n_samples=1, noise=0) |
Here is a snippet: <|code_start|> 'user': user,
})
@ajax()
def xhr_rss(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'profile/rss.html', {
'feed': get_rss_feed(user.profile.rss_url),
})
@login_required
def edit(request):
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
messages.success(request, "Profile updated successfully")
return redirect('profile:edit')
else:
form = ProfileForm(instance=request.user.profile)
return render(request, 'profile/edit/view.html', {
'form': form,
})
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from librement.utils.ajax import ajax
from .forms import ProfileForm, AccountForm, URLForm, PictureForm, PasswordForm
from .utils import get_rss_feed
and context from other files:
# Path: src/librement/profile/forms.py
# class ProfileForm(forms.ModelForm):
# class Meta:
# model = Profile
# fields = (
# 'display_name',
# 'biography',
# 'rss_url',
# )
#
# class AccountForm(dict):
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# for key, klass, fn in (
# ('user', AccountUserForm, lambda x: x),
# ('profile', AccountProfileForm, lambda x: x.profile),
# ):
# self[key] = klass(instance=fn(user), *args, **kwargs)
#
# def save(self):
# return [x.save() for x in self.values()]
#
# def is_valid(self):
# return all(x.is_valid() for x in self.values())
#
# class URLForm(forms.ModelForm):
# username = forms.RegexField(regex=r'^[\w-]+$')
#
# class Meta:
# model = User
# fields = (
# 'username',
# )
#
# class PictureForm(forms.Form):
# picture = forms.ImageField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PictureForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.profile.picture.save(
# self.cleaned_data['picture']
# )
# self.user.profile.save()
#
# class PasswordForm(forms.Form):
# password_old = forms.CharField()
# password = forms.CharField()
# password_confirm = forms.CharField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PasswordForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.set_password(self.cleaned_data['password'])
# self.user.save()
#
# def clean_password_old(self):
# val = self.cleaned_data['password_old']
#
# if not self.user.check_password(val):
# raise forms.ValidationError(
# "Password is not correct."
# )
#
# return val
#
# def clean_password_confirm(self):
# password = self.cleaned_data.get('password', '')
# password_confirm = self.cleaned_data['password_confirm']
#
# if password != password_confirm:
# raise forms.ValidationError("Passwords do not match.")
#
# if len(password) < 8:
# raise forms.ValidationError(
# "Password must be at least 8 characters"
# )
#
# return password
#
# Path: src/librement/profile/utils.py
# def get_rss_feed(url):
# if not url:
# return None
#
# key = 'feed:%s' % hashlib.sha1(url).hexdigest()
# feed = cache.get(key)
#
# if feed is None:
# feed = feedparser.parse(url)
# cache.set(key, feed, 3600)
#
# return feed
, which may include functions, classes, or code. Output only the next line. | @login_required |
Next line prediction: <|code_start|>@login_required
def edit_account(request):
if request.method == 'POST':
form = AccountForm(request.user, request.POST)
if form.is_valid():
form.save()
messages.success(
request,
"Account updated successfully",
)
return redirect('profile:edit-account')
else:
form = AccountForm(request.user)
return render(request, 'profile/edit/account.html', {
'form': form,
})
@login_required
def edit_url(request):
if request.method == 'POST':
form = URLForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
<|code_end|>
. Use current file imports:
(from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from librement.utils.ajax import ajax
from .forms import ProfileForm, AccountForm, URLForm, PictureForm, PasswordForm
from .utils import get_rss_feed)
and context including class names, function names, or small code snippets from other files:
# Path: src/librement/profile/forms.py
# class ProfileForm(forms.ModelForm):
# class Meta:
# model = Profile
# fields = (
# 'display_name',
# 'biography',
# 'rss_url',
# )
#
# class AccountForm(dict):
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# for key, klass, fn in (
# ('user', AccountUserForm, lambda x: x),
# ('profile', AccountProfileForm, lambda x: x.profile),
# ):
# self[key] = klass(instance=fn(user), *args, **kwargs)
#
# def save(self):
# return [x.save() for x in self.values()]
#
# def is_valid(self):
# return all(x.is_valid() for x in self.values())
#
# class URLForm(forms.ModelForm):
# username = forms.RegexField(regex=r'^[\w-]+$')
#
# class Meta:
# model = User
# fields = (
# 'username',
# )
#
# class PictureForm(forms.Form):
# picture = forms.ImageField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PictureForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.profile.picture.save(
# self.cleaned_data['picture']
# )
# self.user.profile.save()
#
# class PasswordForm(forms.Form):
# password_old = forms.CharField()
# password = forms.CharField()
# password_confirm = forms.CharField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PasswordForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.set_password(self.cleaned_data['password'])
# self.user.save()
#
# def clean_password_old(self):
# val = self.cleaned_data['password_old']
#
# if not self.user.check_password(val):
# raise forms.ValidationError(
# "Password is not correct."
# )
#
# return val
#
# def clean_password_confirm(self):
# password = self.cleaned_data.get('password', '')
# password_confirm = self.cleaned_data['password_confirm']
#
# if password != password_confirm:
# raise forms.ValidationError("Passwords do not match.")
#
# if len(password) < 8:
# raise forms.ValidationError(
# "Password must be at least 8 characters"
# )
#
# return password
#
# Path: src/librement/profile/utils.py
# def get_rss_feed(url):
# if not url:
# return None
#
# key = 'feed:%s' % hashlib.sha1(url).hexdigest()
# feed = cache.get(key)
#
# if feed is None:
# feed = feedparser.parse(url)
# cache.set(key, feed, 3600)
#
# return feed
. Output only the next line. | messages.success(request, "URL updated successfully") |
Here is a snippet: <|code_start|># Copyright 2012 The Librement Developers
#
# See the AUTHORS file at the top-level directory of this distribution
# and at http://librement.net/copyright/
#
# This file is part of Librement. It is subject to the license terms in
# the LICENSE file found in the top-level directory of this distribution
# and at http://librement.net/license/. No part of Librement, including
# this file, may be copied, modified, propagated, or distributed except
# according to the terms contained in the LICENSE file.
def view(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'profile/view.html', {
'user': user,
})
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from librement.utils.ajax import ajax
from .forms import ProfileForm, AccountForm, URLForm, PictureForm, PasswordForm
from .utils import get_rss_feed
and context from other files:
# Path: src/librement/profile/forms.py
# class ProfileForm(forms.ModelForm):
# class Meta:
# model = Profile
# fields = (
# 'display_name',
# 'biography',
# 'rss_url',
# )
#
# class AccountForm(dict):
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# for key, klass, fn in (
# ('user', AccountUserForm, lambda x: x),
# ('profile', AccountProfileForm, lambda x: x.profile),
# ):
# self[key] = klass(instance=fn(user), *args, **kwargs)
#
# def save(self):
# return [x.save() for x in self.values()]
#
# def is_valid(self):
# return all(x.is_valid() for x in self.values())
#
# class URLForm(forms.ModelForm):
# username = forms.RegexField(regex=r'^[\w-]+$')
#
# class Meta:
# model = User
# fields = (
# 'username',
# )
#
# class PictureForm(forms.Form):
# picture = forms.ImageField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PictureForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.profile.picture.save(
# self.cleaned_data['picture']
# )
# self.user.profile.save()
#
# class PasswordForm(forms.Form):
# password_old = forms.CharField()
# password = forms.CharField()
# password_confirm = forms.CharField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PasswordForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.set_password(self.cleaned_data['password'])
# self.user.save()
#
# def clean_password_old(self):
# val = self.cleaned_data['password_old']
#
# if not self.user.check_password(val):
# raise forms.ValidationError(
# "Password is not correct."
# )
#
# return val
#
# def clean_password_confirm(self):
# password = self.cleaned_data.get('password', '')
# password_confirm = self.cleaned_data['password_confirm']
#
# if password != password_confirm:
# raise forms.ValidationError("Passwords do not match.")
#
# if len(password) < 8:
# raise forms.ValidationError(
# "Password must be at least 8 characters"
# )
#
# return password
#
# Path: src/librement/profile/utils.py
# def get_rss_feed(url):
# if not url:
# return None
#
# key = 'feed:%s' % hashlib.sha1(url).hexdigest()
# feed = cache.get(key)
#
# if feed is None:
# feed = feedparser.parse(url)
# cache.set(key, feed, 3600)
#
# return feed
, which may include functions, classes, or code. Output only the next line. | @ajax() |
Given snippet: <|code_start|> 'user': user,
})
@ajax()
def xhr_rss(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'profile/rss.html', {
'feed': get_rss_feed(user.profile.rss_url),
})
@login_required
def edit(request):
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
messages.success(request, "Profile updated successfully")
return redirect('profile:edit')
else:
form = ProfileForm(instance=request.user.profile)
return render(request, 'profile/edit/view.html', {
'form': form,
})
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from librement.utils.ajax import ajax
from .forms import ProfileForm, AccountForm, URLForm, PictureForm, PasswordForm
from .utils import get_rss_feed
and context:
# Path: src/librement/profile/forms.py
# class ProfileForm(forms.ModelForm):
# class Meta:
# model = Profile
# fields = (
# 'display_name',
# 'biography',
# 'rss_url',
# )
#
# class AccountForm(dict):
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# for key, klass, fn in (
# ('user', AccountUserForm, lambda x: x),
# ('profile', AccountProfileForm, lambda x: x.profile),
# ):
# self[key] = klass(instance=fn(user), *args, **kwargs)
#
# def save(self):
# return [x.save() for x in self.values()]
#
# def is_valid(self):
# return all(x.is_valid() for x in self.values())
#
# class URLForm(forms.ModelForm):
# username = forms.RegexField(regex=r'^[\w-]+$')
#
# class Meta:
# model = User
# fields = (
# 'username',
# )
#
# class PictureForm(forms.Form):
# picture = forms.ImageField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PictureForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.profile.picture.save(
# self.cleaned_data['picture']
# )
# self.user.profile.save()
#
# class PasswordForm(forms.Form):
# password_old = forms.CharField()
# password = forms.CharField()
# password_confirm = forms.CharField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PasswordForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.set_password(self.cleaned_data['password'])
# self.user.save()
#
# def clean_password_old(self):
# val = self.cleaned_data['password_old']
#
# if not self.user.check_password(val):
# raise forms.ValidationError(
# "Password is not correct."
# )
#
# return val
#
# def clean_password_confirm(self):
# password = self.cleaned_data.get('password', '')
# password_confirm = self.cleaned_data['password_confirm']
#
# if password != password_confirm:
# raise forms.ValidationError("Passwords do not match.")
#
# if len(password) < 8:
# raise forms.ValidationError(
# "Password must be at least 8 characters"
# )
#
# return password
#
# Path: src/librement/profile/utils.py
# def get_rss_feed(url):
# if not url:
# return None
#
# key = 'feed:%s' % hashlib.sha1(url).hexdigest()
# feed = cache.get(key)
#
# if feed is None:
# feed = feedparser.parse(url)
# cache.set(key, feed, 3600)
#
# return feed
which might include code, classes, or functions. Output only the next line. | @login_required |
Next line prediction: <|code_start|>
return redirect('profile:edit-account')
else:
form = AccountForm(request.user)
return render(request, 'profile/edit/account.html', {
'form': form,
})
@login_required
def edit_url(request):
if request.method == 'POST':
form = URLForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
messages.success(request, "URL updated successfully")
return redirect('profile:edit-url')
else:
form = URLForm(instance=request.user)
return render(request, 'profile/edit/url.html', {
'form': form,
})
@login_required
<|code_end|>
. Use current file imports:
(from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from librement.utils.ajax import ajax
from .forms import ProfileForm, AccountForm, URLForm, PictureForm, PasswordForm
from .utils import get_rss_feed)
and context including class names, function names, or small code snippets from other files:
# Path: src/librement/profile/forms.py
# class ProfileForm(forms.ModelForm):
# class Meta:
# model = Profile
# fields = (
# 'display_name',
# 'biography',
# 'rss_url',
# )
#
# class AccountForm(dict):
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# for key, klass, fn in (
# ('user', AccountUserForm, lambda x: x),
# ('profile', AccountProfileForm, lambda x: x.profile),
# ):
# self[key] = klass(instance=fn(user), *args, **kwargs)
#
# def save(self):
# return [x.save() for x in self.values()]
#
# def is_valid(self):
# return all(x.is_valid() for x in self.values())
#
# class URLForm(forms.ModelForm):
# username = forms.RegexField(regex=r'^[\w-]+$')
#
# class Meta:
# model = User
# fields = (
# 'username',
# )
#
# class PictureForm(forms.Form):
# picture = forms.ImageField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PictureForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.profile.picture.save(
# self.cleaned_data['picture']
# )
# self.user.profile.save()
#
# class PasswordForm(forms.Form):
# password_old = forms.CharField()
# password = forms.CharField()
# password_confirm = forms.CharField()
#
# def __init__(self, user, *args, **kwargs):
# self.user = user
#
# super(PasswordForm, self).__init__(*args, **kwargs)
#
# def save(self):
# self.user.set_password(self.cleaned_data['password'])
# self.user.save()
#
# def clean_password_old(self):
# val = self.cleaned_data['password_old']
#
# if not self.user.check_password(val):
# raise forms.ValidationError(
# "Password is not correct."
# )
#
# return val
#
# def clean_password_confirm(self):
# password = self.cleaned_data.get('password', '')
# password_confirm = self.cleaned_data['password_confirm']
#
# if password != password_confirm:
# raise forms.ValidationError("Passwords do not match.")
#
# if len(password) < 8:
# raise forms.ValidationError(
# "Password must be at least 8 characters"
# )
#
# return password
#
# Path: src/librement/profile/utils.py
# def get_rss_feed(url):
# if not url:
# return None
#
# key = 'feed:%s' % hashlib.sha1(url).hexdigest()
# feed = cache.get(key)
#
# if feed is None:
# feed = feedparser.parse(url)
# cache.set(key, feed, 3600)
#
# return feed
. Output only the next line. | def edit_picture(request): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.