Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
url(r'^account/$', AccountSettingsView.as_view(), name='settings'),
url(r'^created/$', WebsiteCreatedView.as_view(), name='website_created'),
url(r'^register/$', RegisterView.as_view(), name='register'),
url(r'^websites/$', WebsiteListView.as_view(), name='website_list'),
url(r'^addwebsite/$', AddWebsiteView.as_view(), name='add_website'),
url(r'^editwebsite/(?P<website_id>\d)/$', EditWebsiteView.as_view(), name='edit_website'),
url(r'^signup/$', RegisterView.as_view(), name='signup'),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import patterns, url
from accounts.views import LoginView, RegisterView, WebsiteListView, LogoutView, AddWebsiteView, WebsiteCreatedView, \
AccountSettingsView, EditWebsiteView
and context (functions, classes, or occasionally code) from other files:
# Path: accounts/views.py
# class LoginView(FormView):
# template_name = 'accounts/login.html'
# form_class = AuthenticationForm
#
# def get_success_url(self):
# if 'next' in self.request.GET:
# return self.request.GET['next']
# return reverse_lazy('accounts:website_list')
#
# def form_valid(self, form):
# login(self.request, form.get_user())
# return super(LoginView, self).form_valid(form)
#
# class RegisterView(FormView):
# template_name = 'accounts/register.html'
# form_class = EmailUserCreationForm
# success_url = reverse_lazy('accounts:login')
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Registration successful, you can now sign in.')
# return super(RegisterView, self).form_valid(form)
#
# class WebsiteListView(LoginRequiredMixin, ListView):
# template_name = 'accounts/websites.html'
# context_object_name = 'websites'
#
# def get_queryset(self):
# return self.request.user.website_set.order_by('pk')
#
# class LogoutView(RedirectView):
# url = reverse_lazy('home')
#
# def dispatch(self, *args, **kwargs):
# logout(self.request)
# return super(LogoutView, self).dispatch(*args, **kwargs)
#
# class AddWebsiteView(LoginRequiredMixin, FormView):
# template_name = 'accounts/add_website.html'
# form_class = modelform_factory(Website, exclude=('user', ), widgets={'timezone': django_select2.Select2Widget()})
# success_url = reverse_lazy('accounts:website_list')
#
# def redirect_to_website_created(self, pk):
# return HttpResponseRedirect(reverse_lazy('accounts:website_created') + '?id={}'.format(pk))
#
# def form_valid(self, form):
# website = form.save(commit=False)
# website.user = self.request.user
# website.save()
# return self.redirect_to_website_created(website.pk)
#
# class WebsiteCreatedView(TemplateView):
# template_name = 'accounts/website_created.html'
#
# def get_context_data(self, **kwargs):
# context = super(WebsiteCreatedView, self).get_context_data(**kwargs)
# context['jspath'] = self.request.build_absolute_uri(static('js/insightful.min.js'))
# context['report'] = self.request.build_absolute_uri(reverse('report'))
# if 'id' in self.request.GET:
# context['id'] = self.request.GET['id']
# else:
# context['id'] = '"YOUR WEBSITE ID"'
#
# return context
#
# class AccountSettingsView(FormView):
# form_class = PasswordChangeForm
# template_name = 'accounts/password_change.html'
# success_url = reverse_lazy('accounts:website_list')
#
# def get_form(self, form_class):
# return form_class(self.request.user, **self.get_form_kwargs())
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Password successfully changed.')
# return super(AccountSettingsView, self).form_valid(form)
#
# class EditWebsiteView(AngularAppMixin, FormView):
# template_name = 'accounts/edit_website.html'
# form_class = modelform_factory(Website, exclude=('user', ), widgets={'timezone': django_select2.Select2Widget()})
# success_url = reverse_lazy('accounts:website_list')
#
# def get_form_kwargs(self):
# kwargs = super(EditWebsiteView, self).get_form_kwargs()
# kwargs['instance'] = self.get_website()
# return kwargs
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Website successfully edited.')
# return super(EditWebsiteView, self).form_valid(form)
. Output only the next line. | ) |
Using the snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
url(r'^account/$', AccountSettingsView.as_view(), name='settings'),
url(r'^created/$', WebsiteCreatedView.as_view(), name='website_created'),
url(r'^register/$', RegisterView.as_view(), name='register'),
url(r'^websites/$', WebsiteListView.as_view(), name='website_list'),
url(r'^addwebsite/$', AddWebsiteView.as_view(), name='add_website'),
url(r'^editwebsite/(?P<website_id>\d)/$', EditWebsiteView.as_view(), name='edit_website'),
url(r'^signup/$', RegisterView.as_view(), name='signup'),
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import patterns, url
from accounts.views import LoginView, RegisterView, WebsiteListView, LogoutView, AddWebsiteView, WebsiteCreatedView, \
AccountSettingsView, EditWebsiteView
and context (class names, function names, or code) available:
# Path: accounts/views.py
# class LoginView(FormView):
# template_name = 'accounts/login.html'
# form_class = AuthenticationForm
#
# def get_success_url(self):
# if 'next' in self.request.GET:
# return self.request.GET['next']
# return reverse_lazy('accounts:website_list')
#
# def form_valid(self, form):
# login(self.request, form.get_user())
# return super(LoginView, self).form_valid(form)
#
# class RegisterView(FormView):
# template_name = 'accounts/register.html'
# form_class = EmailUserCreationForm
# success_url = reverse_lazy('accounts:login')
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Registration successful, you can now sign in.')
# return super(RegisterView, self).form_valid(form)
#
# class WebsiteListView(LoginRequiredMixin, ListView):
# template_name = 'accounts/websites.html'
# context_object_name = 'websites'
#
# def get_queryset(self):
# return self.request.user.website_set.order_by('pk')
#
# class LogoutView(RedirectView):
# url = reverse_lazy('home')
#
# def dispatch(self, *args, **kwargs):
# logout(self.request)
# return super(LogoutView, self).dispatch(*args, **kwargs)
#
# class AddWebsiteView(LoginRequiredMixin, FormView):
# template_name = 'accounts/add_website.html'
# form_class = modelform_factory(Website, exclude=('user', ), widgets={'timezone': django_select2.Select2Widget()})
# success_url = reverse_lazy('accounts:website_list')
#
# def redirect_to_website_created(self, pk):
# return HttpResponseRedirect(reverse_lazy('accounts:website_created') + '?id={}'.format(pk))
#
# def form_valid(self, form):
# website = form.save(commit=False)
# website.user = self.request.user
# website.save()
# return self.redirect_to_website_created(website.pk)
#
# class WebsiteCreatedView(TemplateView):
# template_name = 'accounts/website_created.html'
#
# def get_context_data(self, **kwargs):
# context = super(WebsiteCreatedView, self).get_context_data(**kwargs)
# context['jspath'] = self.request.build_absolute_uri(static('js/insightful.min.js'))
# context['report'] = self.request.build_absolute_uri(reverse('report'))
# if 'id' in self.request.GET:
# context['id'] = self.request.GET['id']
# else:
# context['id'] = '"YOUR WEBSITE ID"'
#
# return context
#
# class AccountSettingsView(FormView):
# form_class = PasswordChangeForm
# template_name = 'accounts/password_change.html'
# success_url = reverse_lazy('accounts:website_list')
#
# def get_form(self, form_class):
# return form_class(self.request.user, **self.get_form_kwargs())
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Password successfully changed.')
# return super(AccountSettingsView, self).form_valid(form)
#
# class EditWebsiteView(AngularAppMixin, FormView):
# template_name = 'accounts/edit_website.html'
# form_class = modelform_factory(Website, exclude=('user', ), widgets={'timezone': django_select2.Select2Widget()})
# success_url = reverse_lazy('accounts:website_list')
#
# def get_form_kwargs(self):
# kwargs = super(EditWebsiteView, self).get_form_kwargs()
# kwargs['instance'] = self.get_website()
# return kwargs
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Website successfully edited.')
# return super(EditWebsiteView, self).form_valid(form)
. Output only the next line. | ) |
Given snippet: <|code_start|>
class OverviewJSONView(AngularAppMixin, ChartsUtilityMixin, JSONResponseMixin, View):
@allowed_action
def get_data(self, in_data):
return {'views': self.view_count_today(),
'visitors': self.visitor_count_today(),
'unique_visitors': self.unique_visitor_count_today(),
'mobile': self.mobile_percent(),
'top_pages': self.top_pages()}
def view_count_today(self):
return len(self.pageviews_today.all())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.db.models import Count
from django.views.generic import View
from djangular.views.mixins import allowed_action, JSONResponseMixin
from core.mixins import AngularAppMixin, ChartsUtilityMixin
from core.helpers import cache_until_midnight
and context:
# Path: core/mixins.py
# class AngularAppMixin(LoginRequiredMixin):
# def get_website(self):
# try:
# website = Website.objects.get(pk=self.kwargs['website_id'])
# except Website.DoesNotExist:
# raise Http404('No such website.')
# if website.user != self.request.user:
# raise PermissionDenied('You don\'t have permission to view this website.')
# return website
#
# def website_to_json(self, website):
# return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
#
# class ChartsUtilityMixin(object):
# num_days = None
#
# @property
# def pageviews(self):
# return PageView.objects.filter(session__website=self.kwargs['website_id'])
#
# @property
# def pageviews_today(self):
# return self.pageviews.filter(view_timestamp__gt=self.today_midnight())
#
# @property
# def pageviews_yesterday(self):
# return self.pageviews.filter(view_timestamp__lte=self.today_midnight(),
# view_timestamp__gte=self.today_midnight() - timezone.timedelta(days=1))
#
# @property
# def sessions(self):
# return Session.objects.filter(website=self.kwargs['website_id'])
#
# @property
# def sessions_today(self):
# return self.sessions.filter(timestamp__gt=self.today_midnight())
#
# @property
# def sessions_yesterday(self):
# return self.sessions.filter(timestamp__lt=self.today_midnight(),
# timestamp__gt=self.today_midnight() - timezone.timedelta(days=1))
#
# def past_timestamp(self, **kwargs):
# return timezone.now().astimezone(self.get_website().timezone) - timezone.timedelta(**kwargs)
#
# def today_midnight(self):
# """
# Returns datetime, today at 00:00 am
# One might use now.date(), but that removes timezone data
# """
# return timezone.now().astimezone(self.get_website().timezone).replace(hour=0, minute=0, second=0)
#
# def seconds_until_midnight(self):
# now = timezone.now().astimezone(self.get_website().timezone)
# midnight = now.replace(hour=23, minute=59, second=59)
# diff = (midnight-now).total_seconds()
# return int(diff) + 60
#
# def yesterday_midnight(self):
# return self.today_midnight() - timezone.timedelta(days=1)
#
# def group_by_date(self, queryset, timestamp_field, aggregation_function):
# """
# Take given queryset, filter by website_id, group by day on timestamp_field
# with aggregation_function for last num_days days
# """
# end_date = self.today_midnight()
# truncate_date = get_date_truncate('day', timestamp_field, self.get_website().timezone)
#
# queryset = queryset.extra({'date': truncate_date})
# queryset = queryset.filter(**{timestamp_field + '__lt': end_date,
# timestamp_field + '__gt': end_date - timezone.timedelta(days=self.num_days)})
# # Need something else than a queryset for serialising
# data = list(queryset.values('date').annotate(aggregated_data=aggregation_function).order_by('date'))
# return self.add_zeros(data, self.num_days)
#
# def add_zeros(self, in_data, num_days):
# """
# Add count=0 on dates that aren't present in in_data list from self.group_by_date()
# """
# data = SortedDict()
# end_date = self.today_midnight().date()
# for date in daterange(end_date - timezone.timedelta(days=num_days), end_date):
# for pair in in_data:
#
# # Dates stored as datetime when using postgresql
# if isinstance(pair['date'], datetime.datetime):
# if pair['date'].date() == date:
# data[str(pair['date'].date())] = pair['aggregated_data']
# break
# # Dates stored as string when using sqlite
# elif isinstance(pair['date'], unicode) or isinstance(pair['date'], str):
# if pair['date'] == str(date):
# data[pair['date']] = pair['aggregated_data']
# break
# else:
# raise StandardError('Can\'t figure out the date format in database. '
# 'Not unicode, str or datetime')
# else:
# data[str(date)] = 0
# return data
#
# Path: core/helpers.py
# def cache_until_midnight(method):
# """
# Caches a CBV (class based view) method until local midnight
# Used for calculations that don't use today's data (e.g. monthly chart)
#
# Requires ChartUtilityMixin to access current website's timezone
#
# Cache key is built from module name, method name and
# request path (which must include unique identifier, e.g. website id)
# """
#
# @wraps(method)
# def wrapped(self, *args, **kwargs):
# key = 'django.{0}.{1}():{2}'.format(method.__module__, method.__name__, iri_to_uri(self.request.get_full_path()))
# seconds = self.seconds_until_midnight()
#
# result = cache.get(key)
# if result is None:
# # key not in cache, call actual method and add to cache
# result = method(self, *args, **kwargs)
# cache.set(key, result, seconds)
#
# return result
#
# return wrapped
which might include code, classes, or functions. Output only the next line. | def visitor_count_today(self): |
Predict the next line after this snippet: <|code_start|>
class OverviewJSONView(AngularAppMixin, ChartsUtilityMixin, JSONResponseMixin, View):
@allowed_action
def get_data(self, in_data):
return {'views': self.view_count_today(),
'visitors': self.visitor_count_today(),
<|code_end|>
using the current file's imports:
from django.db.models import Count
from django.views.generic import View
from djangular.views.mixins import allowed_action, JSONResponseMixin
from core.mixins import AngularAppMixin, ChartsUtilityMixin
from core.helpers import cache_until_midnight
and any relevant context from other files:
# Path: core/mixins.py
# class AngularAppMixin(LoginRequiredMixin):
# def get_website(self):
# try:
# website = Website.objects.get(pk=self.kwargs['website_id'])
# except Website.DoesNotExist:
# raise Http404('No such website.')
# if website.user != self.request.user:
# raise PermissionDenied('You don\'t have permission to view this website.')
# return website
#
# def website_to_json(self, website):
# return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
#
# class ChartsUtilityMixin(object):
# num_days = None
#
# @property
# def pageviews(self):
# return PageView.objects.filter(session__website=self.kwargs['website_id'])
#
# @property
# def pageviews_today(self):
# return self.pageviews.filter(view_timestamp__gt=self.today_midnight())
#
# @property
# def pageviews_yesterday(self):
# return self.pageviews.filter(view_timestamp__lte=self.today_midnight(),
# view_timestamp__gte=self.today_midnight() - timezone.timedelta(days=1))
#
# @property
# def sessions(self):
# return Session.objects.filter(website=self.kwargs['website_id'])
#
# @property
# def sessions_today(self):
# return self.sessions.filter(timestamp__gt=self.today_midnight())
#
# @property
# def sessions_yesterday(self):
# return self.sessions.filter(timestamp__lt=self.today_midnight(),
# timestamp__gt=self.today_midnight() - timezone.timedelta(days=1))
#
# def past_timestamp(self, **kwargs):
# return timezone.now().astimezone(self.get_website().timezone) - timezone.timedelta(**kwargs)
#
# def today_midnight(self):
# """
# Returns datetime, today at 00:00 am
# One might use now.date(), but that removes timezone data
# """
# return timezone.now().astimezone(self.get_website().timezone).replace(hour=0, minute=0, second=0)
#
# def seconds_until_midnight(self):
# now = timezone.now().astimezone(self.get_website().timezone)
# midnight = now.replace(hour=23, minute=59, second=59)
# diff = (midnight-now).total_seconds()
# return int(diff) + 60
#
# def yesterday_midnight(self):
# return self.today_midnight() - timezone.timedelta(days=1)
#
# def group_by_date(self, queryset, timestamp_field, aggregation_function):
# """
# Take given queryset, filter by website_id, group by day on timestamp_field
# with aggregation_function for last num_days days
# """
# end_date = self.today_midnight()
# truncate_date = get_date_truncate('day', timestamp_field, self.get_website().timezone)
#
# queryset = queryset.extra({'date': truncate_date})
# queryset = queryset.filter(**{timestamp_field + '__lt': end_date,
# timestamp_field + '__gt': end_date - timezone.timedelta(days=self.num_days)})
# # Need something else than a queryset for serialising
# data = list(queryset.values('date').annotate(aggregated_data=aggregation_function).order_by('date'))
# return self.add_zeros(data, self.num_days)
#
# def add_zeros(self, in_data, num_days):
# """
# Add count=0 on dates that aren't present in in_data list from self.group_by_date()
# """
# data = SortedDict()
# end_date = self.today_midnight().date()
# for date in daterange(end_date - timezone.timedelta(days=num_days), end_date):
# for pair in in_data:
#
# # Dates stored as datetime when using postgresql
# if isinstance(pair['date'], datetime.datetime):
# if pair['date'].date() == date:
# data[str(pair['date'].date())] = pair['aggregated_data']
# break
# # Dates stored as string when using sqlite
# elif isinstance(pair['date'], unicode) or isinstance(pair['date'], str):
# if pair['date'] == str(date):
# data[pair['date']] = pair['aggregated_data']
# break
# else:
# raise StandardError('Can\'t figure out the date format in database. '
# 'Not unicode, str or datetime')
# else:
# data[str(date)] = 0
# return data
#
# Path: core/helpers.py
# def cache_until_midnight(method):
# """
# Caches a CBV (class based view) method until local midnight
# Used for calculations that don't use today's data (e.g. monthly chart)
#
# Requires ChartUtilityMixin to access current website's timezone
#
# Cache key is built from module name, method name and
# request path (which must include unique identifier, e.g. website id)
# """
#
# @wraps(method)
# def wrapped(self, *args, **kwargs):
# key = 'django.{0}.{1}():{2}'.format(method.__module__, method.__name__, iri_to_uri(self.request.get_full_path()))
# seconds = self.seconds_until_midnight()
#
# result = cache.get(key)
# if result is None:
# # key not in cache, call actual method and add to cache
# result = method(self, *args, **kwargs)
# cache.set(key, result, seconds)
#
# return result
#
# return wrapped
. Output only the next line. | 'unique_visitors': self.unique_visitor_count_today(), |
Using the snippet: <|code_start|> self.user = AnalyticsUser.objects.create_user(email='test@test.com', password='password')
def test_user_registration(self):
request = self.factory.post(reverse('accounts:register'), {
'email': 'testemail@gmail.com',
'password1': 'passwd',
'password2': 'passwd'
})
# RequestFactory doesn't support middlewares, need fallback storage for messages
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
setattr(request, '_messages', messages)
response = RegisterView.as_view()(request)
user, created = AnalyticsUser.objects.get_or_create(email='testemail@gmail.com')
self.assertEqual(created, False)
def test_user_login(self):
request = self.factory.post(reverse('accounts:login'), {
'username': 'test@test.com',
'password': 'password'
})
response = LoginView.as_view()(request)
self.assertEqual(response.url, reverse('accounts:website_list'))
def test_website_create(self):
request = self.factory.post(reverse('accounts:add_website'), {
'name': 'Website name',
'url': 'http://test.com',
'timezone': 'Europe/Ljubljana'
<|code_end|>
, determine the next line of code. You have imports:
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from django.test import TestCase
from django.contrib.messages.storage.fallback import FallbackStorage
from accounts.models import AnalyticsUser
from accounts.views import RegisterView, LoginView, AddWebsiteView
from core.models import Website
and context (class names, function names, or code) available:
# Path: accounts/models.py
# class AnalyticsUser(AbstractBaseUser):
# USERNAME_FIELD = 'email'
# email = models.EmailField(unique=True)
# is_active = models.BooleanField(default=True)
#
# objects = EmailUserManager()
#
# def get_full_name(self):
# return self.email
#
# def get_short_name(self):
# return self.email
#
# Path: accounts/views.py
# class RegisterView(FormView):
# template_name = 'accounts/register.html'
# form_class = EmailUserCreationForm
# success_url = reverse_lazy('accounts:login')
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Registration successful, you can now sign in.')
# return super(RegisterView, self).form_valid(form)
#
# class LoginView(FormView):
# template_name = 'accounts/login.html'
# form_class = AuthenticationForm
#
# def get_success_url(self):
# if 'next' in self.request.GET:
# return self.request.GET['next']
# return reverse_lazy('accounts:website_list')
#
# def form_valid(self, form):
# login(self.request, form.get_user())
# return super(LoginView, self).form_valid(form)
#
# class AddWebsiteView(LoginRequiredMixin, FormView):
# template_name = 'accounts/add_website.html'
# form_class = modelform_factory(Website, exclude=('user', ), widgets={'timezone': django_select2.Select2Widget()})
# success_url = reverse_lazy('accounts:website_list')
#
# def redirect_to_website_created(self, pk):
# return HttpResponseRedirect(reverse_lazy('accounts:website_created') + '?id={}'.format(pk))
#
# def form_valid(self, form):
# website = form.save(commit=False)
# website.user = self.request.user
# website.save()
# return self.redirect_to_website_created(website.pk)
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
. Output only the next line. | }) |
Using the snippet: <|code_start|>
class AccountsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = AnalyticsUser.objects.create_user(email='test@test.com', password='password')
def test_user_registration(self):
request = self.factory.post(reverse('accounts:register'), {
'email': 'testemail@gmail.com',
'password1': 'passwd',
'password2': 'passwd'
})
# RequestFactory doesn't support middlewares, need fallback storage for messages
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
setattr(request, '_messages', messages)
response = RegisterView.as_view()(request)
user, created = AnalyticsUser.objects.get_or_create(email='testemail@gmail.com')
self.assertEqual(created, False)
def test_user_login(self):
request = self.factory.post(reverse('accounts:login'), {
'username': 'test@test.com',
'password': 'password'
})
response = LoginView.as_view()(request)
self.assertEqual(response.url, reverse('accounts:website_list'))
<|code_end|>
, determine the next line of code. You have imports:
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from django.test import TestCase
from django.contrib.messages.storage.fallback import FallbackStorage
from accounts.models import AnalyticsUser
from accounts.views import RegisterView, LoginView, AddWebsiteView
from core.models import Website
and context (class names, function names, or code) available:
# Path: accounts/models.py
# class AnalyticsUser(AbstractBaseUser):
# USERNAME_FIELD = 'email'
# email = models.EmailField(unique=True)
# is_active = models.BooleanField(default=True)
#
# objects = EmailUserManager()
#
# def get_full_name(self):
# return self.email
#
# def get_short_name(self):
# return self.email
#
# Path: accounts/views.py
# class RegisterView(FormView):
# template_name = 'accounts/register.html'
# form_class = EmailUserCreationForm
# success_url = reverse_lazy('accounts:login')
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Registration successful, you can now sign in.')
# return super(RegisterView, self).form_valid(form)
#
# class LoginView(FormView):
# template_name = 'accounts/login.html'
# form_class = AuthenticationForm
#
# def get_success_url(self):
# if 'next' in self.request.GET:
# return self.request.GET['next']
# return reverse_lazy('accounts:website_list')
#
# def form_valid(self, form):
# login(self.request, form.get_user())
# return super(LoginView, self).form_valid(form)
#
# class AddWebsiteView(LoginRequiredMixin, FormView):
# template_name = 'accounts/add_website.html'
# form_class = modelform_factory(Website, exclude=('user', ), widgets={'timezone': django_select2.Select2Widget()})
# success_url = reverse_lazy('accounts:website_list')
#
# def redirect_to_website_created(self, pk):
# return HttpResponseRedirect(reverse_lazy('accounts:website_created') + '?id={}'.format(pk))
#
# def form_valid(self, form):
# website = form.save(commit=False)
# website.user = self.request.user
# website.save()
# return self.redirect_to_website_created(website.pk)
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
. Output only the next line. | def test_website_create(self): |
Next line prediction: <|code_start|>
class AccountsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = AnalyticsUser.objects.create_user(email='test@test.com', password='password')
def test_user_registration(self):
request = self.factory.post(reverse('accounts:register'), {
'email': 'testemail@gmail.com',
'password1': 'passwd',
'password2': 'passwd'
})
# RequestFactory doesn't support middlewares, need fallback storage for messages
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
setattr(request, '_messages', messages)
response = RegisterView.as_view()(request)
user, created = AnalyticsUser.objects.get_or_create(email='testemail@gmail.com')
self.assertEqual(created, False)
def test_user_login(self):
<|code_end|>
. Use current file imports:
(from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from django.test import TestCase
from django.contrib.messages.storage.fallback import FallbackStorage
from accounts.models import AnalyticsUser
from accounts.views import RegisterView, LoginView, AddWebsiteView
from core.models import Website)
and context including class names, function names, or small code snippets from other files:
# Path: accounts/models.py
# class AnalyticsUser(AbstractBaseUser):
# USERNAME_FIELD = 'email'
# email = models.EmailField(unique=True)
# is_active = models.BooleanField(default=True)
#
# objects = EmailUserManager()
#
# def get_full_name(self):
# return self.email
#
# def get_short_name(self):
# return self.email
#
# Path: accounts/views.py
# class RegisterView(FormView):
# template_name = 'accounts/register.html'
# form_class = EmailUserCreationForm
# success_url = reverse_lazy('accounts:login')
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Registration successful, you can now sign in.')
# return super(RegisterView, self).form_valid(form)
#
# class LoginView(FormView):
# template_name = 'accounts/login.html'
# form_class = AuthenticationForm
#
# def get_success_url(self):
# if 'next' in self.request.GET:
# return self.request.GET['next']
# return reverse_lazy('accounts:website_list')
#
# def form_valid(self, form):
# login(self.request, form.get_user())
# return super(LoginView, self).form_valid(form)
#
# class AddWebsiteView(LoginRequiredMixin, FormView):
# template_name = 'accounts/add_website.html'
# form_class = modelform_factory(Website, exclude=('user', ), widgets={'timezone': django_select2.Select2Widget()})
# success_url = reverse_lazy('accounts:website_list')
#
# def redirect_to_website_created(self, pk):
# return HttpResponseRedirect(reverse_lazy('accounts:website_created') + '?id={}'.format(pk))
#
# def form_valid(self, form):
# website = form.save(commit=False)
# website.user = self.request.user
# website.save()
# return self.redirect_to_website_created(website.pk)
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
. Output only the next line. | request = self.factory.post(reverse('accounts:login'), { |
Predict the next line after this snippet: <|code_start|>
class AccountsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = AnalyticsUser.objects.create_user(email='test@test.com', password='password')
def test_user_registration(self):
request = self.factory.post(reverse('accounts:register'), {
'email': 'testemail@gmail.com',
'password1': 'passwd',
'password2': 'passwd'
})
# RequestFactory doesn't support middlewares, need fallback storage for messages
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
setattr(request, '_messages', messages)
response = RegisterView.as_view()(request)
user, created = AnalyticsUser.objects.get_or_create(email='testemail@gmail.com')
self.assertEqual(created, False)
def test_user_login(self):
request = self.factory.post(reverse('accounts:login'), {
'username': 'test@test.com',
'password': 'password'
})
response = LoginView.as_view()(request)
self.assertEqual(response.url, reverse('accounts:website_list'))
<|code_end|>
using the current file's imports:
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from django.test import TestCase
from django.contrib.messages.storage.fallback import FallbackStorage
from accounts.models import AnalyticsUser
from accounts.views import RegisterView, LoginView, AddWebsiteView
from core.models import Website
and any relevant context from other files:
# Path: accounts/models.py
# class AnalyticsUser(AbstractBaseUser):
# USERNAME_FIELD = 'email'
# email = models.EmailField(unique=True)
# is_active = models.BooleanField(default=True)
#
# objects = EmailUserManager()
#
# def get_full_name(self):
# return self.email
#
# def get_short_name(self):
# return self.email
#
# Path: accounts/views.py
# class RegisterView(FormView):
# template_name = 'accounts/register.html'
# form_class = EmailUserCreationForm
# success_url = reverse_lazy('accounts:login')
#
# def form_valid(self, form):
# form.save()
# messages.success(self.request, 'Registration successful, you can now sign in.')
# return super(RegisterView, self).form_valid(form)
#
# class LoginView(FormView):
# template_name = 'accounts/login.html'
# form_class = AuthenticationForm
#
# def get_success_url(self):
# if 'next' in self.request.GET:
# return self.request.GET['next']
# return reverse_lazy('accounts:website_list')
#
# def form_valid(self, form):
# login(self.request, form.get_user())
# return super(LoginView, self).form_valid(form)
#
# class AddWebsiteView(LoginRequiredMixin, FormView):
# template_name = 'accounts/add_website.html'
# form_class = modelform_factory(Website, exclude=('user', ), widgets={'timezone': django_select2.Select2Widget()})
# success_url = reverse_lazy('accounts:website_list')
#
# def redirect_to_website_created(self, pk):
# return HttpResponseRedirect(reverse_lazy('accounts:website_created') + '?id={}'.format(pk))
#
# def form_valid(self, form):
# website = form.save(commit=False)
# website.user = self.request.user
# website.save()
# return self.redirect_to_website_created(website.pk)
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
. Output only the next line. | def test_website_create(self): |
Continue the code snippet: <|code_start|>
class MonthlyChartView(AngularAppMixin, JSONResponseMixin, ChartsUtilityMixin, View):
num_days = 30
SERIES = (
('page_views', 'Page views'),
('visits', 'Visitors'),
('unique_visitors', 'Unique visitors'),
<|code_end|>
. Use current file imports:
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Count, Avg
from django.http import HttpResponse
from django.utils.datastructures import SortedDict
from django.views.generic import View
from djangular.views.mixins import JSONResponseMixin
from core.mixins import ChartsUtilityMixin, AngularAppMixin
from core.helpers import cache_until_midnight
and context (classes, functions, or code) from other files:
# Path: core/mixins.py
# class ChartsUtilityMixin(object):
# num_days = None
#
# @property
# def pageviews(self):
# return PageView.objects.filter(session__website=self.kwargs['website_id'])
#
# @property
# def pageviews_today(self):
# return self.pageviews.filter(view_timestamp__gt=self.today_midnight())
#
# @property
# def pageviews_yesterday(self):
# return self.pageviews.filter(view_timestamp__lte=self.today_midnight(),
# view_timestamp__gte=self.today_midnight() - timezone.timedelta(days=1))
#
# @property
# def sessions(self):
# return Session.objects.filter(website=self.kwargs['website_id'])
#
# @property
# def sessions_today(self):
# return self.sessions.filter(timestamp__gt=self.today_midnight())
#
# @property
# def sessions_yesterday(self):
# return self.sessions.filter(timestamp__lt=self.today_midnight(),
# timestamp__gt=self.today_midnight() - timezone.timedelta(days=1))
#
# def past_timestamp(self, **kwargs):
# return timezone.now().astimezone(self.get_website().timezone) - timezone.timedelta(**kwargs)
#
# def today_midnight(self):
# """
# Returns datetime, today at 00:00 am
# One might use now.date(), but that removes timezone data
# """
# return timezone.now().astimezone(self.get_website().timezone).replace(hour=0, minute=0, second=0)
#
# def seconds_until_midnight(self):
# now = timezone.now().astimezone(self.get_website().timezone)
# midnight = now.replace(hour=23, minute=59, second=59)
# diff = (midnight-now).total_seconds()
# return int(diff) + 60
#
# def yesterday_midnight(self):
# return self.today_midnight() - timezone.timedelta(days=1)
#
# def group_by_date(self, queryset, timestamp_field, aggregation_function):
# """
# Take given queryset, filter by website_id, group by day on timestamp_field
# with aggregation_function for last num_days days
# """
# end_date = self.today_midnight()
# truncate_date = get_date_truncate('day', timestamp_field, self.get_website().timezone)
#
# queryset = queryset.extra({'date': truncate_date})
# queryset = queryset.filter(**{timestamp_field + '__lt': end_date,
# timestamp_field + '__gt': end_date - timezone.timedelta(days=self.num_days)})
# # Need something else than a queryset for serialising
# data = list(queryset.values('date').annotate(aggregated_data=aggregation_function).order_by('date'))
# return self.add_zeros(data, self.num_days)
#
# def add_zeros(self, in_data, num_days):
# """
# Add count=0 on dates that aren't present in in_data list from self.group_by_date()
# """
# data = SortedDict()
# end_date = self.today_midnight().date()
# for date in daterange(end_date - timezone.timedelta(days=num_days), end_date):
# for pair in in_data:
#
# # Dates stored as datetime when using postgresql
# if isinstance(pair['date'], datetime.datetime):
# if pair['date'].date() == date:
# data[str(pair['date'].date())] = pair['aggregated_data']
# break
# # Dates stored as string when using sqlite
# elif isinstance(pair['date'], unicode) or isinstance(pair['date'], str):
# if pair['date'] == str(date):
# data[pair['date']] = pair['aggregated_data']
# break
# else:
# raise StandardError('Can\'t figure out the date format in database. '
# 'Not unicode, str or datetime')
# else:
# data[str(date)] = 0
# return data
#
# class AngularAppMixin(LoginRequiredMixin):
# def get_website(self):
# try:
# website = Website.objects.get(pk=self.kwargs['website_id'])
# except Website.DoesNotExist:
# raise Http404('No such website.')
# if website.user != self.request.user:
# raise PermissionDenied('You don\'t have permission to view this website.')
# return website
#
# def website_to_json(self, website):
# return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
#
# Path: core/helpers.py
# def cache_until_midnight(method):
# """
# Caches a CBV (class based view) method until local midnight
# Used for calculations that don't use today's data (e.g. monthly chart)
#
# Requires ChartUtilityMixin to access current website's timezone
#
# Cache key is built from module name, method name and
# request path (which must include unique identifier, e.g. website id)
# """
#
# @wraps(method)
# def wrapped(self, *args, **kwargs):
# key = 'django.{0}.{1}():{2}'.format(method.__module__, method.__name__, iri_to_uri(self.request.get_full_path()))
# seconds = self.seconds_until_midnight()
#
# result = cache.get(key)
# if result is None:
# # key not in cache, call actual method and add to cache
# result = method(self, *args, **kwargs)
# cache.set(key, result, seconds)
#
# return result
#
# return wrapped
. Output only the next line. | ('avg_duration', 'Average view duration'), |
Based on the snippet: <|code_start|>
class LoginView(FormView):
template_name = 'accounts/login.html'
form_class = AuthenticationForm
def get_success_url(self):
if 'next' in self.request.GET:
return self.request.GET['next']
<|code_end|>
, predict the immediate next line with the help of imports:
import django_select2
from django.http.response import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.templatetags.static import static
from django.views.generic.base import TemplateView
from django.contrib.auth import logout
from django.contrib.auth.views import AuthenticationForm, login
from django.core.urlresolvers import reverse_lazy, reverse
from django.forms.models import modelform_factory
from django.views.generic import FormView, ListView, RedirectView
from core.mixins import LoginRequiredMixin, AngularAppMixin
from core.models import Website
from accounts.forms import EmailUserCreationForm
and context (classes, functions, sometimes code) from other files:
# Path: core/mixins.py
# class LoginRequiredMixin(object):
# @method_decorator(login_required)
# def dispatch(self, *args, **kwargs):
# return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
#
# class AngularAppMixin(LoginRequiredMixin):
# def get_website(self):
# try:
# website = Website.objects.get(pk=self.kwargs['website_id'])
# except Website.DoesNotExist:
# raise Http404('No such website.')
# if website.user != self.request.user:
# raise PermissionDenied('You don\'t have permission to view this website.')
# return website
#
# def website_to_json(self, website):
# return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
#
# Path: accounts/forms.py
# class EmailUserCreationForm(UserCreationForm):
# class Meta:
# model = get_user_model()
# fields = (model.USERNAME_FIELD, )
#
# def __init__(self, *args, **kwargs):
# super(EmailUserCreationForm, self).__init__(*args, **kwargs)
# if 'username' not in self.Meta.fields:
# self.fields.pop('username', None)
. Output only the next line. | return reverse_lazy('accounts:website_list') |
Given the following code snippet before the placeholder: <|code_start|>
class LoginView(FormView):
template_name = 'accounts/login.html'
form_class = AuthenticationForm
def get_success_url(self):
if 'next' in self.request.GET:
<|code_end|>
, predict the next line using imports from the current file:
import django_select2
from django.http.response import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.templatetags.static import static
from django.views.generic.base import TemplateView
from django.contrib.auth import logout
from django.contrib.auth.views import AuthenticationForm, login
from django.core.urlresolvers import reverse_lazy, reverse
from django.forms.models import modelform_factory
from django.views.generic import FormView, ListView, RedirectView
from core.mixins import LoginRequiredMixin, AngularAppMixin
from core.models import Website
from accounts.forms import EmailUserCreationForm
and context including class names, function names, and sometimes code from other files:
# Path: core/mixins.py
# class LoginRequiredMixin(object):
# @method_decorator(login_required)
# def dispatch(self, *args, **kwargs):
# return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
#
# class AngularAppMixin(LoginRequiredMixin):
# def get_website(self):
# try:
# website = Website.objects.get(pk=self.kwargs['website_id'])
# except Website.DoesNotExist:
# raise Http404('No such website.')
# if website.user != self.request.user:
# raise PermissionDenied('You don\'t have permission to view this website.')
# return website
#
# def website_to_json(self, website):
# return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
#
# Path: accounts/forms.py
# class EmailUserCreationForm(UserCreationForm):
# class Meta:
# model = get_user_model()
# fields = (model.USERNAME_FIELD, )
#
# def __init__(self, *args, **kwargs):
# super(EmailUserCreationForm, self).__init__(*args, **kwargs)
# if 'username' not in self.Meta.fields:
# self.fields.pop('username', None)
. Output only the next line. | return self.request.GET['next'] |
Given the code snippet: <|code_start|>class LoginView(FormView):
template_name = 'accounts/login.html'
form_class = AuthenticationForm
def get_success_url(self):
if 'next' in self.request.GET:
return self.request.GET['next']
return reverse_lazy('accounts:website_list')
def form_valid(self, form):
login(self.request, form.get_user())
return super(LoginView, self).form_valid(form)
class LogoutView(RedirectView):
url = reverse_lazy('home')
def dispatch(self, *args, **kwargs):
logout(self.request)
return super(LogoutView, self).dispatch(*args, **kwargs)
class RegisterView(FormView):
template_name = 'accounts/register.html'
form_class = EmailUserCreationForm
success_url = reverse_lazy('accounts:login')
def form_valid(self, form):
form.save()
messages.success(self.request, 'Registration successful, you can now sign in.')
<|code_end|>
, generate the next line using the imports in this file:
import django_select2
from django.http.response import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.templatetags.static import static
from django.views.generic.base import TemplateView
from django.contrib.auth import logout
from django.contrib.auth.views import AuthenticationForm, login
from django.core.urlresolvers import reverse_lazy, reverse
from django.forms.models import modelform_factory
from django.views.generic import FormView, ListView, RedirectView
from core.mixins import LoginRequiredMixin, AngularAppMixin
from core.models import Website
from accounts.forms import EmailUserCreationForm
and context (functions, classes, or occasionally code) from other files:
# Path: core/mixins.py
# class LoginRequiredMixin(object):
# @method_decorator(login_required)
# def dispatch(self, *args, **kwargs):
# return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
#
# class AngularAppMixin(LoginRequiredMixin):
# def get_website(self):
# try:
# website = Website.objects.get(pk=self.kwargs['website_id'])
# except Website.DoesNotExist:
# raise Http404('No such website.')
# if website.user != self.request.user:
# raise PermissionDenied('You don\'t have permission to view this website.')
# return website
#
# def website_to_json(self, website):
# return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
#
# Path: accounts/forms.py
# class EmailUserCreationForm(UserCreationForm):
# class Meta:
# model = get_user_model()
# fields = (model.USERNAME_FIELD, )
#
# def __init__(self, *args, **kwargs):
# super(EmailUserCreationForm, self).__init__(*args, **kwargs)
# if 'username' not in self.Meta.fields:
# self.fields.pop('username', None)
. Output only the next line. | return super(RegisterView, self).form_valid(form) |
Given snippet: <|code_start|>class RegisterView(FormView):
template_name = 'accounts/register.html'
form_class = EmailUserCreationForm
success_url = reverse_lazy('accounts:login')
def form_valid(self, form):
form.save()
messages.success(self.request, 'Registration successful, you can now sign in.')
return super(RegisterView, self).form_valid(form)
class AccountSettingsView(FormView):
form_class = PasswordChangeForm
template_name = 'accounts/password_change.html'
success_url = reverse_lazy('accounts:website_list')
def get_form(self, form_class):
return form_class(self.request.user, **self.get_form_kwargs())
def form_valid(self, form):
form.save()
messages.success(self.request, 'Password successfully changed.')
return super(AccountSettingsView, self).form_valid(form)
class WebsiteListView(LoginRequiredMixin, ListView):
template_name = 'accounts/websites.html'
context_object_name = 'websites'
def get_queryset(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import django_select2
from django.http.response import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.templatetags.static import static
from django.views.generic.base import TemplateView
from django.contrib.auth import logout
from django.contrib.auth.views import AuthenticationForm, login
from django.core.urlresolvers import reverse_lazy, reverse
from django.forms.models import modelform_factory
from django.views.generic import FormView, ListView, RedirectView
from core.mixins import LoginRequiredMixin, AngularAppMixin
from core.models import Website
from accounts.forms import EmailUserCreationForm
and context:
# Path: core/mixins.py
# class LoginRequiredMixin(object):
# @method_decorator(login_required)
# def dispatch(self, *args, **kwargs):
# return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
#
# class AngularAppMixin(LoginRequiredMixin):
# def get_website(self):
# try:
# website = Website.objects.get(pk=self.kwargs['website_id'])
# except Website.DoesNotExist:
# raise Http404('No such website.')
# if website.user != self.request.user:
# raise PermissionDenied('You don\'t have permission to view this website.')
# return website
#
# def website_to_json(self, website):
# return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
#
# Path: accounts/forms.py
# class EmailUserCreationForm(UserCreationForm):
# class Meta:
# model = get_user_model()
# fields = (model.USERNAME_FIELD, )
#
# def __init__(self, *args, **kwargs):
# super(EmailUserCreationForm, self).__init__(*args, **kwargs)
# if 'username' not in self.Meta.fields:
# self.fields.pop('username', None)
which might include code, classes, or functions. Output only the next line. | return self.request.user.website_set.order_by('pk') |
Predict the next line after this snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='website/home.html'), name='home'),
url(r'^learnmore$', TemplateView.as_view(template_name='website/learnmore.html'), name='learnmore'),
url(r'^report/$', ReportView.as_view(), name='report'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^app/(?P<website_id>\d)/', AngularView.as_view(), name='app'), # angular app
<|code_end|>
using the current file's imports:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from core.views import ReportView, AngularView
and any relevant context from other files:
# Path: core/views.py
# class ReportView(View):
# @method_decorator(csrf_exempt)
# def dispatch(self, request, *args, **kwargs):
# return super(ReportView, self).dispatch(request, *args, **kwargs)
#
# def post(self, request, *args, **kwargs):
# website = get_object_or_404(Website, pk=request.POST['id'])
# post = request.POST.copy()
#
# user, created = TrackerUser.objects.get_or_create(uuid=post['uuid'])
# if created:
# user.http_agent = request.META['HTTP_USER_AGENT']
# user.remote_addr = request.META['REMOTE_ADDR']
# user.mobile = request.mobile
# user.save()
#
# session = user.get_session(website)
# last_view = session.pageview_set.last()
# if last_view:
# last_view.duration = int((timezone.now() - last_view.view_timestamp).total_seconds())
# if 'i_active_time' in post:
# last_view.active_duration = post.pop('i_active_time')[0]
# last_view.save()
#
# for key in filter(lambda x: x.startswith('i_'), post):
# content, created = TrackedContent.objects.get_or_create(website=website, name=key[2:])
# ContentInteraction(content=content,
# page_view=last_view,
# duration=request.POST[key][0]).save() # remove v_ prefix
#
# PageView(session=session, path=post['path']).save()
# return HttpResponse(status=204) # Http No content
#
# class AngularView(AngularAppMixin, TemplateView):
# template_name = 'core/app.html'
#
# def get_context_data(self, **kwargs):
# context = super(AngularView, self).get_context_data(**kwargs)
# website = self.get_website()
# context.update(static_url=settings.STATIC_URL,
# website=website,
# website_json=self.website_to_json(website),
# series=mark_safe(json.dumps(MonthlyChartView.SERIES)))
# return context
. Output only the next line. | url(r'api/', include('core.apiurls', namespace='api')), |
Given the code snippet: <|code_start|> return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
class ChartsUtilityMixin(object):
num_days = None
@property
def pageviews(self):
return PageView.objects.filter(session__website=self.kwargs['website_id'])
@property
def pageviews_today(self):
return self.pageviews.filter(view_timestamp__gt=self.today_midnight())
@property
def pageviews_yesterday(self):
return self.pageviews.filter(view_timestamp__lte=self.today_midnight(),
view_timestamp__gte=self.today_midnight() - timezone.timedelta(days=1))
@property
def sessions(self):
return Session.objects.filter(website=self.kwargs['website_id'])
@property
def sessions_today(self):
return self.sessions.filter(timestamp__gt=self.today_midnight())
@property
def sessions_yesterday(self):
return self.sessions.filter(timestamp__lt=self.today_midnight(),
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import json
from core.helpers import get_date_truncate
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.forms import model_to_dict
from django.http import Http404
from django.utils import timezone
from django.utils.datastructures import SortedDict
from django.utils.decorators import method_decorator
from django.utils.safestring import mark_safe
from core.models import Website, PageView, Session
from overview.helpers import daterange
and context (functions, classes, or occasionally code) from other files:
# Path: core/helpers.py
# def get_date_truncate(truncate, fieldname, timezone):
# if connection.vendor != 'postgresql':
# warnings.warn('Not running on PostgreSQL, timezone support not entirely functional on other backends yet. '
# 'Falling back to no-timezone mode in some calculations.')
# return connection.ops.date_trunc_sql(truncate, fieldname)
# return "DATE_TRUNC('{0}', {1} AT TIME ZONE INTERVAL '{2}')".format(truncate, fieldname, timezone_offset(timezone))
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
#
# class PageView(models.Model):
# session = models.ForeignKey('Session')
# path = models.CharField(max_length=255)
# view_timestamp = models.DateTimeField(auto_now_add=True)
# # Duration in seconds
# duration = models.IntegerField(default=0)
# active_duration = models.IntegerField(default=0)
#
# class Meta:
# ordering = ('view_timestamp', )
#
# class Session(models.Model):
# timestamp = models.DateTimeField(auto_now_add=True)
# user = models.ForeignKey('TrackerUser')
# website = models.ForeignKey('Website')
#
# class Meta:
# ordering = ('timestamp', )
#
# Path: overview/helpers.py
# def daterange(start_date, end_date):
# for n in range(int((end_date - start_date).days)):
# yield start_date + timedelta(days=n)
. Output only the next line. | timestamp__gt=self.today_midnight() - timezone.timedelta(days=1)) |
Predict the next line for this snippet: <|code_start|> def get_website(self):
try:
website = Website.objects.get(pk=self.kwargs['website_id'])
except Website.DoesNotExist:
raise Http404('No such website.')
if website.user != self.request.user:
raise PermissionDenied('You don\'t have permission to view this website.')
return website
def website_to_json(self, website):
return mark_safe(json.dumps(model_to_dict(website, exclude=('timezone', ))))
class ChartsUtilityMixin(object):
num_days = None
@property
def pageviews(self):
return PageView.objects.filter(session__website=self.kwargs['website_id'])
@property
def pageviews_today(self):
return self.pageviews.filter(view_timestamp__gt=self.today_midnight())
@property
def pageviews_yesterday(self):
return self.pageviews.filter(view_timestamp__lte=self.today_midnight(),
view_timestamp__gte=self.today_midnight() - timezone.timedelta(days=1))
@property
<|code_end|>
with the help of current file imports:
import datetime
import json
from core.helpers import get_date_truncate
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.forms import model_to_dict
from django.http import Http404
from django.utils import timezone
from django.utils.datastructures import SortedDict
from django.utils.decorators import method_decorator
from django.utils.safestring import mark_safe
from core.models import Website, PageView, Session
from overview.helpers import daterange
and context from other files:
# Path: core/helpers.py
# def get_date_truncate(truncate, fieldname, timezone):
# if connection.vendor != 'postgresql':
# warnings.warn('Not running on PostgreSQL, timezone support not entirely functional on other backends yet. '
# 'Falling back to no-timezone mode in some calculations.')
# return connection.ops.date_trunc_sql(truncate, fieldname)
# return "DATE_TRUNC('{0}', {1} AT TIME ZONE INTERVAL '{2}')".format(truncate, fieldname, timezone_offset(timezone))
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
#
# class PageView(models.Model):
# session = models.ForeignKey('Session')
# path = models.CharField(max_length=255)
# view_timestamp = models.DateTimeField(auto_now_add=True)
# # Duration in seconds
# duration = models.IntegerField(default=0)
# active_duration = models.IntegerField(default=0)
#
# class Meta:
# ordering = ('view_timestamp', )
#
# class Session(models.Model):
# timestamp = models.DateTimeField(auto_now_add=True)
# user = models.ForeignKey('TrackerUser')
# website = models.ForeignKey('Website')
#
# class Meta:
# ordering = ('timestamp', )
#
# Path: overview/helpers.py
# def daterange(start_date, end_date):
# for n in range(int((end_date - start_date).days)):
# yield start_date + timedelta(days=n)
, which may contain function names, class names, or code. Output only the next line. | def sessions(self): |
Given snippet: <|code_start|>class ChartsUtilityMixin(object):
num_days = None
@property
def pageviews(self):
return PageView.objects.filter(session__website=self.kwargs['website_id'])
@property
def pageviews_today(self):
return self.pageviews.filter(view_timestamp__gt=self.today_midnight())
@property
def pageviews_yesterday(self):
return self.pageviews.filter(view_timestamp__lte=self.today_midnight(),
view_timestamp__gte=self.today_midnight() - timezone.timedelta(days=1))
@property
def sessions(self):
return Session.objects.filter(website=self.kwargs['website_id'])
@property
def sessions_today(self):
return self.sessions.filter(timestamp__gt=self.today_midnight())
@property
def sessions_yesterday(self):
return self.sessions.filter(timestamp__lt=self.today_midnight(),
timestamp__gt=self.today_midnight() - timezone.timedelta(days=1))
def past_timestamp(self, **kwargs):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import json
from core.helpers import get_date_truncate
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.forms import model_to_dict
from django.http import Http404
from django.utils import timezone
from django.utils.datastructures import SortedDict
from django.utils.decorators import method_decorator
from django.utils.safestring import mark_safe
from core.models import Website, PageView, Session
from overview.helpers import daterange
and context:
# Path: core/helpers.py
# def get_date_truncate(truncate, fieldname, timezone):
# if connection.vendor != 'postgresql':
# warnings.warn('Not running on PostgreSQL, timezone support not entirely functional on other backends yet. '
# 'Falling back to no-timezone mode in some calculations.')
# return connection.ops.date_trunc_sql(truncate, fieldname)
# return "DATE_TRUNC('{0}', {1} AT TIME ZONE INTERVAL '{2}')".format(truncate, fieldname, timezone_offset(timezone))
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
#
# class PageView(models.Model):
# session = models.ForeignKey('Session')
# path = models.CharField(max_length=255)
# view_timestamp = models.DateTimeField(auto_now_add=True)
# # Duration in seconds
# duration = models.IntegerField(default=0)
# active_duration = models.IntegerField(default=0)
#
# class Meta:
# ordering = ('view_timestamp', )
#
# class Session(models.Model):
# timestamp = models.DateTimeField(auto_now_add=True)
# user = models.ForeignKey('TrackerUser')
# website = models.ForeignKey('Website')
#
# class Meta:
# ordering = ('timestamp', )
#
# Path: overview/helpers.py
# def daterange(start_date, end_date):
# for n in range(int((end_date - start_date).days)):
# yield start_date + timedelta(days=n)
which might include code, classes, or functions. Output only the next line. | return timezone.now().astimezone(self.get_website().timezone) - timezone.timedelta(**kwargs) |
Given the following code snippet before the placeholder: <|code_start|>
class LoginRequiredMixin(object):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
class AngularAppMixin(LoginRequiredMixin):
def get_website(self):
try:
website = Website.objects.get(pk=self.kwargs['website_id'])
except Website.DoesNotExist:
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import json
from core.helpers import get_date_truncate
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.forms import model_to_dict
from django.http import Http404
from django.utils import timezone
from django.utils.datastructures import SortedDict
from django.utils.decorators import method_decorator
from django.utils.safestring import mark_safe
from core.models import Website, PageView, Session
from overview.helpers import daterange
and context including class names, function names, and sometimes code from other files:
# Path: core/helpers.py
# def get_date_truncate(truncate, fieldname, timezone):
# if connection.vendor != 'postgresql':
# warnings.warn('Not running on PostgreSQL, timezone support not entirely functional on other backends yet. '
# 'Falling back to no-timezone mode in some calculations.')
# return connection.ops.date_trunc_sql(truncate, fieldname)
# return "DATE_TRUNC('{0}', {1} AT TIME ZONE INTERVAL '{2}')".format(truncate, fieldname, timezone_offset(timezone))
#
# Path: core/models.py
# class Website(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# url = models.URLField()
# timezone = TimeZoneField()
#
# def __unicode__(self):
# return self.name
#
# def view_count_today(self):
# today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
# return len(PageView.objects.filter(session__website=self,
# view_timestamp__gt=today_midnight))
#
# class PageView(models.Model):
# session = models.ForeignKey('Session')
# path = models.CharField(max_length=255)
# view_timestamp = models.DateTimeField(auto_now_add=True)
# # Duration in seconds
# duration = models.IntegerField(default=0)
# active_duration = models.IntegerField(default=0)
#
# class Meta:
# ordering = ('view_timestamp', )
#
# class Session(models.Model):
# timestamp = models.DateTimeField(auto_now_add=True)
# user = models.ForeignKey('TrackerUser')
# website = models.ForeignKey('Website')
#
# class Meta:
# ordering = ('timestamp', )
#
# Path: overview/helpers.py
# def daterange(start_date, end_date):
# for n in range(int((end_date - start_date).days)):
# yield start_date + timedelta(days=n)
. Output only the next line. | raise Http404('No such website.') |
Based on the snippet: <|code_start|>
class Website(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
name = models.CharField(max_length=255)
url = models.URLField()
timezone = TimeZoneField()
def __unicode__(self):
return self.name
def view_count_today(self):
today_midnight = timezone.now().astimezone(self.timezone).replace(hour=0, minute=0, second=0)
return len(PageView.objects.filter(session__website=self,
view_timestamp__gt=today_midnight))
class TrackerUser(GeoIpMixin, models.Model):
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from django.conf import settings
from django.db import models
from django.utils import timezone
from timezone_field.fields import TimeZoneField
from ua_parser import user_agent_parser
from geoip.mixins import GeoIpMixin
and context (classes, functions, sometimes code) from other files:
# Path: geoip/mixins.py
# class GeoIpMixin(object):
# gi = pygeoip.GeoIP(os.path.join(BASE_DIR, 'GeoIP.dat'))
#
# def ip_lookup(self, ip):
# code = self.gi.country_code_by_addr(ip).lower()
# if not code:
# return ['unknown', 'Unknown']
# return [self.gi.country_code_by_addr(ip).lower(),
# self.gi.country_name_by_addr(ip)]
. Output only the next line. | uuid = models.CharField(max_length=50) |
Based on the snippet: <|code_start|> """Request to cancel an activity task failed"""
def __init__(self, event_id, activity_id, cause, decision_task_completed_event_id):
super(RequestCancelActivityTaskFailedError, self).__init__(
event_id, activity_id, decision_task_completed_event_id)
self.activity_id = activity_id
self.cause = cause
self.decision_task_completed_event_id = decision_task_completed_event_id
def __repr__(self):
return ("<%s at %s event_id=%s activity_id=%s cause=%s "
"decision_task_completed_event_id=%s >") % (
self.__class__.__name__, hex(id(self)),
self.event_id, self.activity_id, self.cause,
self.decision_task_completed_event_id)
class WorkflowError(DecisionException):
"""Base class for exceptions used to report failure of the originating
workflow"""
def __init__(self, event_id, workflow_type, workflow_execution):
super(WorkflowError, self).__init__(event_id)
self.workflow_type = workflow_type
self.workflow_execution = workflow_execution
def __repr__(self):
return ("<%s at %s event_id=%s workflow_type=%s "
"workflow_execution=%s>") % (
self.__class__.__name__, hex(id(self)),
self.event_id, self.workflow_type,
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import traceback
from .core.exceptions import CancelledError
and context (classes, functions, sometimes code) from other files:
# Path: botoflow/core/exceptions.py
# class CancelledError(Exception):
# """
# The Future was cancelled
# """
#
# @property
# def cause(self):
# return self
. Output only the next line. | self.workflow_execution) |
Using the snippet: <|code_start|> def task_func():
task_raises_recursive()
@task_func.do_except
def except_func(err):
self.tb_str = format_exc()
ev = AsyncEventLoop()
with ev:
task_func()
ev.execute_all_tasks()
self.assertTrue(self.tb_str)
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_async(self):
@coroutine
def raises():
raise RuntimeError("TestErr")
@coroutine
def main():
try:
yield raises()
except RuntimeError:
self.tb_str = "".join(format_exc())
ev = AsyncEventLoop()
with ev:
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import unittest
import logging
import pytest
import sys
import six
from botoflow.core.async_event_loop import AsyncEventLoop
from botoflow.core.decorators import coroutine, task
from botoflow.core.async_traceback import format_exc, print_exc
from botoflow.logging_filters import BotoflowFilter
and context (class names, function names, or code) available:
# Path: botoflow/core/async_event_loop.py
# class AsyncEventLoop(object):
# """
# TODO Document
# """
#
# def __init__(self):
# self.tasks = deque()
# self.root_context = AsyncRootTaskContext(weakref.proxy(self))
#
# def __enter__(self):
# set_async_context(self.root_context)
# return self.root_context
#
# # noinspection PyUnusedLocal
# def __exit__(self, exc_type, err, tb):
# set_async_context(None)
#
# def execute(self, task):
# if DEBUG:
# log.debug("Adding task: %s", task)
# self.tasks.append(task)
#
# def execute_now(self, task):
# if DEBUG:
# log.debug("Prepending task: %s", task)
# self.tasks.appendleft(task)
#
# def execute_all_tasks(self):
# while self.execute_queued_task():
# pass
#
# def execute_queued_task(self):
# if DEBUG:
# log.debug("Task queue: %s", self.tasks)
# try:
# task = self.tasks.popleft()
# if not task.done:
# if DEBUG:
# log.debug("Running task: %s", task)
# task.run()
# except IndexError: # no more tasks
# return False
# return True
#
# Path: botoflow/core/decorators.py
# DEBUG = False
# def _task(daemon=False):
# def __task(func):
# def inner_task(*args, **kwargs):
# def _do_except_wrapper(except_func):
# def _do_finally_wrapper(finally_func):
# def __init__(self, func, daemon):
# def _progress_function(self, future, *args, **kwargs):
# def _progress_except(self, future, except_func, err):
# def __get__(self, instance, cls):
# def __call__(self, *args, **kwargs):
# def _coroutine(daemon=False):
# def __coroutine(func=None):
# def ___coroutine(func):
# class CoroutineDecorator(object):
#
# Path: botoflow/core/async_traceback.py
# def format_exc(limit=None, exception=None, tb_list=None):
# """
# This is like print_exc(limit) but returns a string instead of printing to a
# file.
# """
# result = ["Traceback (most recent call last):\n"]
# if exception is None:
# exception = get_context_with_traceback(get_async_context()).exception
#
# if tb_list is None:
# tb_list = extract_tb(limit)
#
# if tb_list:
# result.extend(traceback.format_list(tb_list))
# result.extend(traceback.format_exception_only(exception.__class__,
# exception))
# return result
# else:
# return None
#
# def print_exc(limit=None, file=None):
# """
# Print exception information and up to limit stack trace entries to file
# """
# if file is None:
# file = sys.stderr
#
# formatted_exc = format_exc(limit)
# if formatted_exc is not None:
# for line in formatted_exc:
# file.write(line)
#
# Path: botoflow/logging_filters.py
# class BotoflowFilter(logging.Filter):
# """You can use this filter with Python's :py:mod:`logging` module to filter out
# botoflow logs that are being replayed by the decider.
#
# For example::
#
# import logging
# from botoflow.logging_filters import BotoflowFilter
#
# logging.basicConfig(level=logging.DEBUG,
# format='%(filename)s:%(lineno)d (%(funcName)s) - %(message)s')
#
# logging.getLogger('botoflow').addFilter(BotoflowFilter())
#
# """
#
# def __init__(self, name='', filter_replaying=True):
# super(BotoflowFilter, self).__init__(name)
# self._filter_replaying = filter_replaying
#
# def filter(self, record):
# try:
# if self._filter_replaying and botoflow.get_context().replaying:
# return 0
# except AttributeError:
# pass
# return 1
. Output only the next line. | main() |
Given the code snippet: <|code_start|> self.tb_str = None
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_format(self):
@task
def task_func():
raise RuntimeError("Test")
@task_func.do_except
def except_func(err):
self.tb_str = "".join(format_exc())
ev = AsyncEventLoop()
with ev:
task_func()
ev.execute_all_tasks()
self.assertTrue(self.tb_str)
self.assertEqual(1, self.tb_str.count('---continuation---'))
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_print(self):
@task
def task_func():
raise RuntimeError("Test")
@task_func.do_except
def except_func(err):
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import unittest
import logging
import pytest
import sys
import six
from botoflow.core.async_event_loop import AsyncEventLoop
from botoflow.core.decorators import coroutine, task
from botoflow.core.async_traceback import format_exc, print_exc
from botoflow.logging_filters import BotoflowFilter
and context (functions, classes, or occasionally code) from other files:
# Path: botoflow/core/async_event_loop.py
# class AsyncEventLoop(object):
# """
# TODO Document
# """
#
# def __init__(self):
# self.tasks = deque()
# self.root_context = AsyncRootTaskContext(weakref.proxy(self))
#
# def __enter__(self):
# set_async_context(self.root_context)
# return self.root_context
#
# # noinspection PyUnusedLocal
# def __exit__(self, exc_type, err, tb):
# set_async_context(None)
#
# def execute(self, task):
# if DEBUG:
# log.debug("Adding task: %s", task)
# self.tasks.append(task)
#
# def execute_now(self, task):
# if DEBUG:
# log.debug("Prepending task: %s", task)
# self.tasks.appendleft(task)
#
# def execute_all_tasks(self):
# while self.execute_queued_task():
# pass
#
# def execute_queued_task(self):
# if DEBUG:
# log.debug("Task queue: %s", self.tasks)
# try:
# task = self.tasks.popleft()
# if not task.done:
# if DEBUG:
# log.debug("Running task: %s", task)
# task.run()
# except IndexError: # no more tasks
# return False
# return True
#
# Path: botoflow/core/decorators.py
# DEBUG = False
# def _task(daemon=False):
# def __task(func):
# def inner_task(*args, **kwargs):
# def _do_except_wrapper(except_func):
# def _do_finally_wrapper(finally_func):
# def __init__(self, func, daemon):
# def _progress_function(self, future, *args, **kwargs):
# def _progress_except(self, future, except_func, err):
# def __get__(self, instance, cls):
# def __call__(self, *args, **kwargs):
# def _coroutine(daemon=False):
# def __coroutine(func=None):
# def ___coroutine(func):
# class CoroutineDecorator(object):
#
# Path: botoflow/core/async_traceback.py
# def format_exc(limit=None, exception=None, tb_list=None):
# """
# This is like print_exc(limit) but returns a string instead of printing to a
# file.
# """
# result = ["Traceback (most recent call last):\n"]
# if exception is None:
# exception = get_context_with_traceback(get_async_context()).exception
#
# if tb_list is None:
# tb_list = extract_tb(limit)
#
# if tb_list:
# result.extend(traceback.format_list(tb_list))
# result.extend(traceback.format_exception_only(exception.__class__,
# exception))
# return result
# else:
# return None
#
# def print_exc(limit=None, file=None):
# """
# Print exception information and up to limit stack trace entries to file
# """
# if file is None:
# file = sys.stderr
#
# formatted_exc = format_exc(limit)
# if formatted_exc is not None:
# for line in formatted_exc:
# file.write(line)
#
# Path: botoflow/logging_filters.py
# class BotoflowFilter(logging.Filter):
# """You can use this filter with Python's :py:mod:`logging` module to filter out
# botoflow logs that are being replayed by the decider.
#
# For example::
#
# import logging
# from botoflow.logging_filters import BotoflowFilter
#
# logging.basicConfig(level=logging.DEBUG,
# format='%(filename)s:%(lineno)d (%(funcName)s) - %(message)s')
#
# logging.getLogger('botoflow').addFilter(BotoflowFilter())
#
# """
#
# def __init__(self, name='', filter_replaying=True):
# super(BotoflowFilter, self).__init__(name)
# self._filter_replaying = filter_replaying
#
# def filter(self, record):
# try:
# if self._filter_replaying and botoflow.get_context().replaying:
# return 0
# except AttributeError:
# pass
# return 1
. Output only the next line. | strfile = six.StringIO() |
Using the snippet: <|code_start|> raise RuntimeError("Test")
count -= 1
task_raises_recursive(count)
@task
def task_func():
task_raises_recursive()
@task_func.do_except
def except_func(err):
self.tb_str = format_exc()
ev = AsyncEventLoop()
with ev:
task_func()
ev.execute_all_tasks()
self.assertTrue(self.tb_str)
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_async(self):
@coroutine
def raises():
raise RuntimeError("TestErr")
@coroutine
def main():
try:
yield raises()
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import unittest
import logging
import pytest
import sys
import six
from botoflow.core.async_event_loop import AsyncEventLoop
from botoflow.core.decorators import coroutine, task
from botoflow.core.async_traceback import format_exc, print_exc
from botoflow.logging_filters import BotoflowFilter
and context (class names, function names, or code) available:
# Path: botoflow/core/async_event_loop.py
# class AsyncEventLoop(object):
# """
# TODO Document
# """
#
# def __init__(self):
# self.tasks = deque()
# self.root_context = AsyncRootTaskContext(weakref.proxy(self))
#
# def __enter__(self):
# set_async_context(self.root_context)
# return self.root_context
#
# # noinspection PyUnusedLocal
# def __exit__(self, exc_type, err, tb):
# set_async_context(None)
#
# def execute(self, task):
# if DEBUG:
# log.debug("Adding task: %s", task)
# self.tasks.append(task)
#
# def execute_now(self, task):
# if DEBUG:
# log.debug("Prepending task: %s", task)
# self.tasks.appendleft(task)
#
# def execute_all_tasks(self):
# while self.execute_queued_task():
# pass
#
# def execute_queued_task(self):
# if DEBUG:
# log.debug("Task queue: %s", self.tasks)
# try:
# task = self.tasks.popleft()
# if not task.done:
# if DEBUG:
# log.debug("Running task: %s", task)
# task.run()
# except IndexError: # no more tasks
# return False
# return True
#
# Path: botoflow/core/decorators.py
# DEBUG = False
# def _task(daemon=False):
# def __task(func):
# def inner_task(*args, **kwargs):
# def _do_except_wrapper(except_func):
# def _do_finally_wrapper(finally_func):
# def __init__(self, func, daemon):
# def _progress_function(self, future, *args, **kwargs):
# def _progress_except(self, future, except_func, err):
# def __get__(self, instance, cls):
# def __call__(self, *args, **kwargs):
# def _coroutine(daemon=False):
# def __coroutine(func=None):
# def ___coroutine(func):
# class CoroutineDecorator(object):
#
# Path: botoflow/core/async_traceback.py
# def format_exc(limit=None, exception=None, tb_list=None):
# """
# This is like print_exc(limit) but returns a string instead of printing to a
# file.
# """
# result = ["Traceback (most recent call last):\n"]
# if exception is None:
# exception = get_context_with_traceback(get_async_context()).exception
#
# if tb_list is None:
# tb_list = extract_tb(limit)
#
# if tb_list:
# result.extend(traceback.format_list(tb_list))
# result.extend(traceback.format_exception_only(exception.__class__,
# exception))
# return result
# else:
# return None
#
# def print_exc(limit=None, file=None):
# """
# Print exception information and up to limit stack trace entries to file
# """
# if file is None:
# file = sys.stderr
#
# formatted_exc = format_exc(limit)
# if formatted_exc is not None:
# for line in formatted_exc:
# file.write(line)
#
# Path: botoflow/logging_filters.py
# class BotoflowFilter(logging.Filter):
# """You can use this filter with Python's :py:mod:`logging` module to filter out
# botoflow logs that are being replayed by the decider.
#
# For example::
#
# import logging
# from botoflow.logging_filters import BotoflowFilter
#
# logging.basicConfig(level=logging.DEBUG,
# format='%(filename)s:%(lineno)d (%(funcName)s) - %(message)s')
#
# logging.getLogger('botoflow').addFilter(BotoflowFilter())
#
# """
#
# def __init__(self, name='', filter_replaying=True):
# super(BotoflowFilter, self).__init__(name)
# self._filter_replaying = filter_replaying
#
# def filter(self, record):
# try:
# if self._filter_replaying and botoflow.get_context().replaying:
# return 0
# except AttributeError:
# pass
# return 1
. Output only the next line. | except RuntimeError: |
Continue the code snippet: <|code_start|>
def setUp(self):
self.tb_str = None
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_format(self):
@task
def task_func():
raise RuntimeError("Test")
@task_func.do_except
def except_func(err):
self.tb_str = "".join(format_exc())
ev = AsyncEventLoop()
with ev:
task_func()
ev.execute_all_tasks()
self.assertTrue(self.tb_str)
self.assertEqual(1, self.tb_str.count('---continuation---'))
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_print(self):
@task
def task_func():
raise RuntimeError("Test")
<|code_end|>
. Use current file imports:
import pytest
import unittest
import logging
import pytest
import sys
import six
from botoflow.core.async_event_loop import AsyncEventLoop
from botoflow.core.decorators import coroutine, task
from botoflow.core.async_traceback import format_exc, print_exc
from botoflow.logging_filters import BotoflowFilter
and context (classes, functions, or code) from other files:
# Path: botoflow/core/async_event_loop.py
# class AsyncEventLoop(object):
# """
# TODO Document
# """
#
# def __init__(self):
# self.tasks = deque()
# self.root_context = AsyncRootTaskContext(weakref.proxy(self))
#
# def __enter__(self):
# set_async_context(self.root_context)
# return self.root_context
#
# # noinspection PyUnusedLocal
# def __exit__(self, exc_type, err, tb):
# set_async_context(None)
#
# def execute(self, task):
# if DEBUG:
# log.debug("Adding task: %s", task)
# self.tasks.append(task)
#
# def execute_now(self, task):
# if DEBUG:
# log.debug("Prepending task: %s", task)
# self.tasks.appendleft(task)
#
# def execute_all_tasks(self):
# while self.execute_queued_task():
# pass
#
# def execute_queued_task(self):
# if DEBUG:
# log.debug("Task queue: %s", self.tasks)
# try:
# task = self.tasks.popleft()
# if not task.done:
# if DEBUG:
# log.debug("Running task: %s", task)
# task.run()
# except IndexError: # no more tasks
# return False
# return True
#
# Path: botoflow/core/decorators.py
# DEBUG = False
# def _task(daemon=False):
# def __task(func):
# def inner_task(*args, **kwargs):
# def _do_except_wrapper(except_func):
# def _do_finally_wrapper(finally_func):
# def __init__(self, func, daemon):
# def _progress_function(self, future, *args, **kwargs):
# def _progress_except(self, future, except_func, err):
# def __get__(self, instance, cls):
# def __call__(self, *args, **kwargs):
# def _coroutine(daemon=False):
# def __coroutine(func=None):
# def ___coroutine(func):
# class CoroutineDecorator(object):
#
# Path: botoflow/core/async_traceback.py
# def format_exc(limit=None, exception=None, tb_list=None):
# """
# This is like print_exc(limit) but returns a string instead of printing to a
# file.
# """
# result = ["Traceback (most recent call last):\n"]
# if exception is None:
# exception = get_context_with_traceback(get_async_context()).exception
#
# if tb_list is None:
# tb_list = extract_tb(limit)
#
# if tb_list:
# result.extend(traceback.format_list(tb_list))
# result.extend(traceback.format_exception_only(exception.__class__,
# exception))
# return result
# else:
# return None
#
# def print_exc(limit=None, file=None):
# """
# Print exception information and up to limit stack trace entries to file
# """
# if file is None:
# file = sys.stderr
#
# formatted_exc = format_exc(limit)
# if formatted_exc is not None:
# for line in formatted_exc:
# file.write(line)
#
# Path: botoflow/logging_filters.py
# class BotoflowFilter(logging.Filter):
# """You can use this filter with Python's :py:mod:`logging` module to filter out
# botoflow logs that are being replayed by the decider.
#
# For example::
#
# import logging
# from botoflow.logging_filters import BotoflowFilter
#
# logging.basicConfig(level=logging.DEBUG,
# format='%(filename)s:%(lineno)d (%(funcName)s) - %(message)s')
#
# logging.getLogger('botoflow').addFilter(BotoflowFilter())
#
# """
#
# def __init__(self, name='', filter_replaying=True):
# super(BotoflowFilter, self).__init__(name)
# self._filter_replaying = filter_replaying
#
# def filter(self, record):
# try:
# if self._filter_replaying and botoflow.get_context().replaying:
# return 0
# except AttributeError:
# pass
# return 1
. Output only the next line. | @task_func.do_except |
Predict the next line for this snippet: <|code_start|>
pytestmark = pytest.mark.usefixtures('core_debug')
class TestTraceback(unittest.TestCase):
def setUp(self):
self.tb_str = None
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
def test_format(self):
@task
def task_func():
raise RuntimeError("Test")
@task_func.do_except
def except_func(err):
self.tb_str = "".join(format_exc())
ev = AsyncEventLoop()
with ev:
task_func()
ev.execute_all_tasks()
self.assertTrue(self.tb_str)
self.assertEqual(1, self.tb_str.count('---continuation---'))
@pytest.mark.xfail(sys.version_info >= (3,5,0),
reason="Some kind of brokennes on 3.5.0 specifically")
<|code_end|>
with the help of current file imports:
import pytest
import unittest
import logging
import pytest
import sys
import six
from botoflow.core.async_event_loop import AsyncEventLoop
from botoflow.core.decorators import coroutine, task
from botoflow.core.async_traceback import format_exc, print_exc
from botoflow.logging_filters import BotoflowFilter
and context from other files:
# Path: botoflow/core/async_event_loop.py
# class AsyncEventLoop(object):
# """
# TODO Document
# """
#
# def __init__(self):
# self.tasks = deque()
# self.root_context = AsyncRootTaskContext(weakref.proxy(self))
#
# def __enter__(self):
# set_async_context(self.root_context)
# return self.root_context
#
# # noinspection PyUnusedLocal
# def __exit__(self, exc_type, err, tb):
# set_async_context(None)
#
# def execute(self, task):
# if DEBUG:
# log.debug("Adding task: %s", task)
# self.tasks.append(task)
#
# def execute_now(self, task):
# if DEBUG:
# log.debug("Prepending task: %s", task)
# self.tasks.appendleft(task)
#
# def execute_all_tasks(self):
# while self.execute_queued_task():
# pass
#
# def execute_queued_task(self):
# if DEBUG:
# log.debug("Task queue: %s", self.tasks)
# try:
# task = self.tasks.popleft()
# if not task.done:
# if DEBUG:
# log.debug("Running task: %s", task)
# task.run()
# except IndexError: # no more tasks
# return False
# return True
#
# Path: botoflow/core/decorators.py
# DEBUG = False
# def _task(daemon=False):
# def __task(func):
# def inner_task(*args, **kwargs):
# def _do_except_wrapper(except_func):
# def _do_finally_wrapper(finally_func):
# def __init__(self, func, daemon):
# def _progress_function(self, future, *args, **kwargs):
# def _progress_except(self, future, except_func, err):
# def __get__(self, instance, cls):
# def __call__(self, *args, **kwargs):
# def _coroutine(daemon=False):
# def __coroutine(func=None):
# def ___coroutine(func):
# class CoroutineDecorator(object):
#
# Path: botoflow/core/async_traceback.py
# def format_exc(limit=None, exception=None, tb_list=None):
# """
# This is like print_exc(limit) but returns a string instead of printing to a
# file.
# """
# result = ["Traceback (most recent call last):\n"]
# if exception is None:
# exception = get_context_with_traceback(get_async_context()).exception
#
# if tb_list is None:
# tb_list = extract_tb(limit)
#
# if tb_list:
# result.extend(traceback.format_list(tb_list))
# result.extend(traceback.format_exception_only(exception.__class__,
# exception))
# return result
# else:
# return None
#
# def print_exc(limit=None, file=None):
# """
# Print exception information and up to limit stack trace entries to file
# """
# if file is None:
# file = sys.stderr
#
# formatted_exc = format_exc(limit)
# if formatted_exc is not None:
# for line in formatted_exc:
# file.write(line)
#
# Path: botoflow/logging_filters.py
# class BotoflowFilter(logging.Filter):
# """You can use this filter with Python's :py:mod:`logging` module to filter out
# botoflow logs that are being replayed by the decider.
#
# For example::
#
# import logging
# from botoflow.logging_filters import BotoflowFilter
#
# logging.basicConfig(level=logging.DEBUG,
# format='%(filename)s:%(lineno)d (%(funcName)s) - %(message)s')
#
# logging.getLogger('botoflow').addFilter(BotoflowFilter())
#
# """
#
# def __init__(self, name='', filter_replaying=True):
# super(BotoflowFilter, self).__init__(name)
# self._filter_replaying = filter_replaying
#
# def filter(self, record):
# try:
# if self._filter_replaying and botoflow.get_context().replaying:
# return 0
# except AttributeError:
# pass
# return 1
, which may contain function names, class names, or code. Output only the next line. | def test_print(self): |
Here is a snippet: <|code_start|> @task
def task_func():
raise RuntimeError("Test")
@task_func.do_except
def except_func(err):
strfile = six.StringIO()
print_exc(file=strfile)
self.tb_str = strfile.getvalue()
ev = AsyncEventLoop()
with ev:
task_func()
ev.execute_all_tasks()
self.assertTrue(self.tb_str)
self.assertEqual(1, self.tb_str.count('---continuation---'))
def test_recursive(self):
@task
def task_raises_recursive(count=3):
if not count:
raise RuntimeError("Test")
count -= 1
task_raises_recursive(count)
@task
def task_func():
task_raises_recursive()
<|code_end|>
. Write the next line using the current file imports:
import pytest
import unittest
import logging
import pytest
import sys
import six
from botoflow.core.async_event_loop import AsyncEventLoop
from botoflow.core.decorators import coroutine, task
from botoflow.core.async_traceback import format_exc, print_exc
from botoflow.logging_filters import BotoflowFilter
and context from other files:
# Path: botoflow/core/async_event_loop.py
# class AsyncEventLoop(object):
# """
# TODO Document
# """
#
# def __init__(self):
# self.tasks = deque()
# self.root_context = AsyncRootTaskContext(weakref.proxy(self))
#
# def __enter__(self):
# set_async_context(self.root_context)
# return self.root_context
#
# # noinspection PyUnusedLocal
# def __exit__(self, exc_type, err, tb):
# set_async_context(None)
#
# def execute(self, task):
# if DEBUG:
# log.debug("Adding task: %s", task)
# self.tasks.append(task)
#
# def execute_now(self, task):
# if DEBUG:
# log.debug("Prepending task: %s", task)
# self.tasks.appendleft(task)
#
# def execute_all_tasks(self):
# while self.execute_queued_task():
# pass
#
# def execute_queued_task(self):
# if DEBUG:
# log.debug("Task queue: %s", self.tasks)
# try:
# task = self.tasks.popleft()
# if not task.done:
# if DEBUG:
# log.debug("Running task: %s", task)
# task.run()
# except IndexError: # no more tasks
# return False
# return True
#
# Path: botoflow/core/decorators.py
# DEBUG = False
# def _task(daemon=False):
# def __task(func):
# def inner_task(*args, **kwargs):
# def _do_except_wrapper(except_func):
# def _do_finally_wrapper(finally_func):
# def __init__(self, func, daemon):
# def _progress_function(self, future, *args, **kwargs):
# def _progress_except(self, future, except_func, err):
# def __get__(self, instance, cls):
# def __call__(self, *args, **kwargs):
# def _coroutine(daemon=False):
# def __coroutine(func=None):
# def ___coroutine(func):
# class CoroutineDecorator(object):
#
# Path: botoflow/core/async_traceback.py
# def format_exc(limit=None, exception=None, tb_list=None):
# """
# This is like print_exc(limit) but returns a string instead of printing to a
# file.
# """
# result = ["Traceback (most recent call last):\n"]
# if exception is None:
# exception = get_context_with_traceback(get_async_context()).exception
#
# if tb_list is None:
# tb_list = extract_tb(limit)
#
# if tb_list:
# result.extend(traceback.format_list(tb_list))
# result.extend(traceback.format_exception_only(exception.__class__,
# exception))
# return result
# else:
# return None
#
# def print_exc(limit=None, file=None):
# """
# Print exception information and up to limit stack trace entries to file
# """
# if file is None:
# file = sys.stderr
#
# formatted_exc = format_exc(limit)
# if formatted_exc is not None:
# for line in formatted_exc:
# file.write(line)
#
# Path: botoflow/logging_filters.py
# class BotoflowFilter(logging.Filter):
# """You can use this filter with Python's :py:mod:`logging` module to filter out
# botoflow logs that are being replayed by the decider.
#
# For example::
#
# import logging
# from botoflow.logging_filters import BotoflowFilter
#
# logging.basicConfig(level=logging.DEBUG,
# format='%(filename)s:%(lineno)d (%(funcName)s) - %(message)s')
#
# logging.getLogger('botoflow').addFilter(BotoflowFilter())
#
# """
#
# def __init__(self, name='', filter_replaying=True):
# super(BotoflowFilter, self).__init__(name)
# self._filter_replaying = filter_replaying
#
# def filter(self, record):
# try:
# if self._filter_replaying and botoflow.get_context().replaying:
# return 0
# except AttributeError:
# pass
# return 1
, which may include functions, classes, or code. Output only the next line. | @task_func.do_except |
Given the following code snippet before the placeholder: <|code_start|>
class TestDecisionList(unittest.TestCase):
def test_delete_decision(self):
dlist = decision_list.DecisionList()
dlist.append(decisions.CancelTimer(123))
self.assertTrue(dlist)
dlist.delete_decision(decisions.CancelTimer, 999)
self.assertTrue(dlist)
dlist.delete_decision(decisions.CancelTimer, 123)
self.assertFalse(dlist)
def test_to_swf(self):
dlist = decision_list.DecisionList()
dlist.append(decisions.CancelTimer(123))
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from botoflow.decisions import decision_list, decisions
and context including class names, function names, and sometimes code from other files:
# Path: botoflow/decisions/decision_list.py
# class DecisionList(list):
# def delete_decision(self, decision_type, decision_id):
# def has_decision_type(self, *args):
# def to_swf(self):
#
# Path: botoflow/decisions/decisions.py
# class CancelWorkflowExecution(WorkflowDecisionBase):
# class CancelTimer(TimerDecisionBase):
# class CompleteWorkflowExecution(WorkflowDecisionBase):
# class ContinueAsNewWorkflowExecution(WorkflowDecisionBase):
# class FailWorkflowExecution(WorkflowDecisionBase):
# class RecordMarker(RecordMarkerDecisionBase):
# class RequestCancelActivityTask(ActivityDecisionBase):
# class RequestCancelExternalWorkflowExecution(RequestCancelExternalWorkflowDecisionBase):
# class ScheduleActivityTask(ActivityDecisionBase):
# class SignalExternalWorkflowExecution(SignalExternalWorkflowExecutionDecisionBase):
# class StartChildWorkflowExecution(StartChildWorkflowExecutionDecisionBase):
# class StartTimer(TimerDecisionBase):
# def __init__(self, details=None):
# def __init__(self, timer_id):
# def __init__(self, result=None):
# def __init__(self,
# child_policy=None,
# execution_start_to_close_timeout=None,
# input=None,
# tag_list=None,
# task_list=None,
# task_priority=None,
# task_start_to_close_timeout=None,
# version=None):
# def __init__(self, reason=None, details=None):
# def __init__(self, marker_name, details=None):
# def __init__(self, activity_id):
# def __init__(self, workflow_id, run_id, control=None):
# def __init__(self, activity_id, activity_type_name, activity_type_version,
# task_list=None, control=None, heartbeat_timeout=None,
# schedule_to_close_timeout=None,
# schedule_to_start_timeout=None, start_to_close_timeout=None,
# task_priority=None,
# input=None):
# def __init__(self, workflow_id, run_id, signal_name,
# control=None, input=None):
# def __init__(self, workflow_type, workflow_id, child_policy=None,
# control=None, execution_start_to_close_timeout=None,
# input=None, tag_list=None, task_list=None,
# task_start_to_close_timeout=None, task_priority=None):
# def __init__(self, timer_id, start_to_fire_timeout, control=None):
. Output only the next line. | swf_list = dlist.to_swf() |
Next line prediction: <|code_start|>
class TestDecisionList(unittest.TestCase):
def test_delete_decision(self):
dlist = decision_list.DecisionList()
dlist.append(decisions.CancelTimer(123))
self.assertTrue(dlist)
dlist.delete_decision(decisions.CancelTimer, 999)
self.assertTrue(dlist)
dlist.delete_decision(decisions.CancelTimer, 123)
self.assertFalse(dlist)
def test_to_swf(self):
dlist = decision_list.DecisionList()
dlist.append(decisions.CancelTimer(123))
swf_list = dlist.to_swf()
self.assertTrue(swf_list)
self.assertEqual(swf_list, [{'cancelTimerDecisionAttributes':
{'timerId': 123},
'decisionType': 'CancelTimer'}])
if __name__ == '__main__':
<|code_end|>
. Use current file imports:
(import unittest
from botoflow.decisions import decision_list, decisions)
and context including class names, function names, or small code snippets from other files:
# Path: botoflow/decisions/decision_list.py
# class DecisionList(list):
# def delete_decision(self, decision_type, decision_id):
# def has_decision_type(self, *args):
# def to_swf(self):
#
# Path: botoflow/decisions/decisions.py
# class CancelWorkflowExecution(WorkflowDecisionBase):
# class CancelTimer(TimerDecisionBase):
# class CompleteWorkflowExecution(WorkflowDecisionBase):
# class ContinueAsNewWorkflowExecution(WorkflowDecisionBase):
# class FailWorkflowExecution(WorkflowDecisionBase):
# class RecordMarker(RecordMarkerDecisionBase):
# class RequestCancelActivityTask(ActivityDecisionBase):
# class RequestCancelExternalWorkflowExecution(RequestCancelExternalWorkflowDecisionBase):
# class ScheduleActivityTask(ActivityDecisionBase):
# class SignalExternalWorkflowExecution(SignalExternalWorkflowExecutionDecisionBase):
# class StartChildWorkflowExecution(StartChildWorkflowExecutionDecisionBase):
# class StartTimer(TimerDecisionBase):
# def __init__(self, details=None):
# def __init__(self, timer_id):
# def __init__(self, result=None):
# def __init__(self,
# child_policy=None,
# execution_start_to_close_timeout=None,
# input=None,
# tag_list=None,
# task_list=None,
# task_priority=None,
# task_start_to_close_timeout=None,
# version=None):
# def __init__(self, reason=None, details=None):
# def __init__(self, marker_name, details=None):
# def __init__(self, activity_id):
# def __init__(self, workflow_id, run_id, control=None):
# def __init__(self, activity_id, activity_type_name, activity_type_version,
# task_list=None, control=None, heartbeat_timeout=None,
# schedule_to_close_timeout=None,
# schedule_to_start_timeout=None, start_to_close_timeout=None,
# task_priority=None,
# input=None):
# def __init__(self, workflow_id, run_id, signal_name,
# control=None, input=None):
# def __init__(self, workflow_type, workflow_id, child_policy=None,
# control=None, execution_start_to_close_timeout=None,
# input=None, tag_list=None, task_list=None,
# task_start_to_close_timeout=None, task_priority=None):
# def __init__(self, timer_id, start_to_fire_timeout, control=None):
. Output only the next line. | unittest.main() |
Using the snippet: <|code_start|> 'startToCloseTimeout': '6', 'taskPriority': '100', 'input': 'input'}
decision = decisions.ScheduleActivityTask(
activity_id="activity_id", activity_type_name="name", activity_type_version="1.0").decision
assert 'taskList' not in decision['scheduleActivityTaskDecisionAttributes']
def test_signal_external_workflow_execution():
decision = decisions.SignalExternalWorkflowExecution(workflow_id="workflow_id", run_id="run_id",
signal_name='signal_name', control="control",
input='input').decision
assert decision['decisionType'] == 'SignalExternalWorkflowExecution'
assert decision['signalExternalEorkflowExecutionDecisionAttributes'] == {
'workflowId': 'workflow_id', 'runId': 'run_id', 'signalName': 'signal_name', 'control': 'control',
'input': 'input'}
decision = decisions.SignalExternalWorkflowExecution(workflow_id="workflow_id", run_id="run_id",
signal_name='signal_name').decision
assert 'control' not in decision['signalExternalEorkflowExecutionDecisionAttributes']
# special for run_id as it can be None but is required
decision = decisions.SignalExternalWorkflowExecution(workflow_id="workflow_id", run_id=None,
signal_name='signal_name').decision
assert 'runId' not in decision['signalExternalEorkflowExecutionDecisionAttributes']
def test_start_child_workflow_execution():
decision = decisions.StartChildWorkflowExecution(
workflow_type={'name': 'name', 'version': '1.0'}, workflow_id='workflow_id',
child_policy="child_policy", control='control', execution_start_to_close_timeout="5", input="input",
<|code_end|>
, determine the next line of code. You have imports:
from botoflow.decisions import decisions
and context (class names, function names, or code) available:
# Path: botoflow/decisions/decisions.py
# class CancelWorkflowExecution(WorkflowDecisionBase):
# class CancelTimer(TimerDecisionBase):
# class CompleteWorkflowExecution(WorkflowDecisionBase):
# class ContinueAsNewWorkflowExecution(WorkflowDecisionBase):
# class FailWorkflowExecution(WorkflowDecisionBase):
# class RecordMarker(RecordMarkerDecisionBase):
# class RequestCancelActivityTask(ActivityDecisionBase):
# class RequestCancelExternalWorkflowExecution(RequestCancelExternalWorkflowDecisionBase):
# class ScheduleActivityTask(ActivityDecisionBase):
# class SignalExternalWorkflowExecution(SignalExternalWorkflowExecutionDecisionBase):
# class StartChildWorkflowExecution(StartChildWorkflowExecutionDecisionBase):
# class StartTimer(TimerDecisionBase):
# def __init__(self, details=None):
# def __init__(self, timer_id):
# def __init__(self, result=None):
# def __init__(self,
# child_policy=None,
# execution_start_to_close_timeout=None,
# input=None,
# tag_list=None,
# task_list=None,
# task_priority=None,
# task_start_to_close_timeout=None,
# version=None):
# def __init__(self, reason=None, details=None):
# def __init__(self, marker_name, details=None):
# def __init__(self, activity_id):
# def __init__(self, workflow_id, run_id, control=None):
# def __init__(self, activity_id, activity_type_name, activity_type_version,
# task_list=None, control=None, heartbeat_timeout=None,
# schedule_to_close_timeout=None,
# schedule_to_start_timeout=None, start_to_close_timeout=None,
# task_priority=None,
# input=None):
# def __init__(self, workflow_id, run_id, signal_name,
# control=None, input=None):
# def __init__(self, workflow_type, workflow_id, child_policy=None,
# control=None, execution_start_to_close_timeout=None,
# input=None, tag_list=None, task_list=None,
# task_start_to_close_timeout=None, task_priority=None):
# def __init__(self, timer_id, start_to_fire_timeout, control=None):
. Output only the next line. | tag_list=['tag', 'list'], task_list="task_list", task_start_to_close_timeout="3", task_priority='100').decision |
Predict the next line after this snippet: <|code_start|>
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
try:
self._context = self.get_context()
except AttributeError:
<|code_end|>
using the current file's imports:
from botoflow.core import AsyncEventLoop
from botoflow.context import ContextBase
and any relevant context from other files:
# Path: botoflow/core/async_event_loop.py
# class AsyncEventLoop(object):
# """
# TODO Document
# """
#
# def __init__(self):
# self.tasks = deque()
# self.root_context = AsyncRootTaskContext(weakref.proxy(self))
#
# def __enter__(self):
# set_async_context(self.root_context)
# return self.root_context
#
# # noinspection PyUnusedLocal
# def __exit__(self, exc_type, err, tb):
# set_async_context(None)
#
# def execute(self, task):
# if DEBUG:
# log.debug("Adding task: %s", task)
# self.tasks.append(task)
#
# def execute_now(self, task):
# if DEBUG:
# log.debug("Prepending task: %s", task)
# self.tasks.appendleft(task)
#
# def execute_all_tasks(self):
# while self.execute_queued_task():
# pass
#
# def execute_queued_task(self):
# if DEBUG:
# log.debug("Task queue: %s", self.tasks)
# try:
# task = self.tasks.popleft()
# if not task.done:
# if DEBUG:
# log.debug("Running task: %s", task)
# task.run()
# except IndexError: # no more tasks
# return False
# return True
#
# Path: botoflow/context/context_base.py
# class ContextBase(object):
#
# thread_local = threading.local()
#
# # Python has no good support for class properties
# @classmethod
# def get_context(cls):
# context = cls.thread_local.flow_current_context
# if DEBUG:
# log.debug("Current context: %s", context)
# return context
#
# @classmethod
# def set_context(cls, context):
# if DEBUG:
# log.debug("Setting context: %s", context)
# cls.thread_local.flow_current_context = context
. Output only the next line. | self._context = None |
Given snippet: <|code_start|>
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
try:
self._context = self.get_context()
except AttributeError:
self._context = None
self.set_context(self)
self._event_loop.__enter__()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from botoflow.core import AsyncEventLoop
from botoflow.context import ContextBase
and context:
# Path: botoflow/core/async_event_loop.py
# class AsyncEventLoop(object):
# """
# TODO Document
# """
#
# def __init__(self):
# self.tasks = deque()
# self.root_context = AsyncRootTaskContext(weakref.proxy(self))
#
# def __enter__(self):
# set_async_context(self.root_context)
# return self.root_context
#
# # noinspection PyUnusedLocal
# def __exit__(self, exc_type, err, tb):
# set_async_context(None)
#
# def execute(self, task):
# if DEBUG:
# log.debug("Adding task: %s", task)
# self.tasks.append(task)
#
# def execute_now(self, task):
# if DEBUG:
# log.debug("Prepending task: %s", task)
# self.tasks.appendleft(task)
#
# def execute_all_tasks(self):
# while self.execute_queued_task():
# pass
#
# def execute_queued_task(self):
# if DEBUG:
# log.debug("Task queue: %s", self.tasks)
# try:
# task = self.tasks.popleft()
# if not task.done:
# if DEBUG:
# log.debug("Running task: %s", task)
# task.run()
# except IndexError: # no more tasks
# return False
# return True
#
# Path: botoflow/context/context_base.py
# class ContextBase(object):
#
# thread_local = threading.local()
#
# # Python has no good support for class properties
# @classmethod
# def get_context(cls):
# context = cls.thread_local.flow_current_context
# if DEBUG:
# log.debug("Current context: %s", context)
# return context
#
# @classmethod
# def set_context(cls, context):
# if DEBUG:
# log.debug("Setting context: %s", context)
# cls.thread_local.flow_current_context = context
which might include code, classes, or functions. Output only the next line. | def __exit__(self, exc_type, exc_val, exc_tb): |
Next line prediction: <|code_start|> ('TypeAlreadyExistsFault', swf_exceptions.TypeAlreadyExistsError),
('OperationNotPermittedFault', swf_exceptions.OperationNotPermittedError),
('UnknownResourceFault', swf_exceptions.UnknownResourceError),
('SWFResponseError', swf_exceptions.SWFResponseError),
('ThrottlingException', swf_exceptions.ThrottlingException),
('ValidationException', swf_exceptions.ValidationException),
('UnrecognizedClientException', swf_exceptions.UnrecognizedClientException),
('InternalFailure', swf_exceptions.InternalFailureError),
])
def test_swf_exception_wrapper_with_known_exception(code_key, expected_exception):
with pytest.raises(expected_exception) as exc:
with swf_exceptions.swf_exception_wrapper():
raise ClientError({'Error': {'Code': code_key, 'Message': 'Oops'}}, 'foobar')
assert str(exc.value) == "Oops"
def test_swf_exception_wrapper_with_no_error_response_details():
with pytest.raises(swf_exceptions.SWFResponseError) as exc:
with swf_exceptions.swf_exception_wrapper():
raise ClientError({'Error': {'Code': None, 'Message': None}}, 'foobar')
def test_swf_exception_wrapper_with_malformed_code_key():
with pytest.raises(swf_exceptions.SWFResponseError) as exc:
with swf_exceptions.swf_exception_wrapper():
raise ClientError({'Error': {'Code': (123, "this is not a key"), 'Message': None}}, 'foobar')
def test_swf_exception_wrapper_with_non_client_error():
<|code_end|>
. Use current file imports:
(import pytest
from botocore.exceptions import ClientError
from botoflow import swf_exceptions)
and context including class names, function names, or small code snippets from other files:
# Path: botoflow/swf_exceptions.py
# class SWFResponseError(Exception):
# class DomainDeprecatedError(SWFResponseError):
# class DomainAlreadyExistsError(SWFResponseError):
# class DefaultUndefinedError(SWFResponseError):
# class LimitExceededError(SWFResponseError):
# class WorkflowExecutionAlreadyStartedError(SWFResponseError):
# class TypeDeprecatedError(SWFResponseError):
# class TypeAlreadyExistsError(SWFResponseError):
# class OperationNotPermittedError(SWFResponseError):
# class UnknownResourceError(SWFResponseError):
# class UnrecognizedClientException(SWFResponseError):
# class ThrottlingException(SWFResponseError):
# class ValidationException(SWFResponseError):
# class InternalFailureError(SWFResponseError):
# def swf_exception_wrapper():
. Output only the next line. | exception = RuntimeError("Not handled by swf_exception_wrapper") |
Given the following code snippet before the placeholder: <|code_start|> with self:
task = AsyncTask(self.finally_func, context=self,
name=self.finally_func.__name__)
task.daemon = self.daemon
task.cancellable = False
task.execute()
self.finally_func = None
else:
self.update_parent()
def __enter__(self):
self._parent_context = get_async_context()
set_async_context(self)
return self
def __exit__(self, exc_type, err, tb):
set_async_context(self._parent_context)
self._parent_context = None # gc
def __repr__(self):
args = []
if self.name is not None:
args.append("name=%s" % self.name)
if self.parent:
args.append("parent=%s" % self.parent)
if self.children:
args.append("children=%d" % len(self.children))
if self.daemon_children:
args.append("daemon_children=%d" % len(self.daemon_children))
if self.except_func:
<|code_end|>
, predict the next line using imports from the current file:
import abc
import logging
from weakref import WeakSet
from .async_context import get_async_context, set_async_context
from .exceptions import CancellationError
from .utils import split_stack, log_task_context
from .async_task import AsyncTask
and context including class names, function names, and sometimes code from other files:
# Path: botoflow/core/async_context.py
# @classmethod
# def get_async_context(cls):
# context = cls.thread_local.async_current_context
# if DEBUG:
# log.debug("Current async context: %r", context)
# return context
#
# @classmethod
# def set_async_context(cls, context):
# if DEBUG:
# log.debug("Setting async context: %r", context)
# cls.thread_local.async_current_context = context
#
# Path: botoflow/core/exceptions.py
# class CancellationError(Exception):
# """
# Cancellation error exception
# """
# pass
#
# Path: botoflow/core/utils.py
# def split_stack(stack):
# """
# Splits the stack into two, before and after the framework
# """
# stack_before, stack_after = list(), list()
# in_before = True
# for frame in stack:
# if 'flow/core' in frame[0]:
# in_before = False
# else:
# if in_before:
# stack_before.append(frame)
# else:
# stack_after.append(frame)
# return stack_before, stack_after
#
# def log_task_context(context, logger):
# """
# A helper for printing contexts as a tree
# """
# from .async_root_task_context import AsyncRootTaskContext
#
# root_context = None
# while root_context is None:
# if isinstance(context, AsyncRootTaskContext):
# root_context = context
# context = context.parent
# _log_task_context(root_context, logger)
. Output only the next line. | args.append("except_func=%r" % self.except_func.__name__) |
Continue the code snippet: <|code_start|> @abc.abstractmethod
def handle_exception(self, error):
raise NotImplementedError()
class AsyncTaskContext(AbstractAsyncTaskContext):
def __init__(self, daemon=False, parent=None, name=None):
self._setup()
self.daemon = daemon
self.parent = parent
self.name = name
self.eventloop = parent.eventloop
self.parent.add_child(self)
def _setup(self):
self.children = WeakSet()
self.daemon_children = WeakSet()
self.exception = None
self.tb_list = None
self.stack_list = None
self.except_func = None
self.finally_func = None
def add_child(self, child):
if DEBUG:
log.debug("Adding child:%r ", child)
<|code_end|>
. Use current file imports:
import abc
import logging
from weakref import WeakSet
from .async_context import get_async_context, set_async_context
from .exceptions import CancellationError
from .utils import split_stack, log_task_context
from .async_task import AsyncTask
and context (classes, functions, or code) from other files:
# Path: botoflow/core/async_context.py
# @classmethod
# def get_async_context(cls):
# context = cls.thread_local.async_current_context
# if DEBUG:
# log.debug("Current async context: %r", context)
# return context
#
# @classmethod
# def set_async_context(cls, context):
# if DEBUG:
# log.debug("Setting async context: %r", context)
# cls.thread_local.async_current_context = context
#
# Path: botoflow/core/exceptions.py
# class CancellationError(Exception):
# """
# Cancellation error exception
# """
# pass
#
# Path: botoflow/core/utils.py
# def split_stack(stack):
# """
# Splits the stack into two, before and after the framework
# """
# stack_before, stack_after = list(), list()
# in_before = True
# for frame in stack:
# if 'flow/core' in frame[0]:
# in_before = False
# else:
# if in_before:
# stack_before.append(frame)
# else:
# stack_after.append(frame)
# return stack_before, stack_after
#
# def log_task_context(context, logger):
# """
# A helper for printing contexts as a tree
# """
# from .async_root_task_context import AsyncRootTaskContext
#
# root_context = None
# while root_context is None:
# if isinstance(context, AsyncRootTaskContext):
# root_context = context
# context = context.parent
# _log_task_context(root_context, logger)
. Output only the next line. | if child.daemon: |
Based on the snippet: <|code_start|> else:
self.update_parent()
def __enter__(self):
self._parent_context = get_async_context()
set_async_context(self)
return self
def __exit__(self, exc_type, err, tb):
set_async_context(self._parent_context)
self._parent_context = None # gc
def __repr__(self):
args = []
if self.name is not None:
args.append("name=%s" % self.name)
if self.parent:
args.append("parent=%s" % self.parent)
if self.children:
args.append("children=%d" % len(self.children))
if self.daemon_children:
args.append("daemon_children=%d" % len(self.daemon_children))
if self.except_func:
args.append("except_func=%r" % self.except_func.__name__)
if self.finally_func:
args.append("finally_func=%r" % self.finally_func.__name__)
if self.exception:
args.append("exception=%r" % self.exception)
if args:
<|code_end|>
, predict the immediate next line with the help of imports:
import abc
import logging
from weakref import WeakSet
from .async_context import get_async_context, set_async_context
from .exceptions import CancellationError
from .utils import split_stack, log_task_context
from .async_task import AsyncTask
and context (classes, functions, sometimes code) from other files:
# Path: botoflow/core/async_context.py
# @classmethod
# def get_async_context(cls):
# context = cls.thread_local.async_current_context
# if DEBUG:
# log.debug("Current async context: %r", context)
# return context
#
# @classmethod
# def set_async_context(cls, context):
# if DEBUG:
# log.debug("Setting async context: %r", context)
# cls.thread_local.async_current_context = context
#
# Path: botoflow/core/exceptions.py
# class CancellationError(Exception):
# """
# Cancellation error exception
# """
# pass
#
# Path: botoflow/core/utils.py
# def split_stack(stack):
# """
# Splits the stack into two, before and after the framework
# """
# stack_before, stack_after = list(), list()
# in_before = True
# for frame in stack:
# if 'flow/core' in frame[0]:
# in_before = False
# else:
# if in_before:
# stack_before.append(frame)
# else:
# stack_after.append(frame)
# return stack_before, stack_after
#
# def log_task_context(context, logger):
# """
# A helper for printing contexts as a tree
# """
# from .async_root_task_context import AsyncRootTaskContext
#
# root_context = None
# while root_context is None:
# if isinstance(context, AsyncRootTaskContext):
# root_context = context
# context = context.parent
# _log_task_context(root_context, logger)
. Output only the next line. | args.insert(0, "") |
Continue the code snippet: <|code_start|> def handle_exception(self, exception, tb_list=None):
if DEBUG:
log.debug("Handling exception %r %r", self, exception)
if self.exception is None \
or not isinstance(exception, CancellationError):
self.exception = exception
self.tb_list = tb_list
for child in self.children.union(self.daemon_children):
child.cancel()
def cancel(self):
if DEBUG:
log.debug("Cancelling %r", self)
self.handle_exception(CancellationError(), self.tb_list)
def update_parent(self):
if DEBUG:
log.debug("updating parent %r of self %r", self.parent, self)
if self.parent is None:
return
if self.exception is not None:
self.parent.handle_exception(self.exception, self.tb_list)
self.parent.remove_child(self)
self.parent = None # gc
<|code_end|>
. Use current file imports:
import abc
import logging
from weakref import WeakSet
from .async_context import get_async_context, set_async_context
from .exceptions import CancellationError
from .utils import split_stack, log_task_context
from .async_task import AsyncTask
and context (classes, functions, or code) from other files:
# Path: botoflow/core/async_context.py
# @classmethod
# def get_async_context(cls):
# context = cls.thread_local.async_current_context
# if DEBUG:
# log.debug("Current async context: %r", context)
# return context
#
# @classmethod
# def set_async_context(cls, context):
# if DEBUG:
# log.debug("Setting async context: %r", context)
# cls.thread_local.async_current_context = context
#
# Path: botoflow/core/exceptions.py
# class CancellationError(Exception):
# """
# Cancellation error exception
# """
# pass
#
# Path: botoflow/core/utils.py
# def split_stack(stack):
# """
# Splits the stack into two, before and after the framework
# """
# stack_before, stack_after = list(), list()
# in_before = True
# for frame in stack:
# if 'flow/core' in frame[0]:
# in_before = False
# else:
# if in_before:
# stack_before.append(frame)
# else:
# stack_after.append(frame)
# return stack_before, stack_after
#
# def log_task_context(context, logger):
# """
# A helper for printing contexts as a tree
# """
# from .async_root_task_context import AsyncRootTaskContext
#
# root_context = None
# while root_context is None:
# if isinstance(context, AsyncRootTaskContext):
# root_context = context
# context = context.parent
# _log_task_context(root_context, logger)
. Output only the next line. | def schedule_task(self, task, now=False): |
Based on the snippet: <|code_start|> else:
self.update_parent()
def __enter__(self):
self._parent_context = get_async_context()
set_async_context(self)
return self
def __exit__(self, exc_type, err, tb):
set_async_context(self._parent_context)
self._parent_context = None # gc
def __repr__(self):
args = []
if self.name is not None:
args.append("name=%s" % self.name)
if self.parent:
args.append("parent=%s" % self.parent)
if self.children:
args.append("children=%d" % len(self.children))
if self.daemon_children:
args.append("daemon_children=%d" % len(self.daemon_children))
if self.except_func:
args.append("except_func=%r" % self.except_func.__name__)
if self.finally_func:
args.append("finally_func=%r" % self.finally_func.__name__)
if self.exception:
args.append("exception=%r" % self.exception)
if args:
<|code_end|>
, predict the immediate next line with the help of imports:
import abc
import logging
from weakref import WeakSet
from .async_context import get_async_context, set_async_context
from .exceptions import CancellationError
from .utils import split_stack, log_task_context
from .async_task import AsyncTask
and context (classes, functions, sometimes code) from other files:
# Path: botoflow/core/async_context.py
# @classmethod
# def get_async_context(cls):
# context = cls.thread_local.async_current_context
# if DEBUG:
# log.debug("Current async context: %r", context)
# return context
#
# @classmethod
# def set_async_context(cls, context):
# if DEBUG:
# log.debug("Setting async context: %r", context)
# cls.thread_local.async_current_context = context
#
# Path: botoflow/core/exceptions.py
# class CancellationError(Exception):
# """
# Cancellation error exception
# """
# pass
#
# Path: botoflow/core/utils.py
# def split_stack(stack):
# """
# Splits the stack into two, before and after the framework
# """
# stack_before, stack_after = list(), list()
# in_before = True
# for frame in stack:
# if 'flow/core' in frame[0]:
# in_before = False
# else:
# if in_before:
# stack_before.append(frame)
# else:
# stack_after.append(frame)
# return stack_before, stack_after
#
# def log_task_context(context, logger):
# """
# A helper for printing contexts as a tree
# """
# from .async_root_task_context import AsyncRootTaskContext
#
# root_context = None
# while root_context is None:
# if isinstance(context, AsyncRootTaskContext):
# root_context = context
# context = context.parent
# _log_task_context(root_context, logger)
. Output only the next line. | args.insert(0, "") |
Based on the snippet: <|code_start|>
@execute('1.0', 1)
def execute0(self):
pass
@execute('1.0', 1)
def execute1(self):
pass
@signal()
def signal0(self):
pass
@signal()
def signal1(self):
pass
class SubSpamWorkflow(SpamWorkflow):
@execute('1.1', 2)
def execute0(self):
pass
@signal()
def signal0(self):
pass
def test_meta_subclass():
<|code_end|>
, predict the immediate next line with the help of imports:
from botoflow import execute, signal
from botoflow import workflow_definition as wodef
and context (classes, functions, sometimes code) from other files:
# Path: botoflow/decorators.py
# def execute(version,
# execution_start_to_close_timeout,
# task_list=USE_WORKER_TASK_LIST,
# task_priority=None,
# task_start_to_close_timeout=30, # as in java flow
# child_policy=CHILD_TERMINATE,
# data_converter=None,
# description=None,
# skip_registration=False):
# """This decorator indicates the entry point of the workflow.
#
# The entry point of the workflow can be invoked remotely by your application
# using :py:class`~botoflow.workflow_starter.workflow_starter` or direct API call from ``boto3`` or
# `AWS CLI <http://docs.aws.amazon.com/cli/latest/reference/swf/start-workflow-execution.html>`_.
#
# :param str version: Required version of the workflow type. Maximum length
# is 64 characters.
# :param int execution_start_to_close_timeout: Specifies the
# defaultExecutionStartToCloseTimeout registered with Amazon SWF for the
# workflow type. This specifies the total time a workflow execution of
# this type may take to complete. See the Amazon SWF API reference for
# more details.
# :param str task_list: The default task list for the decision tasks for
# executions of this workflow type. The default can be overridden using
# :py:func`~botoflow.options_overrides.workflow_options` when starting a
# workflow execution. Set to
# :py:data:`~botoflow.constants.USE_WORKER_TASK_LIST` by default. This is
# a special value which indicates that the task list used by the worker,
# which is performing the registration, should be used.
# :param int task_priority: The default priority for decision tasks for
# executions of this workflow type. The default can be overridden using
# :py:func`~botoflow.options_overrides.workflow_options` when starting a
# workflow execution. If unset AWS SWF defaults this to 0.
# :param int task_start_to_close_timeout: Specifies the
# defaultTaskStartToCloseTimeout registered with Amazon SWF for the
# workflow type. This specifies the time a single decision task for a
# workflow execution of this type may take to complete. See the Amazon
# SWF API reference for more details. The default is 30 seconds.
# :param str child_policy: Specifies the policy to use for the child
# workflows if an execution of this type is terminated. The default value
# is :py:data:`~botoflow.constants.CHILD_TERMINATE`.
# :param data_converter: Specifies the type of the DataConverter to use for
# serializing/deserializing data when sending requests to and receiving
# results from workflow executions of this workflow type. Set to `None`
# by default, which indicates that the JsonDataConverter should be used.
# :type data_converter: :py:class:`~botoflow.data_converter.abstract_data_converter.AbstractDataConverter`
# :param description: Textual description of the workflow definition. By
# default will use the docstring of the workflow definition class if
# available. The maximum length is 1024 characters, so a long docstring
# will be truncated to that length.
# :type description: str or None
# :param bool skip_registration: Indicates that the workflow type should not
# be registered with Amazon SWF.
# """
# _workflow_type = WorkflowType(
# version,
# task_list=task_list,
# execution_start_to_close_timeout=execution_start_to_close_timeout,
# task_start_to_close_timeout=task_start_to_close_timeout,
# task_priority=task_priority,
# child_policy=child_policy,
# data_converter=data_converter,
# description=description,
# skip_registration=skip_registration)
#
# def _execute(func):
# # set description
# if _workflow_type.description is None:
# _workflow_type.description = func.__doc__
#
# _set_swf_options(func, 'workflow_type', _workflow_type)
# return decorator_descriptors.WorkflowExecuteFunc(func)
#
# return _execute
#
# def signal(name=None):
# """When used on a method in the WorkflowDefinition subclass, identifies a
# signal that can be received by executions of the workflow.
# Use of this decorator is required to define a signal method.
#
# :param str name: Specifies the name portion of the signal name.
# If not set, the name of the method is used.
# """
#
# def _signal(func):
# _signal_type = SignalType(name=name)
# if name is None:
# _signal_type = SignalType(name=func.__name__)
#
# _set_swf_options(func, 'signal_type', _signal_type)
# return decorator_descriptors.SignalFunc(func)
#
# return _signal
#
# Path: botoflow/workflow_definition.py
# class _WorkflowDefinitionMeta(type):
# class WorkflowDefinition(six.with_metaclass(_WorkflowDefinitionMeta, object)):
# def __new__(mcs, name, bases, dct):
# def _extract_workflows_and_signals(dct):
# def __init__(self, workflow_execution):
# def workflow_execution(self):
# def workflow_execution(self, workflow_execution):
# def workflow_state(self):
# def workflow_state(self, state):
# def workflow_result(self):
# def cancel(self, details=""):
# def cancellation_handler(self):
# def _get_decision_context(self, calling_func):
. Output only the next line. | assert set(SubSpamWorkflow._workflow_types.values()) == {'execute0', 'execute1'} |
Predict the next line for this snippet: <|code_start|>
class SpamWorkflow(wodef.WorkflowDefinition):
@execute('1.0', 1)
def execute0(self):
pass
@execute('1.0', 1)
def execute1(self):
pass
@signal()
def signal0(self):
pass
@signal()
def signal1(self):
pass
<|code_end|>
with the help of current file imports:
from botoflow import execute, signal
from botoflow import workflow_definition as wodef
and context from other files:
# Path: botoflow/decorators.py
# def execute(version,
# execution_start_to_close_timeout,
# task_list=USE_WORKER_TASK_LIST,
# task_priority=None,
# task_start_to_close_timeout=30, # as in java flow
# child_policy=CHILD_TERMINATE,
# data_converter=None,
# description=None,
# skip_registration=False):
# """This decorator indicates the entry point of the workflow.
#
# The entry point of the workflow can be invoked remotely by your application
# using :py:class`~botoflow.workflow_starter.workflow_starter` or direct API call from ``boto3`` or
# `AWS CLI <http://docs.aws.amazon.com/cli/latest/reference/swf/start-workflow-execution.html>`_.
#
# :param str version: Required version of the workflow type. Maximum length
# is 64 characters.
# :param int execution_start_to_close_timeout: Specifies the
# defaultExecutionStartToCloseTimeout registered with Amazon SWF for the
# workflow type. This specifies the total time a workflow execution of
# this type may take to complete. See the Amazon SWF API reference for
# more details.
# :param str task_list: The default task list for the decision tasks for
# executions of this workflow type. The default can be overridden using
# :py:func`~botoflow.options_overrides.workflow_options` when starting a
# workflow execution. Set to
# :py:data:`~botoflow.constants.USE_WORKER_TASK_LIST` by default. This is
# a special value which indicates that the task list used by the worker,
# which is performing the registration, should be used.
# :param int task_priority: The default priority for decision tasks for
# executions of this workflow type. The default can be overridden using
# :py:func`~botoflow.options_overrides.workflow_options` when starting a
# workflow execution. If unset AWS SWF defaults this to 0.
# :param int task_start_to_close_timeout: Specifies the
# defaultTaskStartToCloseTimeout registered with Amazon SWF for the
# workflow type. This specifies the time a single decision task for a
# workflow execution of this type may take to complete. See the Amazon
# SWF API reference for more details. The default is 30 seconds.
# :param str child_policy: Specifies the policy to use for the child
# workflows if an execution of this type is terminated. The default value
# is :py:data:`~botoflow.constants.CHILD_TERMINATE`.
# :param data_converter: Specifies the type of the DataConverter to use for
# serializing/deserializing data when sending requests to and receiving
# results from workflow executions of this workflow type. Set to `None`
# by default, which indicates that the JsonDataConverter should be used.
# :type data_converter: :py:class:`~botoflow.data_converter.abstract_data_converter.AbstractDataConverter`
# :param description: Textual description of the workflow definition. By
# default will use the docstring of the workflow definition class if
# available. The maximum length is 1024 characters, so a long docstring
# will be truncated to that length.
# :type description: str or None
# :param bool skip_registration: Indicates that the workflow type should not
# be registered with Amazon SWF.
# """
# _workflow_type = WorkflowType(
# version,
# task_list=task_list,
# execution_start_to_close_timeout=execution_start_to_close_timeout,
# task_start_to_close_timeout=task_start_to_close_timeout,
# task_priority=task_priority,
# child_policy=child_policy,
# data_converter=data_converter,
# description=description,
# skip_registration=skip_registration)
#
# def _execute(func):
# # set description
# if _workflow_type.description is None:
# _workflow_type.description = func.__doc__
#
# _set_swf_options(func, 'workflow_type', _workflow_type)
# return decorator_descriptors.WorkflowExecuteFunc(func)
#
# return _execute
#
# def signal(name=None):
# """When used on a method in the WorkflowDefinition subclass, identifies a
# signal that can be received by executions of the workflow.
# Use of this decorator is required to define a signal method.
#
# :param str name: Specifies the name portion of the signal name.
# If not set, the name of the method is used.
# """
#
# def _signal(func):
# _signal_type = SignalType(name=name)
# if name is None:
# _signal_type = SignalType(name=func.__name__)
#
# _set_swf_options(func, 'signal_type', _signal_type)
# return decorator_descriptors.SignalFunc(func)
#
# return _signal
#
# Path: botoflow/workflow_definition.py
# class _WorkflowDefinitionMeta(type):
# class WorkflowDefinition(six.with_metaclass(_WorkflowDefinitionMeta, object)):
# def __new__(mcs, name, bases, dct):
# def _extract_workflows_and_signals(dct):
# def __init__(self, workflow_execution):
# def workflow_execution(self):
# def workflow_execution(self, workflow_execution):
# def workflow_state(self):
# def workflow_state(self, state):
# def workflow_result(self):
# def cancel(self, details=""):
# def cancellation_handler(self):
# def _get_decision_context(self, calling_func):
, which may contain function names, class names, or code. Output only the next line. | class SubSpamWorkflow(SpamWorkflow): |
Given snippet: <|code_start|>
class SpamWorkflow(wodef.WorkflowDefinition):
@execute('1.0', 1)
def execute0(self):
pass
@execute('1.0', 1)
def execute1(self):
pass
@signal()
def signal0(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from botoflow import execute, signal
from botoflow import workflow_definition as wodef
and context:
# Path: botoflow/decorators.py
# def execute(version,
# execution_start_to_close_timeout,
# task_list=USE_WORKER_TASK_LIST,
# task_priority=None,
# task_start_to_close_timeout=30, # as in java flow
# child_policy=CHILD_TERMINATE,
# data_converter=None,
# description=None,
# skip_registration=False):
# """This decorator indicates the entry point of the workflow.
#
# The entry point of the workflow can be invoked remotely by your application
# using :py:class`~botoflow.workflow_starter.workflow_starter` or direct API call from ``boto3`` or
# `AWS CLI <http://docs.aws.amazon.com/cli/latest/reference/swf/start-workflow-execution.html>`_.
#
# :param str version: Required version of the workflow type. Maximum length
# is 64 characters.
# :param int execution_start_to_close_timeout: Specifies the
# defaultExecutionStartToCloseTimeout registered with Amazon SWF for the
# workflow type. This specifies the total time a workflow execution of
# this type may take to complete. See the Amazon SWF API reference for
# more details.
# :param str task_list: The default task list for the decision tasks for
# executions of this workflow type. The default can be overridden using
# :py:func`~botoflow.options_overrides.workflow_options` when starting a
# workflow execution. Set to
# :py:data:`~botoflow.constants.USE_WORKER_TASK_LIST` by default. This is
# a special value which indicates that the task list used by the worker,
# which is performing the registration, should be used.
# :param int task_priority: The default priority for decision tasks for
# executions of this workflow type. The default can be overridden using
# :py:func`~botoflow.options_overrides.workflow_options` when starting a
# workflow execution. If unset AWS SWF defaults this to 0.
# :param int task_start_to_close_timeout: Specifies the
# defaultTaskStartToCloseTimeout registered with Amazon SWF for the
# workflow type. This specifies the time a single decision task for a
# workflow execution of this type may take to complete. See the Amazon
# SWF API reference for more details. The default is 30 seconds.
# :param str child_policy: Specifies the policy to use for the child
# workflows if an execution of this type is terminated. The default value
# is :py:data:`~botoflow.constants.CHILD_TERMINATE`.
# :param data_converter: Specifies the type of the DataConverter to use for
# serializing/deserializing data when sending requests to and receiving
# results from workflow executions of this workflow type. Set to `None`
# by default, which indicates that the JsonDataConverter should be used.
# :type data_converter: :py:class:`~botoflow.data_converter.abstract_data_converter.AbstractDataConverter`
# :param description: Textual description of the workflow definition. By
# default will use the docstring of the workflow definition class if
# available. The maximum length is 1024 characters, so a long docstring
# will be truncated to that length.
# :type description: str or None
# :param bool skip_registration: Indicates that the workflow type should not
# be registered with Amazon SWF.
# """
# _workflow_type = WorkflowType(
# version,
# task_list=task_list,
# execution_start_to_close_timeout=execution_start_to_close_timeout,
# task_start_to_close_timeout=task_start_to_close_timeout,
# task_priority=task_priority,
# child_policy=child_policy,
# data_converter=data_converter,
# description=description,
# skip_registration=skip_registration)
#
# def _execute(func):
# # set description
# if _workflow_type.description is None:
# _workflow_type.description = func.__doc__
#
# _set_swf_options(func, 'workflow_type', _workflow_type)
# return decorator_descriptors.WorkflowExecuteFunc(func)
#
# return _execute
#
# def signal(name=None):
# """When used on a method in the WorkflowDefinition subclass, identifies a
# signal that can be received by executions of the workflow.
# Use of this decorator is required to define a signal method.
#
# :param str name: Specifies the name portion of the signal name.
# If not set, the name of the method is used.
# """
#
# def _signal(func):
# _signal_type = SignalType(name=name)
# if name is None:
# _signal_type = SignalType(name=func.__name__)
#
# _set_swf_options(func, 'signal_type', _signal_type)
# return decorator_descriptors.SignalFunc(func)
#
# return _signal
#
# Path: botoflow/workflow_definition.py
# class _WorkflowDefinitionMeta(type):
# class WorkflowDefinition(six.with_metaclass(_WorkflowDefinitionMeta, object)):
# def __new__(mcs, name, bases, dct):
# def _extract_workflows_and_signals(dct):
# def __init__(self, workflow_execution):
# def workflow_execution(self):
# def workflow_execution(self, workflow_execution):
# def workflow_state(self):
# def workflow_state(self, state):
# def workflow_result(self):
# def cancel(self, details=""):
# def cancellation_handler(self):
# def _get_decision_context(self, calling_func):
which might include code, classes, or functions. Output only the next line. | pass |
Predict the next line after this snippet: <|code_start|>
class TestUtils(unittest.TestCase):
def test_camel_keys_to_snake_case(self):
d = {
'workflowType': 'A',
'taskList': 'B',
'childPolicy': 'C',
'executionStartToCloseTimeout': 'D',
'taskStartToCloseTimeout': 'E',
'input': 'F',
'workflowId': 'G',
'domain': 'H'
}
self.assertDictEqual(camel_keys_to_snake_case(d), {
'workflow_type': 'A',
'task_list': 'B',
'child_policy': 'C',
'execution_start_to_close_timeout': 'D',
'task_start_to_close_timeout': 'E',
'input': 'F',
'workflow_id': 'G',
'domain': 'H'
<|code_end|>
using the current file's imports:
import unittest
from botoflow.utils import camel_keys_to_snake_case, snake_keys_to_camel_case
and any relevant context from other files:
# Path: botoflow/utils.py
# def camel_keys_to_snake_case(dictionary):
# """
# Translate a dictionary containing camelCase keys into dictionary with
# snake_case keys that match python kwargs well.
# """
# output = {}
# for original_key in dictionary.keys():
# # insert an underscore before any word beginning with a capital followed by lower case
# translated_key = _first_cap_replace.sub(r'\1_\2', original_key)
# # insert an underscore before any remaining capitals that follow lower case characters
# translated_key = _remainder_cap_replace.sub(r'\1_\2', translated_key).lower()
# output[translated_key] = dictionary[original_key]
# return output
#
# def snake_keys_to_camel_case(dictionary):
# """
# Translate a dictionary containing snake_case keys into dictionary with
# camelCase keys as required for decision dicts.
# """
# output = {}
# for original_key in dictionary.keys():
# components = original_key.split('_')
# translated_key = components[0] + ''.join([component.title() for component in components[1:]])
# output[translated_key] = dictionary[original_key]
# return output
. Output only the next line. | }) |
Based on the snippet: <|code_start|>
class TestUtils(unittest.TestCase):
def test_camel_keys_to_snake_case(self):
d = {
'workflowType': 'A',
'taskList': 'B',
'childPolicy': 'C',
'executionStartToCloseTimeout': 'D',
'taskStartToCloseTimeout': 'E',
'input': 'F',
'workflowId': 'G',
'domain': 'H'
}
self.assertDictEqual(camel_keys_to_snake_case(d), {
'workflow_type': 'A',
'task_list': 'B',
'child_policy': 'C',
'execution_start_to_close_timeout': 'D',
'task_start_to_close_timeout': 'E',
'input': 'F',
'workflow_id': 'G',
'domain': 'H'
})
def test_snake_keys_to_camel_case(self):
d = {
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from botoflow.utils import camel_keys_to_snake_case, snake_keys_to_camel_case
and context (classes, functions, sometimes code) from other files:
# Path: botoflow/utils.py
# def camel_keys_to_snake_case(dictionary):
# """
# Translate a dictionary containing camelCase keys into dictionary with
# snake_case keys that match python kwargs well.
# """
# output = {}
# for original_key in dictionary.keys():
# # insert an underscore before any word beginning with a capital followed by lower case
# translated_key = _first_cap_replace.sub(r'\1_\2', original_key)
# # insert an underscore before any remaining capitals that follow lower case characters
# translated_key = _remainder_cap_replace.sub(r'\1_\2', translated_key).lower()
# output[translated_key] = dictionary[original_key]
# return output
#
# def snake_keys_to_camel_case(dictionary):
# """
# Translate a dictionary containing snake_case keys into dictionary with
# camelCase keys as required for decision dicts.
# """
# output = {}
# for original_key in dictionary.keys():
# components = original_key.split('_')
# translated_key = components[0] + ''.join([component.title() for component in components[1:]])
# output[translated_key] = dictionary[original_key]
# return output
. Output only the next line. | 'workflow_type': 'A', |
Here is a snippet: <|code_start|># Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
try:
except (ImportError, AttributeError):
class OrderedDict(object):
pass
<|code_end|>
. Write the next line using the current file imports:
import base64
import copy
import json
import datetime
import six
from decimal import Decimal
from collections import OrderedDict
from .abstract_data_converter import AbstractDataConverter
and context from other files:
# Path: botoflow/data_converter/abstract_data_converter.py
# class AbstractDataConverter(object):
# """
# Subclasses of this data converter are used by the framework to
# serialize/deserialize method parameters that need to be sent over the wire.
# """
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractmethod
# def dumps(self, obj):
# """
# Should return serialized string data
# """
# raise NotImplementedError
#
# @abc.abstractmethod
# def loads(self, data):
# """
# Should return deserialized string data
# """
# raise NotImplementedError
, which may include functions, classes, or code. Output only the next line. | DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" |
Based on the snippet: <|code_start|># pragma: no cover
warnings.warn("This module is deprecated. Please use the new API", DeprecationWarning)
SESSION_KEY = "__esteid_session"
class EsteidSessionError(Exception):
pass
def get_esteid_session(request):
return request.session.get(SESSION_KEY, {})
def start_esteid_session(request):
delete_esteid_session(request)
return {}
def update_esteid_session(request, **kwargs):
session = request.session
data = session.get(SESSION_KEY, {})
data.update(kwargs)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import warnings
from io import BytesIO
from typing import List, Union
from pyasice import Container
from esteid.types import DataFile
and context (classes, functions, sometimes code) from other files:
# Path: esteid/types.py
# class DataFile:
# def __init__(self, file_name, mimetype, content_type, size, content, info=None):
# self.file_name = file_name
# self.mimetype = mimetype
# self.content_type = content_type
# self.size = size
# self.content = content
#
# self.info = info
. Output only the next line. | session[SESSION_KEY] = data # Django session object requires setting keys explicitly |
Next line prediction: <|code_start|>
ID_CODE_EE_REGEXP = re.compile(r"^[1-6] \d{2} [01]\d [0123]\d \d{4}$", re.VERBOSE)
ID_CODE_LT_REGEXP = ID_CODE_EE_REGEXP
ID_CODE_LV_REGEXP = re.compile(r"^\d{6}-\d{5}$")
<|code_end|>
. Use current file imports:
(import re
from esteid.constants import Countries
from esteid.exceptions import InvalidIdCode, InvalidParameter)
and context including class names, function names, or small code snippets from other files:
# Path: esteid/constants.py
# class Countries:
# """Mainly used by SmartID, also phone code"""
#
# ESTONIA = "EE"
# LATVIA = "LV"
# LITHUANIA = "LT"
#
# ALL = (ESTONIA, LATVIA, LITHUANIA)
#
# Path: esteid/exceptions.py
# class InvalidIdCode(InvalidParameter):
# """Invalid ID code (format or checksum don't match)"""
#
# default_message = _("Invalid ID code.")
#
# def __init__(self, message=None, *, param="id_code", **kwargs):
# super().__init__(message, param=param, **kwargs)
#
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
. Output only the next line. | def id_code_ee_is_valid(id_code: str) -> bool: |
Based on the snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
url("^$", SKTestView.as_view(), name="sk_test"),
# NOTE: compare the template test-new.html to test.html locally to see JS changes.
url(r"^new/", SKTestView.as_view(template_name="esteid/test-new.html"), name="sk_test_new"),
url(r"^new-auth/", TemplateView.as_view(template_name="esteid/auth-new.html"), name="sk_test_auth_new"),
url(r"^download/", TestDownloadContainerView.as_view(), name="download_signed_container"),
url(r"^id/start/", TestIdCardSignView.as_view(), name="test_id_start"),
url(r"^id/finish/", TestIdCardFinishView.as_view(), name="test_id_finish"),
url(r"^mid/start/", TestMobileIdSignView.as_view(), name="test_mid_start"),
url(r"^mid/status/", TestMobileIdStatusView.as_view(), name="test_mid_status"),
url(r"^smartid/start/", TestSmartIdSignView.as_view(), name="test_smartid_start"),
url(r"^smartid/status/", TestSmartIdStatusView.as_view(), name="test_smartid_status"),
url(r"^flowtest/", include(esteid.flowtest.urls)),
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import esteid.flowtest.urls
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from .views import (
SKTestView,
TestDownloadContainerView,
TestIdCardFinishView,
TestIdCardSignView,
TestMobileIdSignView,
TestMobileIdStatusView,
TestSmartIdSignView,
TestSmartIdStatusView,
)
and context (classes, functions, sometimes code) from other files:
# Path: esteid/views.py
# class SKTestView(TemplateView):
# template_name = "esteid/test.html"
#
# def get_context_data(self, **kwargs):
# context = super(SKTestView, self).get_context_data(**kwargs)
#
# try:
# files = self.request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# context.update(
# {
# "files": files,
# }
# )
#
# return context
#
# def post(self, request, *args, **kwargs):
# """This method is only for testing and can
# be used to add some files to the session.
#
# actions:
#
# - add_file
# - remove_file
# """
# try:
# files = request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# action = request.POST.get("action", "add_file")
#
# if action == "remove_file":
# file_name = request.POST.get("file_name", "")
#
# n_files = {}
# for key, file in files.items():
# if key != file_name:
# n_files[key] = file
#
# files = n_files
#
# else:
# for key, file in request.FILES.items():
# file_name = file.name
#
# idx = 1
# while file_name in files.keys():
# file_name = f"{idx}_{file_name}"
# idx += 1
#
# files[file_name] = dict(
# content=base64.b64encode(file.read()).decode(),
# content_type=file.content_type,
# size=file.size,
# )
#
# request.session["__ddoc_files"] = files
#
# return HttpResponseRedirect(".")
#
# class TestDownloadContainerView(View):
# def get(self, request, *args, **kwargs):
# request.session.pop("__ddoc_files", None)
#
# container_file = request.session.pop("__ddoc_container_file", None)
# logging.info("Got container temp file name '%s'", container_file)
# file_contents = None
# if container_file:
# try:
# with open(container_file, "rb") as f:
# file_contents = f.read()
# except FileNotFoundError:
# pass
#
# if not file_contents:
# response = HttpResponse("Error: no container file found", status=409)
# else:
# # Download the file
# response = HttpResponse(file_contents, content_type=Container.MIME_TYPE)
# response["Content-Disposition"] = "attachment; filename=" + "signed.bdoc"
# return response
#
# class TestIdCardFinishView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = IdCardFinishAction
#
# def build_action_kwargs(self, request):
# return dict(signature_value=request.POST["signature_value"])
#
# class TestIdCardSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return IdCardPrepareAction.do_action(self, certificate=request.POST["certificate"])
#
# class TestMobileIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return MobileIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# phone_number=request.POST.get("phone_nr", ""),
# language=request.POST.get("language", None),
# )
#
# class TestMobileIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = MobileIdStatusAction
#
# class TestSmartIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return SmartIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# language=request.POST.get("language", None),
# )
#
# class TestSmartIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = SmartIdStatusAction
. Output only the next line. | ] |
Predict the next line after this snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
url("^$", SKTestView.as_view(), name="sk_test"),
# NOTE: compare the template test-new.html to test.html locally to see JS changes.
url(r"^new/", SKTestView.as_view(template_name="esteid/test-new.html"), name="sk_test_new"),
url(r"^new-auth/", TemplateView.as_view(template_name="esteid/auth-new.html"), name="sk_test_auth_new"),
url(r"^download/", TestDownloadContainerView.as_view(), name="download_signed_container"),
url(r"^id/start/", TestIdCardSignView.as_view(), name="test_id_start"),
url(r"^id/finish/", TestIdCardFinishView.as_view(), name="test_id_finish"),
url(r"^mid/start/", TestMobileIdSignView.as_view(), name="test_mid_start"),
url(r"^mid/status/", TestMobileIdStatusView.as_view(), name="test_mid_status"),
url(r"^smartid/start/", TestSmartIdSignView.as_view(), name="test_smartid_start"),
url(r"^smartid/status/", TestSmartIdStatusView.as_view(), name="test_smartid_status"),
<|code_end|>
using the current file's imports:
import os
import esteid.flowtest.urls
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from .views import (
SKTestView,
TestDownloadContainerView,
TestIdCardFinishView,
TestIdCardSignView,
TestMobileIdSignView,
TestMobileIdStatusView,
TestSmartIdSignView,
TestSmartIdStatusView,
)
and any relevant context from other files:
# Path: esteid/views.py
# class SKTestView(TemplateView):
# template_name = "esteid/test.html"
#
# def get_context_data(self, **kwargs):
# context = super(SKTestView, self).get_context_data(**kwargs)
#
# try:
# files = self.request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# context.update(
# {
# "files": files,
# }
# )
#
# return context
#
# def post(self, request, *args, **kwargs):
# """This method is only for testing and can
# be used to add some files to the session.
#
# actions:
#
# - add_file
# - remove_file
# """
# try:
# files = request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# action = request.POST.get("action", "add_file")
#
# if action == "remove_file":
# file_name = request.POST.get("file_name", "")
#
# n_files = {}
# for key, file in files.items():
# if key != file_name:
# n_files[key] = file
#
# files = n_files
#
# else:
# for key, file in request.FILES.items():
# file_name = file.name
#
# idx = 1
# while file_name in files.keys():
# file_name = f"{idx}_{file_name}"
# idx += 1
#
# files[file_name] = dict(
# content=base64.b64encode(file.read()).decode(),
# content_type=file.content_type,
# size=file.size,
# )
#
# request.session["__ddoc_files"] = files
#
# return HttpResponseRedirect(".")
#
# class TestDownloadContainerView(View):
# def get(self, request, *args, **kwargs):
# request.session.pop("__ddoc_files", None)
#
# container_file = request.session.pop("__ddoc_container_file", None)
# logging.info("Got container temp file name '%s'", container_file)
# file_contents = None
# if container_file:
# try:
# with open(container_file, "rb") as f:
# file_contents = f.read()
# except FileNotFoundError:
# pass
#
# if not file_contents:
# response = HttpResponse("Error: no container file found", status=409)
# else:
# # Download the file
# response = HttpResponse(file_contents, content_type=Container.MIME_TYPE)
# response["Content-Disposition"] = "attachment; filename=" + "signed.bdoc"
# return response
#
# class TestIdCardFinishView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = IdCardFinishAction
#
# def build_action_kwargs(self, request):
# return dict(signature_value=request.POST["signature_value"])
#
# class TestIdCardSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return IdCardPrepareAction.do_action(self, certificate=request.POST["certificate"])
#
# class TestMobileIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return MobileIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# phone_number=request.POST.get("phone_nr", ""),
# language=request.POST.get("language", None),
# )
#
# class TestMobileIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = MobileIdStatusAction
#
# class TestSmartIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return SmartIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# language=request.POST.get("language", None),
# )
#
# class TestSmartIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = SmartIdStatusAction
. Output only the next line. | url(r"^flowtest/", include(esteid.flowtest.urls)), |
Here is a snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
url("^$", SKTestView.as_view(), name="sk_test"),
# NOTE: compare the template test-new.html to test.html locally to see JS changes.
url(r"^new/", SKTestView.as_view(template_name="esteid/test-new.html"), name="sk_test_new"),
url(r"^new-auth/", TemplateView.as_view(template_name="esteid/auth-new.html"), name="sk_test_auth_new"),
url(r"^download/", TestDownloadContainerView.as_view(), name="download_signed_container"),
url(r"^id/start/", TestIdCardSignView.as_view(), name="test_id_start"),
url(r"^id/finish/", TestIdCardFinishView.as_view(), name="test_id_finish"),
url(r"^mid/start/", TestMobileIdSignView.as_view(), name="test_mid_start"),
url(r"^mid/status/", TestMobileIdStatusView.as_view(), name="test_mid_status"),
url(r"^smartid/start/", TestSmartIdSignView.as_view(), name="test_smartid_start"),
url(r"^smartid/status/", TestSmartIdStatusView.as_view(), name="test_smartid_status"),
url(r"^flowtest/", include(esteid.flowtest.urls)),
<|code_end|>
. Write the next line using the current file imports:
import os
import esteid.flowtest.urls
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from .views import (
SKTestView,
TestDownloadContainerView,
TestIdCardFinishView,
TestIdCardSignView,
TestMobileIdSignView,
TestMobileIdStatusView,
TestSmartIdSignView,
TestSmartIdStatusView,
)
and context from other files:
# Path: esteid/views.py
# class SKTestView(TemplateView):
# template_name = "esteid/test.html"
#
# def get_context_data(self, **kwargs):
# context = super(SKTestView, self).get_context_data(**kwargs)
#
# try:
# files = self.request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# context.update(
# {
# "files": files,
# }
# )
#
# return context
#
# def post(self, request, *args, **kwargs):
# """This method is only for testing and can
# be used to add some files to the session.
#
# actions:
#
# - add_file
# - remove_file
# """
# try:
# files = request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# action = request.POST.get("action", "add_file")
#
# if action == "remove_file":
# file_name = request.POST.get("file_name", "")
#
# n_files = {}
# for key, file in files.items():
# if key != file_name:
# n_files[key] = file
#
# files = n_files
#
# else:
# for key, file in request.FILES.items():
# file_name = file.name
#
# idx = 1
# while file_name in files.keys():
# file_name = f"{idx}_{file_name}"
# idx += 1
#
# files[file_name] = dict(
# content=base64.b64encode(file.read()).decode(),
# content_type=file.content_type,
# size=file.size,
# )
#
# request.session["__ddoc_files"] = files
#
# return HttpResponseRedirect(".")
#
# class TestDownloadContainerView(View):
# def get(self, request, *args, **kwargs):
# request.session.pop("__ddoc_files", None)
#
# container_file = request.session.pop("__ddoc_container_file", None)
# logging.info("Got container temp file name '%s'", container_file)
# file_contents = None
# if container_file:
# try:
# with open(container_file, "rb") as f:
# file_contents = f.read()
# except FileNotFoundError:
# pass
#
# if not file_contents:
# response = HttpResponse("Error: no container file found", status=409)
# else:
# # Download the file
# response = HttpResponse(file_contents, content_type=Container.MIME_TYPE)
# response["Content-Disposition"] = "attachment; filename=" + "signed.bdoc"
# return response
#
# class TestIdCardFinishView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = IdCardFinishAction
#
# def build_action_kwargs(self, request):
# return dict(signature_value=request.POST["signature_value"])
#
# class TestIdCardSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return IdCardPrepareAction.do_action(self, certificate=request.POST["certificate"])
#
# class TestMobileIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return MobileIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# phone_number=request.POST.get("phone_nr", ""),
# language=request.POST.get("language", None),
# )
#
# class TestMobileIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = MobileIdStatusAction
#
# class TestSmartIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return SmartIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# language=request.POST.get("language", None),
# )
#
# class TestSmartIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = SmartIdStatusAction
, which may include functions, classes, or code. Output only the next line. | ] |
Using the snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
url("^$", SKTestView.as_view(), name="sk_test"),
# NOTE: compare the template test-new.html to test.html locally to see JS changes.
url(r"^new/", SKTestView.as_view(template_name="esteid/test-new.html"), name="sk_test_new"),
url(r"^new-auth/", TemplateView.as_view(template_name="esteid/auth-new.html"), name="sk_test_auth_new"),
url(r"^download/", TestDownloadContainerView.as_view(), name="download_signed_container"),
url(r"^id/start/", TestIdCardSignView.as_view(), name="test_id_start"),
url(r"^id/finish/", TestIdCardFinishView.as_view(), name="test_id_finish"),
url(r"^mid/start/", TestMobileIdSignView.as_view(), name="test_mid_start"),
url(r"^mid/status/", TestMobileIdStatusView.as_view(), name="test_mid_status"),
url(r"^smartid/start/", TestSmartIdSignView.as_view(), name="test_smartid_start"),
url(r"^smartid/status/", TestSmartIdStatusView.as_view(), name="test_smartid_status"),
url(r"^flowtest/", include(esteid.flowtest.urls)),
]
<|code_end|>
, determine the next line of code. You have imports:
import os
import esteid.flowtest.urls
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from .views import (
SKTestView,
TestDownloadContainerView,
TestIdCardFinishView,
TestIdCardSignView,
TestMobileIdSignView,
TestMobileIdStatusView,
TestSmartIdSignView,
TestSmartIdStatusView,
)
and context (class names, function names, or code) available:
# Path: esteid/views.py
# class SKTestView(TemplateView):
# template_name = "esteid/test.html"
#
# def get_context_data(self, **kwargs):
# context = super(SKTestView, self).get_context_data(**kwargs)
#
# try:
# files = self.request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# context.update(
# {
# "files": files,
# }
# )
#
# return context
#
# def post(self, request, *args, **kwargs):
# """This method is only for testing and can
# be used to add some files to the session.
#
# actions:
#
# - add_file
# - remove_file
# """
# try:
# files = request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# action = request.POST.get("action", "add_file")
#
# if action == "remove_file":
# file_name = request.POST.get("file_name", "")
#
# n_files = {}
# for key, file in files.items():
# if key != file_name:
# n_files[key] = file
#
# files = n_files
#
# else:
# for key, file in request.FILES.items():
# file_name = file.name
#
# idx = 1
# while file_name in files.keys():
# file_name = f"{idx}_{file_name}"
# idx += 1
#
# files[file_name] = dict(
# content=base64.b64encode(file.read()).decode(),
# content_type=file.content_type,
# size=file.size,
# )
#
# request.session["__ddoc_files"] = files
#
# return HttpResponseRedirect(".")
#
# class TestDownloadContainerView(View):
# def get(self, request, *args, **kwargs):
# request.session.pop("__ddoc_files", None)
#
# container_file = request.session.pop("__ddoc_container_file", None)
# logging.info("Got container temp file name '%s'", container_file)
# file_contents = None
# if container_file:
# try:
# with open(container_file, "rb") as f:
# file_contents = f.read()
# except FileNotFoundError:
# pass
#
# if not file_contents:
# response = HttpResponse("Error: no container file found", status=409)
# else:
# # Download the file
# response = HttpResponse(file_contents, content_type=Container.MIME_TYPE)
# response["Content-Disposition"] = "attachment; filename=" + "signed.bdoc"
# return response
#
# class TestIdCardFinishView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = IdCardFinishAction
#
# def build_action_kwargs(self, request):
# return dict(signature_value=request.POST["signature_value"])
#
# class TestIdCardSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return IdCardPrepareAction.do_action(self, certificate=request.POST["certificate"])
#
# class TestMobileIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return MobileIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# phone_number=request.POST.get("phone_nr", ""),
# language=request.POST.get("language", None),
# )
#
# class TestMobileIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = MobileIdStatusAction
#
# class TestSmartIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return SmartIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# language=request.POST.get("language", None),
# )
#
# class TestSmartIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = SmartIdStatusAction
. Output only the next line. | urlpatterns += static(settings.STATIC_URL, document_root=os.path.dirname(__file__) + "/static/") |
Predict the next line after this snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
url("^$", SKTestView.as_view(), name="sk_test"),
# NOTE: compare the template test-new.html to test.html locally to see JS changes.
url(r"^new/", SKTestView.as_view(template_name="esteid/test-new.html"), name="sk_test_new"),
url(r"^new-auth/", TemplateView.as_view(template_name="esteid/auth-new.html"), name="sk_test_auth_new"),
url(r"^download/", TestDownloadContainerView.as_view(), name="download_signed_container"),
url(r"^id/start/", TestIdCardSignView.as_view(), name="test_id_start"),
url(r"^id/finish/", TestIdCardFinishView.as_view(), name="test_id_finish"),
url(r"^mid/start/", TestMobileIdSignView.as_view(), name="test_mid_start"),
url(r"^mid/status/", TestMobileIdStatusView.as_view(), name="test_mid_status"),
url(r"^smartid/start/", TestSmartIdSignView.as_view(), name="test_smartid_start"),
url(r"^smartid/status/", TestSmartIdStatusView.as_view(), name="test_smartid_status"),
url(r"^flowtest/", include(esteid.flowtest.urls)),
]
<|code_end|>
using the current file's imports:
import os
import esteid.flowtest.urls
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from .views import (
SKTestView,
TestDownloadContainerView,
TestIdCardFinishView,
TestIdCardSignView,
TestMobileIdSignView,
TestMobileIdStatusView,
TestSmartIdSignView,
TestSmartIdStatusView,
)
and any relevant context from other files:
# Path: esteid/views.py
# class SKTestView(TemplateView):
# template_name = "esteid/test.html"
#
# def get_context_data(self, **kwargs):
# context = super(SKTestView, self).get_context_data(**kwargs)
#
# try:
# files = self.request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# context.update(
# {
# "files": files,
# }
# )
#
# return context
#
# def post(self, request, *args, **kwargs):
# """This method is only for testing and can
# be used to add some files to the session.
#
# actions:
#
# - add_file
# - remove_file
# """
# try:
# files = request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# action = request.POST.get("action", "add_file")
#
# if action == "remove_file":
# file_name = request.POST.get("file_name", "")
#
# n_files = {}
# for key, file in files.items():
# if key != file_name:
# n_files[key] = file
#
# files = n_files
#
# else:
# for key, file in request.FILES.items():
# file_name = file.name
#
# idx = 1
# while file_name in files.keys():
# file_name = f"{idx}_{file_name}"
# idx += 1
#
# files[file_name] = dict(
# content=base64.b64encode(file.read()).decode(),
# content_type=file.content_type,
# size=file.size,
# )
#
# request.session["__ddoc_files"] = files
#
# return HttpResponseRedirect(".")
#
# class TestDownloadContainerView(View):
# def get(self, request, *args, **kwargs):
# request.session.pop("__ddoc_files", None)
#
# container_file = request.session.pop("__ddoc_container_file", None)
# logging.info("Got container temp file name '%s'", container_file)
# file_contents = None
# if container_file:
# try:
# with open(container_file, "rb") as f:
# file_contents = f.read()
# except FileNotFoundError:
# pass
#
# if not file_contents:
# response = HttpResponse("Error: no container file found", status=409)
# else:
# # Download the file
# response = HttpResponse(file_contents, content_type=Container.MIME_TYPE)
# response["Content-Disposition"] = "attachment; filename=" + "signed.bdoc"
# return response
#
# class TestIdCardFinishView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = IdCardFinishAction
#
# def build_action_kwargs(self, request):
# return dict(signature_value=request.POST["signature_value"])
#
# class TestIdCardSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return IdCardPrepareAction.do_action(self, certificate=request.POST["certificate"])
#
# class TestMobileIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return MobileIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# phone_number=request.POST.get("phone_nr", ""),
# language=request.POST.get("language", None),
# )
#
# class TestMobileIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = MobileIdStatusAction
#
# class TestSmartIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return SmartIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# language=request.POST.get("language", None),
# )
#
# class TestSmartIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = SmartIdStatusAction
. Output only the next line. | urlpatterns += static(settings.STATIC_URL, document_root=os.path.dirname(__file__) + "/static/") |
Using the snippet: <|code_start|>
urlpatterns = []
# In a project, the URLs can be included if settings.DEBUG is on.
# In tests, settings.DEBUG is False for unknown reasons, so we check that the root urlconf points at this file.
if settings.DEBUG or settings.ROOT_URLCONF == __name__:
urlpatterns += [
url("^$", SKTestView.as_view(), name="sk_test"),
# NOTE: compare the template test-new.html to test.html locally to see JS changes.
url(r"^new/", SKTestView.as_view(template_name="esteid/test-new.html"), name="sk_test_new"),
url(r"^new-auth/", TemplateView.as_view(template_name="esteid/auth-new.html"), name="sk_test_auth_new"),
url(r"^download/", TestDownloadContainerView.as_view(), name="download_signed_container"),
url(r"^id/start/", TestIdCardSignView.as_view(), name="test_id_start"),
url(r"^id/finish/", TestIdCardFinishView.as_view(), name="test_id_finish"),
url(r"^mid/start/", TestMobileIdSignView.as_view(), name="test_mid_start"),
url(r"^mid/status/", TestMobileIdStatusView.as_view(), name="test_mid_status"),
url(r"^smartid/start/", TestSmartIdSignView.as_view(), name="test_smartid_start"),
url(r"^smartid/status/", TestSmartIdStatusView.as_view(), name="test_smartid_status"),
url(r"^flowtest/", include(esteid.flowtest.urls)),
]
<|code_end|>
, determine the next line of code. You have imports:
import os
import esteid.flowtest.urls
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from .views import (
SKTestView,
TestDownloadContainerView,
TestIdCardFinishView,
TestIdCardSignView,
TestMobileIdSignView,
TestMobileIdStatusView,
TestSmartIdSignView,
TestSmartIdStatusView,
)
and context (class names, function names, or code) available:
# Path: esteid/views.py
# class SKTestView(TemplateView):
# template_name = "esteid/test.html"
#
# def get_context_data(self, **kwargs):
# context = super(SKTestView, self).get_context_data(**kwargs)
#
# try:
# files = self.request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# context.update(
# {
# "files": files,
# }
# )
#
# return context
#
# def post(self, request, *args, **kwargs):
# """This method is only for testing and can
# be used to add some files to the session.
#
# actions:
#
# - add_file
# - remove_file
# """
# try:
# files = request.session["__ddoc_files"]
#
# except KeyError:
# files = {}
#
# action = request.POST.get("action", "add_file")
#
# if action == "remove_file":
# file_name = request.POST.get("file_name", "")
#
# n_files = {}
# for key, file in files.items():
# if key != file_name:
# n_files[key] = file
#
# files = n_files
#
# else:
# for key, file in request.FILES.items():
# file_name = file.name
#
# idx = 1
# while file_name in files.keys():
# file_name = f"{idx}_{file_name}"
# idx += 1
#
# files[file_name] = dict(
# content=base64.b64encode(file.read()).decode(),
# content_type=file.content_type,
# size=file.size,
# )
#
# request.session["__ddoc_files"] = files
#
# return HttpResponseRedirect(".")
#
# class TestDownloadContainerView(View):
# def get(self, request, *args, **kwargs):
# request.session.pop("__ddoc_files", None)
#
# container_file = request.session.pop("__ddoc_container_file", None)
# logging.info("Got container temp file name '%s'", container_file)
# file_contents = None
# if container_file:
# try:
# with open(container_file, "rb") as f:
# file_contents = f.read()
# except FileNotFoundError:
# pass
#
# if not file_contents:
# response = HttpResponse("Error: no container file found", status=409)
# else:
# # Download the file
# response = HttpResponse(file_contents, content_type=Container.MIME_TYPE)
# response["Content-Disposition"] = "attachment; filename=" + "signed.bdoc"
# return response
#
# class TestIdCardFinishView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = IdCardFinishAction
#
# def build_action_kwargs(self, request):
# return dict(signature_value=request.POST["signature_value"])
#
# class TestIdCardSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return IdCardPrepareAction.do_action(self, certificate=request.POST["certificate"])
#
# class TestMobileIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return MobileIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# phone_number=request.POST.get("phone_nr", ""),
# language=request.POST.get("language", None),
# )
#
# class TestMobileIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = MobileIdStatusAction
#
# class TestSmartIdSignView(TestFilesMixin, ApiView):
# def post(self, request, *args, **kwargs):
# return SmartIdSignAction.do_action(
# self,
# id_code=request.POST.get("id_code", ""),
# language=request.POST.get("language", None),
# )
#
# class TestSmartIdStatusView(TestSignStatusViewMixin, ApiView):
# ACTION_CLASS = SmartIdStatusAction
. Output only the next line. | urlpatterns += static(settings.STATIC_URL, document_root=os.path.dirname(__file__) + "/static/") |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize("hash_algo", HASH_ALGORITHMS)
def test_hashtypes(hash_algo):
hash_value = generate_hash(hash_algo, b"FOOBAR")
hash_method = getattr(hashlib, hash_algo.lower())
assert hash_value == hash_method(b"FOOBAR").digest()
def test_invalid_hash_algo_fails():
with pytest.raises(ValueError):
generate_hash("FAKEHASH", b"FOOBAR")
@pytest.mark.parametrize(
"id_code, result",
<|code_end|>
, generate the next line using the imports in this file:
import hashlib
import pytest
from esteid.constants import HASH_ALGORITHMS
from esteid.util import generate_hash
from esteid.validators import id_code_ee_is_valid, id_code_lt_is_valid, id_code_lv_is_valid
and context (functions, classes, or occasionally code) from other files:
# Path: esteid/constants.py
# HASH_ALGORITHMS = {
# HASH_SHA256,
# HASH_SHA384,
# HASH_SHA512,
# }
#
# Path: esteid/util.py
# def generate_hash(algorithm, data):
# """Hash the data with the supplied algorithm
#
# https://github.com/SK-EID/smart-id-documentation#33-hash-algorithms
# https://github.com/SK-EID/MID#231-supported-hashing-algorithms
# """
# if algorithm.upper() not in HASH_ALGORITHMS:
# raise ValueError(f"Unsupported algorithm {algorithm}")
#
# hash_method = getattr(hashlib, algorithm.lower())
# digest = hash_method(data).digest()
#
# return digest
#
# Path: esteid/validators.py
# ID_CODE_EE_REGEXP = re.compile(r"^[1-6] \d{2} [01]\d [0123]\d \d{4}$", re.VERBOSE)
# ID_CODE_LT_REGEXP = ID_CODE_EE_REGEXP
# ID_CODE_LV_REGEXP = re.compile(r"^\d{6}-\d{5}$")
# ID_CODE_VALIDATORS = {
# Countries.ESTONIA: id_code_ee_is_valid,
# Countries.LATVIA: id_code_lv_is_valid,
# Countries.LITHUANIA: id_code_lt_is_valid,
# }
# def id_code_ee_is_valid(id_code: str) -> bool:
# def id_code_lv_is_valid(id_code: str) -> bool:
# def validate_id_code(id_code, country):
. Output only the next line. | [ |
Using the snippet: <|code_start|>
@pytest.mark.parametrize("hash_algo", HASH_ALGORITHMS)
def test_hashtypes(hash_algo):
hash_value = generate_hash(hash_algo, b"FOOBAR")
hash_method = getattr(hashlib, hash_algo.lower())
assert hash_value == hash_method(b"FOOBAR").digest()
def test_invalid_hash_algo_fails():
with pytest.raises(ValueError):
generate_hash("FAKEHASH", b"FOOBAR")
@pytest.mark.parametrize(
"id_code, result",
[
pytest.param("", False, id="empty string"),
pytest.param(None, False, id="None"),
pytest.param(["30303039914"], False, id="list"),
pytest.param("ABCDEFGHQWE", False, id="not digits"),
pytest.param("10101010", False, id="not enough digits"),
pytest.param("10101010OO5", False, id="not all digits (0-O)"),
pytest.param("123456789O123456", False, id="too many digits"),
pytest.param("10101010101", False, id="wrong checksum"),
pytest.param("30303039914", True, id="test SmartID code"),
<|code_end|>
, determine the next line of code. You have imports:
import hashlib
import pytest
from esteid.constants import HASH_ALGORITHMS
from esteid.util import generate_hash
from esteid.validators import id_code_ee_is_valid, id_code_lt_is_valid, id_code_lv_is_valid
and context (class names, function names, or code) available:
# Path: esteid/constants.py
# HASH_ALGORITHMS = {
# HASH_SHA256,
# HASH_SHA384,
# HASH_SHA512,
# }
#
# Path: esteid/util.py
# def generate_hash(algorithm, data):
# """Hash the data with the supplied algorithm
#
# https://github.com/SK-EID/smart-id-documentation#33-hash-algorithms
# https://github.com/SK-EID/MID#231-supported-hashing-algorithms
# """
# if algorithm.upper() not in HASH_ALGORITHMS:
# raise ValueError(f"Unsupported algorithm {algorithm}")
#
# hash_method = getattr(hashlib, algorithm.lower())
# digest = hash_method(data).digest()
#
# return digest
#
# Path: esteid/validators.py
# ID_CODE_EE_REGEXP = re.compile(r"^[1-6] \d{2} [01]\d [0123]\d \d{4}$", re.VERBOSE)
# ID_CODE_LT_REGEXP = ID_CODE_EE_REGEXP
# ID_CODE_LV_REGEXP = re.compile(r"^\d{6}-\d{5}$")
# ID_CODE_VALIDATORS = {
# Countries.ESTONIA: id_code_ee_is_valid,
# Countries.LATVIA: id_code_lv_is_valid,
# Countries.LITHUANIA: id_code_lt_is_valid,
# }
# def id_code_ee_is_valid(id_code: str) -> bool:
# def id_code_lv_is_valid(id_code: str) -> bool:
# def validate_id_code(id_code, country):
. Output only the next line. | pytest.param("60001019906", True, id="test MobileID code"), |
Predict the next line for this snippet: <|code_start|> [
pytest.param("", False, id="empty string"),
pytest.param(None, False, id="None"),
pytest.param(["30303039914"], False, id="list"),
pytest.param("ABCDEFGHQWE", False, id="not digits"),
pytest.param("10101010", False, id="not enough digits"),
pytest.param("10101010OO5", False, id="not all digits (0-O)"),
pytest.param("123456789O123456", False, id="too many digits"),
pytest.param("10101010101", False, id="wrong checksum"),
pytest.param("30303039914", True, id="test SmartID code"),
pytest.param("60001019906", True, id="test MobileID code"),
pytest.param("37605030299", True, id="From Wikipedia"),
],
)
def test_id_code_ee_lt_is_valid(id_code, result):
assert id_code_ee_is_valid(id_code) == result
assert id_code_lt_is_valid(id_code) == result, "LT ID codes are same format as EE"
@pytest.mark.parametrize(
"id_code, result",
[
pytest.param("", False, id="empty string"),
pytest.param(None, False, id="None"),
pytest.param(["010101-10006"], False, id="list"),
pytest.param("ABCDEF-QWERT", False, id="not digits"),
pytest.param("01010110006", False, id="no dash"),
pytest.param("010101-1OOO6", False, id="not all digits (0-O)"),
pytest.param("123456-789O123456", False, id="too many digits"),
pytest.param("010101-01010", False, id="wrong checksum"),
<|code_end|>
with the help of current file imports:
import hashlib
import pytest
from esteid.constants import HASH_ALGORITHMS
from esteid.util import generate_hash
from esteid.validators import id_code_ee_is_valid, id_code_lt_is_valid, id_code_lv_is_valid
and context from other files:
# Path: esteid/constants.py
# HASH_ALGORITHMS = {
# HASH_SHA256,
# HASH_SHA384,
# HASH_SHA512,
# }
#
# Path: esteid/util.py
# def generate_hash(algorithm, data):
# """Hash the data with the supplied algorithm
#
# https://github.com/SK-EID/smart-id-documentation#33-hash-algorithms
# https://github.com/SK-EID/MID#231-supported-hashing-algorithms
# """
# if algorithm.upper() not in HASH_ALGORITHMS:
# raise ValueError(f"Unsupported algorithm {algorithm}")
#
# hash_method = getattr(hashlib, algorithm.lower())
# digest = hash_method(data).digest()
#
# return digest
#
# Path: esteid/validators.py
# ID_CODE_EE_REGEXP = re.compile(r"^[1-6] \d{2} [01]\d [0123]\d \d{4}$", re.VERBOSE)
# ID_CODE_LT_REGEXP = ID_CODE_EE_REGEXP
# ID_CODE_LV_REGEXP = re.compile(r"^\d{6}-\d{5}$")
# ID_CODE_VALIDATORS = {
# Countries.ESTONIA: id_code_ee_is_valid,
# Countries.LATVIA: id_code_lv_is_valid,
# Countries.LITHUANIA: id_code_lt_is_valid,
# }
# def id_code_ee_is_valid(id_code: str) -> bool:
# def id_code_lv_is_valid(id_code: str) -> bool:
# def validate_id_code(id_code, country):
, which may contain function names, class names, or code. Output only the next line. | pytest.param("010101-10006", True, id="test MobileID code"), |
Next line prediction: <|code_start|>
@pytest.mark.parametrize("hash_algo", HASH_ALGORITHMS)
def test_hashtypes(hash_algo):
hash_value = generate_hash(hash_algo, b"FOOBAR")
hash_method = getattr(hashlib, hash_algo.lower())
<|code_end|>
. Use current file imports:
(import hashlib
import pytest
from esteid.constants import HASH_ALGORITHMS
from esteid.util import generate_hash
from esteid.validators import id_code_ee_is_valid, id_code_lt_is_valid, id_code_lv_is_valid)
and context including class names, function names, or small code snippets from other files:
# Path: esteid/constants.py
# HASH_ALGORITHMS = {
# HASH_SHA256,
# HASH_SHA384,
# HASH_SHA512,
# }
#
# Path: esteid/util.py
# def generate_hash(algorithm, data):
# """Hash the data with the supplied algorithm
#
# https://github.com/SK-EID/smart-id-documentation#33-hash-algorithms
# https://github.com/SK-EID/MID#231-supported-hashing-algorithms
# """
# if algorithm.upper() not in HASH_ALGORITHMS:
# raise ValueError(f"Unsupported algorithm {algorithm}")
#
# hash_method = getattr(hashlib, algorithm.lower())
# digest = hash_method(data).digest()
#
# return digest
#
# Path: esteid/validators.py
# ID_CODE_EE_REGEXP = re.compile(r"^[1-6] \d{2} [01]\d [0123]\d \d{4}$", re.VERBOSE)
# ID_CODE_LT_REGEXP = ID_CODE_EE_REGEXP
# ID_CODE_LV_REGEXP = re.compile(r"^\d{6}-\d{5}$")
# ID_CODE_VALIDATORS = {
# Countries.ESTONIA: id_code_ee_is_valid,
# Countries.LATVIA: id_code_lv_is_valid,
# Countries.LITHUANIA: id_code_lt_is_valid,
# }
# def id_code_ee_is_valid(id_code: str) -> bool:
# def id_code_lv_is_valid(id_code: str) -> bool:
# def validate_id_code(id_code, country):
. Output only the next line. | assert hash_value == hash_method(b"FOOBAR").digest() |
Given snippet: <|code_start|>
@pytest.mark.parametrize("hash_algo", HASH_ALGORITHMS)
def test_hashtypes(hash_algo):
hash_value = generate_hash(hash_algo, b"FOOBAR")
hash_method = getattr(hashlib, hash_algo.lower())
assert hash_value == hash_method(b"FOOBAR").digest()
def test_invalid_hash_algo_fails():
with pytest.raises(ValueError):
generate_hash("FAKEHASH", b"FOOBAR")
@pytest.mark.parametrize(
"id_code, result",
[
pytest.param("", False, id="empty string"),
pytest.param(None, False, id="None"),
pytest.param(["30303039914"], False, id="list"),
pytest.param("ABCDEFGHQWE", False, id="not digits"),
pytest.param("10101010", False, id="not enough digits"),
pytest.param("10101010OO5", False, id="not all digits (0-O)"),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import hashlib
import pytest
from esteid.constants import HASH_ALGORITHMS
from esteid.util import generate_hash
from esteid.validators import id_code_ee_is_valid, id_code_lt_is_valid, id_code_lv_is_valid
and context:
# Path: esteid/constants.py
# HASH_ALGORITHMS = {
# HASH_SHA256,
# HASH_SHA384,
# HASH_SHA512,
# }
#
# Path: esteid/util.py
# def generate_hash(algorithm, data):
# """Hash the data with the supplied algorithm
#
# https://github.com/SK-EID/smart-id-documentation#33-hash-algorithms
# https://github.com/SK-EID/MID#231-supported-hashing-algorithms
# """
# if algorithm.upper() not in HASH_ALGORITHMS:
# raise ValueError(f"Unsupported algorithm {algorithm}")
#
# hash_method = getattr(hashlib, algorithm.lower())
# digest = hash_method(data).digest()
#
# return digest
#
# Path: esteid/validators.py
# ID_CODE_EE_REGEXP = re.compile(r"^[1-6] \d{2} [01]\d [0123]\d \d{4}$", re.VERBOSE)
# ID_CODE_LT_REGEXP = ID_CODE_EE_REGEXP
# ID_CODE_LV_REGEXP = re.compile(r"^\d{6}-\d{5}$")
# ID_CODE_VALIDATORS = {
# Countries.ESTONIA: id_code_ee_is_valid,
# Countries.LATVIA: id_code_lv_is_valid,
# Countries.LITHUANIA: id_code_lt_is_valid,
# }
# def id_code_ee_is_valid(id_code: str) -> bool:
# def id_code_lv_is_valid(id_code: str) -> bool:
# def validate_id_code(id_code, country):
which might include code, classes, or functions. Output only the next line. | pytest.param("123456789O123456", False, id="too many digits"), |
Using the snippet: <|code_start|>
def esteid_services(*_, **__):
return {
"ESTEID_DEMO": settings.ESTEID_DEMO,
"ID_CARD_ENABLED": settings.ID_CARD_ENABLED,
"MOBILE_ID_ENABLED": settings.MOBILE_ID_ENABLED,
"MOBILE_ID_TEST_MODE": settings.MOBILE_ID_TEST_MODE,
"SMART_ID_ENABLED": settings.SMART_ID_ENABLED,
"SMART_ID_TEST_MODE": settings.SMART_ID_TEST_MODE,
<|code_end|>
, determine the next line of code. You have imports:
from esteid import settings
and context (class names, function names, or code) available:
# Path: esteid/settings.py
# ESTEID_DEMO = getattr(settings, "ESTEID_DEMO", True)
# ID_CARD_ENABLED = getattr(settings, "ID_CARD_ENABLED", False)
# ID_CARD_FRAME_TARGET_ORIGIN = getattr(settings, "ID_CARD_FRAME_TARGET_ORIGIN", "*")
# MOBILE_ID_ENABLED = getattr(settings, "MOBILE_ID_ENABLED", False)
# MOBILE_ID_TEST_MODE = getattr(settings, "MOBILE_ID_TEST_MODE", ESTEID_DEMO)
# MOBILE_ID_SERVICE_NAME = getattr(settings, "MOBILE_ID_SERVICE_NAME", None)
# MOBILE_ID_SERVICE_UUID = getattr(settings, "MOBILE_ID_SERVICE_UUID", None)
# MOBILE_ID_API_ROOT = getattr(settings, "MOBILE_ID_API_ROOT", None)
# _MOBILE_ID_PHONE_NUMBER_REGEXP = getattr(settings, "MOBILE_ID_PHONE_NUMBER_REGEXP", None)
# _MOBILE_ID_PHONE_NUMBER_REGEXP = re.compile(r"^\+37[02]\d{7,8}$")
# _MOBILE_ID_PHONE_NUMBER_REGEXP = re.compile(_MOBILE_ID_PHONE_NUMBER_REGEXP)
# MOBILE_ID_PHONE_NUMBER_REGEXP = _MOBILE_ID_PHONE_NUMBER_REGEXP
# _MOBILE_ID_DEFAULT_LANGUAGE = getattr(settings, "MOBILE_ID_DEFAULT_LANGUAGE", None)
# _MOBILE_ID_DEFAULT_LANGUAGE = Languages.identify_language(settings.LANGUAGE_CODE)
# _MOBILE_ID_DEFAULT_LANGUAGE = Languages.ENG
# MOBILE_ID_DEFAULT_LANGUAGE = Languages.identify_language(_MOBILE_ID_DEFAULT_LANGUAGE)
# MOBILE_ID_SERVICE_NAME = constants.MOBILE_ID_DEMO_SERVICE_NAME
# MOBILE_ID_SERVICE_UUID = constants.MOBILE_ID_DEMO_SERVICE_UUID
# MOBILE_ID_API_ROOT = constants.MOBILE_ID_DEMO_URL
# MOBILE_ID_API_ROOT = constants.MOBILE_ID_LIVE_URL
# SMART_ID_ENABLED = getattr(settings, "SMART_ID_ENABLED", False)
# SMART_ID_TEST_MODE = getattr(settings, "SMART_ID_TEST_MODE", ESTEID_DEMO)
# SMART_ID_SERVICE_NAME = getattr(settings, "SMART_ID_SERVICE_NAME", None)
# SMART_ID_SERVICE_UUID = getattr(settings, "SMART_ID_SERVICE_UUID", None)
# SMART_ID_API_ROOT = getattr(settings, "SMART_ID_API_ROOT", None)
# SMART_ID_SERVICE_NAME = constants.SMART_ID_DEMO_SERVICE_NAME
# SMART_ID_SERVICE_UUID = constants.SMART_ID_DEMO_SERVICE_UUID
# SMART_ID_API_ROOT = constants.SMART_ID_DEMO_URL
# SMART_ID_API_ROOT = constants.SMART_ID_LIVE_URL
# ESTEID_COUNTRY = getattr(settings, "ESTEID_COUNTRY", Countries.ESTONIA)
# ESTEID_USE_LT_TS = getattr(settings, "ESTEID_USE_LT_TS", True)
# OCSP_URL = getattr(settings, "ESTEID_OCSP_URL", constants.OCSP_DEMO_URL if ESTEID_DEMO else constants.OCSP_LIVE_URL)
# TSA_URL = getattr(settings, "ESTEID_TSA_URL", constants.TSA_DEMO_URL if ESTEID_DEMO else constants.TSA_LIVE_URL)
# ESTEID_OCSP_RESPONDER_CERTIFICATE_PATH = getattr(settings, "ESTEID_OCSP_RESPONDER_CERTIFICATE_PATH", None)
# ESTEID_ALLOW_ONE_PARTY_SIGN_TWICE = getattr(settings, "ESTEID_ALLOW_ONE_PARTY_SIGN_TWICE", ESTEID_DEMO)
. Output only the next line. | } |
Given the code snippet: <|code_start|>
try:
except ImportError:
# If rest framework is not installed, create a stub class so the isinstance check is always false
class DRFValidationError:
pass
<|code_end|>
, generate the next line using the imports in this file:
import json
import logging
from http import HTTPStatus
from typing import Callable, TYPE_CHECKING
from django.core.exceptions import ValidationError as DjangoValidationError
from django.http import Http404, HttpRequest, JsonResponse, QueryDict
from django.utils.translation import gettext
from esteid.exceptions import CanceledByUser, EsteidError, InvalidParameters
from rest_framework.exceptions import ValidationError as DRFValidationError
from django.contrib.sessions import base_session
and context (functions, classes, or occasionally code) from other files:
# Path: esteid/exceptions.py
# class CanceledByUser(InvalidParameters):
# """User canceled the operation."""
#
# status = HTTPStatus.CONFLICT
#
# default_message = _("The signing operation was canceled by the user.")
#
# class EsteidError(Exception):
# """
# A generic Esteid error.
#
# Provides an interface for displaying a translated message to the user.
#
# Note: by default, any message passed as a first positional argument is ignored, because it only
# serves for better logging. The User Interface should display a verbose error message
# in case of a user-caused error so that user can take action accordingly. Errors caused by service malfunction
# are likely not informative to a user without malicious intent.
#
# If the default message contains {key} placeholders, the exception is supposed to be
# raised with kwargs, these will be passed on to <translated default message>.format(**kwargs).
# """
#
# status = HTTPStatus.INTERNAL_SERVER_ERROR
#
# default_message = _("Something went wrong")
#
# kwargs: dict
#
# def __init__(self, message=None, **kwargs):
# super().__init__(message)
# self.kwargs = kwargs
#
# def get_message(self):
# return str(self.default_message).format(**self.kwargs)
#
# def get_user_error(self):
# return {
# "error": self.__class__.__name__, # error code that can be bound to JS translations
# # TODO review errors and add translations
# "message": self.get_message(),
# }
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
. Output only the next line. | if TYPE_CHECKING: |
Next line prediction: <|code_start|>
try:
except ImportError:
# If rest framework is not installed, create a stub class so the isinstance check is always false
class DRFValidationError:
pass
if TYPE_CHECKING:
# Make type checkers aware of request.session attribute which is missing on the HttpRequest class
<|code_end|>
. Use current file imports:
(import json
import logging
from http import HTTPStatus
from typing import Callable, TYPE_CHECKING
from django.core.exceptions import ValidationError as DjangoValidationError
from django.http import Http404, HttpRequest, JsonResponse, QueryDict
from django.utils.translation import gettext
from esteid.exceptions import CanceledByUser, EsteidError, InvalidParameters
from rest_framework.exceptions import ValidationError as DRFValidationError
from django.contrib.sessions import base_session)
and context including class names, function names, or small code snippets from other files:
# Path: esteid/exceptions.py
# class CanceledByUser(InvalidParameters):
# """User canceled the operation."""
#
# status = HTTPStatus.CONFLICT
#
# default_message = _("The signing operation was canceled by the user.")
#
# class EsteidError(Exception):
# """
# A generic Esteid error.
#
# Provides an interface for displaying a translated message to the user.
#
# Note: by default, any message passed as a first positional argument is ignored, because it only
# serves for better logging. The User Interface should display a verbose error message
# in case of a user-caused error so that user can take action accordingly. Errors caused by service malfunction
# are likely not informative to a user without malicious intent.
#
# If the default message contains {key} placeholders, the exception is supposed to be
# raised with kwargs, these will be passed on to <translated default message>.format(**kwargs).
# """
#
# status = HTTPStatus.INTERNAL_SERVER_ERROR
#
# default_message = _("Something went wrong")
#
# kwargs: dict
#
# def __init__(self, message=None, **kwargs):
# super().__init__(message)
# self.kwargs = kwargs
#
# def get_message(self):
# return str(self.default_message).format(**self.kwargs)
#
# def get_user_error(self):
# return {
# "error": self.__class__.__name__, # error code that can be bound to JS translations
# # TODO review errors and add translations
# "message": self.get_message(),
# }
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
. Output only the next line. | class RequestType(HttpRequest): |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
# If rest framework is not installed, create a stub class so the isinstance check is always false
class DRFValidationError:
pass
if TYPE_CHECKING:
# Make type checkers aware of request.session attribute which is missing on the HttpRequest class
class RequestType(HttpRequest):
<|code_end|>
with the help of current file imports:
import json
import logging
from http import HTTPStatus
from typing import Callable, TYPE_CHECKING
from django.core.exceptions import ValidationError as DjangoValidationError
from django.http import Http404, HttpRequest, JsonResponse, QueryDict
from django.utils.translation import gettext
from esteid.exceptions import CanceledByUser, EsteidError, InvalidParameters
from rest_framework.exceptions import ValidationError as DRFValidationError
from django.contrib.sessions import base_session
and context from other files:
# Path: esteid/exceptions.py
# class CanceledByUser(InvalidParameters):
# """User canceled the operation."""
#
# status = HTTPStatus.CONFLICT
#
# default_message = _("The signing operation was canceled by the user.")
#
# class EsteidError(Exception):
# """
# A generic Esteid error.
#
# Provides an interface for displaying a translated message to the user.
#
# Note: by default, any message passed as a first positional argument is ignored, because it only
# serves for better logging. The User Interface should display a verbose error message
# in case of a user-caused error so that user can take action accordingly. Errors caused by service malfunction
# are likely not informative to a user without malicious intent.
#
# If the default message contains {key} placeholders, the exception is supposed to be
# raised with kwargs, these will be passed on to <translated default message>.format(**kwargs).
# """
#
# status = HTTPStatus.INTERNAL_SERVER_ERROR
#
# default_message = _("Something went wrong")
#
# kwargs: dict
#
# def __init__(self, message=None, **kwargs):
# super().__init__(message)
# self.kwargs = kwargs
#
# def get_message(self):
# return str(self.default_message).format(**self.kwargs)
#
# def get_user_error(self):
# return {
# "error": self.__class__.__name__, # error code that can be bound to JS translations
# # TODO review errors and add translations
# "message": self.get_message(),
# }
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
, which may contain function names, class names, or code. Output only the next line. | session: base_session.AbstractBaseSession |
Given snippet: <|code_start|>
@pytest.mark.parametrize(
"hash_value,expected_verification_code",
[
(b"\x00\x00", "0000"),
(b"00", "1584"),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import hashlib
import pytest
from ..utils import get_verification_code
and context:
# Path: esteid/mobileid/utils.py
# def get_verification_code(hash_value):
# """Compute Mobile-ID verification code from a hash
#
# Excerpt from https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm
#
# 1. 6 bits from the beginning of hash and 7 bits from the end of hash are taken.
# 2. The resulting 13 bits are transformed into decimal number and printed out.
#
# The Verification code is a decimal 4-digits number in range 0000...8192, always 4 digits are displayed (e.g. 0041).
#
# :param bytes hash_value:
# """
# if not isinstance(hash_value, bytes):
# raise TypeError(f"Invalid hash value: expected bytes, got {type(hash_value)}")
#
# if not hash_value:
# raise ValueError("Hash value can not be empty")
#
# leading_byte = hash_value[0]
# trailing_byte = hash_value[-1]
#
# leading_6_bits = leading_byte >> 2
# trailing_7_bits = trailing_byte & 0x7F
#
# raw_value = (leading_6_bits << 7) + trailing_7_bits
# return f"{raw_value:04d}"
which might include code, classes, or functions. Output only the next line. | (hashlib.sha256(b"test").digest(), "5000"), |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
@pytest.mark.parametrize(
"common_name,expected_name",
[
("TESTNUMBER,SEITSMES,51001091072", "Seitsmes Testnumber"),
("TESTNUMBER\\,SEITSMES\\,51001091072", "Seitsmes Testnumber"),
("TEST-NUMBER,SEITSMES MEES,51001091072", "Seitsmes Mees Test-Number"),
("O’CONNEŽ-ŠUSLIK,MARY ÄNN,11412090004", "Mary Änn O’Connež-Šuslik"),
],
)
def test_get_name_from_legacy_common_name(common_name, expected_name):
result = get_name_from_legacy_common_name(common_name)
assert result == expected_name
@pytest.mark.parametrize(
<|code_end|>
. Use current file imports:
(import pytest
from esteid.util import get_id_from_legacy_common_name, get_name_from_legacy_common_name)
and context including class names, function names, or small code snippets from other files:
# Path: esteid/util.py
# def get_id_from_legacy_common_name(common_name):
# common_name = common_name.strip().rstrip(",")
#
# return common_name.split(",")[-1]
#
# def get_name_from_legacy_common_name(common_name):
# common_name = common_name.replace("\\,", ",")
# common_name = common_name.strip().rstrip(",")
#
# parts = common_name.split(",")[:-1]
# parts.reverse()
#
# return " ".join(parts).title()
. Output only the next line. | "common_name,expected_id", |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize(
"lang_code, result",
[
*[(code.upper(), code) for code in Languages.ALL],
*[(code.lower(), code) for code in Languages.ALL],
*[(alpha2.upper(), code) for alpha2, code in Languages._MAP_ISO_639_1_TO_MID.items()],
*[(alpha2.lower(), code) for alpha2, code in Languages._MAP_ISO_639_1_TO_MID.items()],
# These tests duplicate the ones above, just for clarity here.
("et", "EST"),
("est", "EST"),
("ET", "EST"),
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from django.core.exceptions import ImproperlyConfigured
from esteid.constants import Languages
and context (functions, classes, or occasionally code) from other files:
# Path: esteid/constants.py
# class Languages:
# """Used by MobileID"""
#
# ENG = "ENG"
# EST = "EST"
# LIT = "LIT"
# RUS = "RUS"
#
# ALL = (ENG, EST, LIT, RUS)
#
# # also allow ISO 639-1 (or alpha-2) codes
# _MAP_ISO_639_1_TO_MID = {
# "en": ENG,
# "et": EST,
# "lt": LIT,
# "ru": RUS,
# }
#
# @classmethod
# def identify_language(cls, language_code):
# all_langs = {**cls._MAP_ISO_639_1_TO_MID, **{c.lower(): c for c in cls.ALL}}
# try:
# language_code_lower = language_code.lower()
# return all_langs[language_code_lower]
# except (AttributeError, KeyError) as e:
# raise ImproperlyConfigured(f"Language should be one of {','.join(all_langs)}, got `{language_code}`") from e
. Output only the next line. | ("EST", "EST"), |
Based on the snippet: <|code_start|>
@pytest.fixture()
def idcardsigner():
signer = IdCardSigner({}, initial=True)
mock_container = Mock(name="mock_container")
with patch.object(signer, "open_container", return_value=mock_container), patch.object(signer, "save_session_data"):
mock_container.prepare_signature.return_value = mock_xml_sig = Mock(name="mock_xml_sig")
mock_xml_sig.digest.return_value = b"some binary digest"
yield signer
@pytest.fixture()
def idcard_session_data():
with NamedTemporaryFile("wb", delete=False) as f:
f.write(b"xml signature data")
yield IdCardSigner.SessionData(
{
<|code_end|>
, predict the immediate next line with the help of imports:
import binascii
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import Mock, patch
from esteid.exceptions import InvalidParameter
from esteid.idcard import IdCardSigner
from esteid.idcard import signer as signer_module
and context (classes, functions, sometimes code) from other files:
# Path: esteid/exceptions.py
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# Path: esteid/idcard/signer.py
# class IdCardSigner(Signer):
# certificate: bytes
#
# _certificate_handle: "OsCryptoCertificate"
#
# @property
# def id_code(self) -> str:
# try:
# certificate_handle = self._certificate_handle
# except AttributeError as e:
# raise AttributeError("Attribute id_code not available: certificate not provided") from e
#
# cert_holder_info = CertificateHolderInfo.from_certificate(certificate_handle)
# return cert_holder_info.id_code
#
# def setup(self, initial_data: dict = None):
# """
# Receives a user certificate from the front end
# """
# try:
# certificate_hex = initial_data["certificate"]
# except (TypeError, KeyError) as e:
# raise InvalidParameter("Missing required parameter 'certificate'", param="certificate") from e
#
# try:
# certificate = binascii.a2b_hex(certificate_hex)
# except (TypeError, ValueError) as e:
# raise InvalidParameter(
# "Failed to decode parameter `certificate` from hex-encoding", param="certificate"
# ) from e
#
# try:
# self._certificate_handle = load_certificate(certificate)
# except ValueError as e:
# raise InvalidParameter(
# "Failed to recognize `certificate` as a supported certificate format", param="certificate"
# ) from e
#
# self.certificate = certificate
#
# def prepare(self, container: pyasice.Container = None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
# xml_sig = container.prepare_signature(self.certificate)
#
# # Note: uses default digest algorithm (sha256)
# signed_digest = xml_sig.digest()
#
# self.save_session_data(digest=signed_digest, container=container, xml_sig=xml_sig)
#
# return {
# # hex-encoded digest to be consumed by the hwcrypto.js library
# "digest": binascii.b2a_hex(signed_digest).decode(),
# }
#
# def finalize(self, data: dict = None) -> pyasice.Container:
# try:
# signature_value = data["signature_value"]
# except (TypeError, KeyError) as e:
# raise InvalidParameter("Missing required parameter 'signature_value'", param="signature_value") from e
#
# try:
# signature_value = binascii.a2b_hex(signature_value)
# except (TypeError, ValueError) as e:
# raise InvalidParameter(
# "Failed to decode parameter `signature_value` from hex-encoding", param="signature_value"
# ) from e
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
# digest = self.session_data.digest
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = pyasice.XmlSignature(f.read())
#
# try:
# pyasice.verify(xml_sig.get_certificate_value(), signature_value, digest, prehashed=True)
# except pyasice.SignatureVerificationError as e:
# raise SignatureVerificationError from e
#
# container = pyasice.Container.open(temp_container_file)
#
# xml_sig.set_signature_value(signature_value)
#
# self.finalize_xml_signature(xml_sig)
#
# container.add_signature(xml_sig)
#
# return container
#
# Path: esteid/idcard/signer.py
# class IdCardSigner(Signer):
# def id_code(self) -> str:
# def setup(self, initial_data: dict = None):
# def prepare(self, container: pyasice.Container = None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> pyasice.Container:
. Output only the next line. | "digest_b64": "MTIz", |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture()
def idcardsigner():
signer = IdCardSigner({}, initial=True)
mock_container = Mock(name="mock_container")
with patch.object(signer, "open_container", return_value=mock_container), patch.object(signer, "save_session_data"):
mock_container.prepare_signature.return_value = mock_xml_sig = Mock(name="mock_xml_sig")
mock_xml_sig.digest.return_value = b"some binary digest"
yield signer
@pytest.fixture()
def idcard_session_data():
with NamedTemporaryFile("wb", delete=False) as f:
f.write(b"xml signature data")
yield IdCardSigner.SessionData(
{
"digest_b64": "MTIz",
"temp_signature_file": f.name,
"temp_container_file": "...",
<|code_end|>
with the help of current file imports:
import binascii
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import Mock, patch
from esteid.exceptions import InvalidParameter
from esteid.idcard import IdCardSigner
from esteid.idcard import signer as signer_module
and context from other files:
# Path: esteid/exceptions.py
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# Path: esteid/idcard/signer.py
# class IdCardSigner(Signer):
# certificate: bytes
#
# _certificate_handle: "OsCryptoCertificate"
#
# @property
# def id_code(self) -> str:
# try:
# certificate_handle = self._certificate_handle
# except AttributeError as e:
# raise AttributeError("Attribute id_code not available: certificate not provided") from e
#
# cert_holder_info = CertificateHolderInfo.from_certificate(certificate_handle)
# return cert_holder_info.id_code
#
# def setup(self, initial_data: dict = None):
# """
# Receives a user certificate from the front end
# """
# try:
# certificate_hex = initial_data["certificate"]
# except (TypeError, KeyError) as e:
# raise InvalidParameter("Missing required parameter 'certificate'", param="certificate") from e
#
# try:
# certificate = binascii.a2b_hex(certificate_hex)
# except (TypeError, ValueError) as e:
# raise InvalidParameter(
# "Failed to decode parameter `certificate` from hex-encoding", param="certificate"
# ) from e
#
# try:
# self._certificate_handle = load_certificate(certificate)
# except ValueError as e:
# raise InvalidParameter(
# "Failed to recognize `certificate` as a supported certificate format", param="certificate"
# ) from e
#
# self.certificate = certificate
#
# def prepare(self, container: pyasice.Container = None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
# xml_sig = container.prepare_signature(self.certificate)
#
# # Note: uses default digest algorithm (sha256)
# signed_digest = xml_sig.digest()
#
# self.save_session_data(digest=signed_digest, container=container, xml_sig=xml_sig)
#
# return {
# # hex-encoded digest to be consumed by the hwcrypto.js library
# "digest": binascii.b2a_hex(signed_digest).decode(),
# }
#
# def finalize(self, data: dict = None) -> pyasice.Container:
# try:
# signature_value = data["signature_value"]
# except (TypeError, KeyError) as e:
# raise InvalidParameter("Missing required parameter 'signature_value'", param="signature_value") from e
#
# try:
# signature_value = binascii.a2b_hex(signature_value)
# except (TypeError, ValueError) as e:
# raise InvalidParameter(
# "Failed to decode parameter `signature_value` from hex-encoding", param="signature_value"
# ) from e
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
# digest = self.session_data.digest
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = pyasice.XmlSignature(f.read())
#
# try:
# pyasice.verify(xml_sig.get_certificate_value(), signature_value, digest, prehashed=True)
# except pyasice.SignatureVerificationError as e:
# raise SignatureVerificationError from e
#
# container = pyasice.Container.open(temp_container_file)
#
# xml_sig.set_signature_value(signature_value)
#
# self.finalize_xml_signature(xml_sig)
#
# container.add_signature(xml_sig)
#
# return container
#
# Path: esteid/idcard/signer.py
# class IdCardSigner(Signer):
# def id_code(self) -> str:
# def setup(self, initial_data: dict = None):
# def prepare(self, container: pyasice.Container = None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> pyasice.Container:
, which may contain function names, class names, or code. Output only the next line. | "timestamp": int(time()), |
Predict the next line after this snippet: <|code_start|> with pytest.raises(InvalidParameter, match="Failed to decode"):
signer.setup({"certificate": b"something not hex-encoded"})
with pytest.raises(InvalidParameter, match="supported certificate format"):
signer.setup({"certificate": binascii.b2a_hex(b"this is not a certificate")})
def test_idcardsigner_prepare(idcardsigner, static_certificate):
idcardsigner.setup({"certificate": binascii.b2a_hex(static_certificate)})
result = idcardsigner.prepare(None, [])
idcardsigner.open_container.assert_called_once_with(None, [])
container = idcardsigner.open_container(...)
container.prepare_signature.assert_called_once_with(static_certificate)
xml_sig = idcardsigner.open_container().prepare_signature(...)
assert xml_sig._mock_name == "mock_xml_sig"
idcardsigner.save_session_data.assert_called_once_with(
digest=xml_sig.digest(),
container=container,
xml_sig=xml_sig,
)
assert result == {"digest": binascii.b2a_hex(xml_sig.digest()).decode()}
@patch.object(signer_module, "pyasice")
<|code_end|>
using the current file's imports:
import binascii
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import Mock, patch
from esteid.exceptions import InvalidParameter
from esteid.idcard import IdCardSigner
from esteid.idcard import signer as signer_module
and any relevant context from other files:
# Path: esteid/exceptions.py
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# Path: esteid/idcard/signer.py
# class IdCardSigner(Signer):
# certificate: bytes
#
# _certificate_handle: "OsCryptoCertificate"
#
# @property
# def id_code(self) -> str:
# try:
# certificate_handle = self._certificate_handle
# except AttributeError as e:
# raise AttributeError("Attribute id_code not available: certificate not provided") from e
#
# cert_holder_info = CertificateHolderInfo.from_certificate(certificate_handle)
# return cert_holder_info.id_code
#
# def setup(self, initial_data: dict = None):
# """
# Receives a user certificate from the front end
# """
# try:
# certificate_hex = initial_data["certificate"]
# except (TypeError, KeyError) as e:
# raise InvalidParameter("Missing required parameter 'certificate'", param="certificate") from e
#
# try:
# certificate = binascii.a2b_hex(certificate_hex)
# except (TypeError, ValueError) as e:
# raise InvalidParameter(
# "Failed to decode parameter `certificate` from hex-encoding", param="certificate"
# ) from e
#
# try:
# self._certificate_handle = load_certificate(certificate)
# except ValueError as e:
# raise InvalidParameter(
# "Failed to recognize `certificate` as a supported certificate format", param="certificate"
# ) from e
#
# self.certificate = certificate
#
# def prepare(self, container: pyasice.Container = None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
# xml_sig = container.prepare_signature(self.certificate)
#
# # Note: uses default digest algorithm (sha256)
# signed_digest = xml_sig.digest()
#
# self.save_session_data(digest=signed_digest, container=container, xml_sig=xml_sig)
#
# return {
# # hex-encoded digest to be consumed by the hwcrypto.js library
# "digest": binascii.b2a_hex(signed_digest).decode(),
# }
#
# def finalize(self, data: dict = None) -> pyasice.Container:
# try:
# signature_value = data["signature_value"]
# except (TypeError, KeyError) as e:
# raise InvalidParameter("Missing required parameter 'signature_value'", param="signature_value") from e
#
# try:
# signature_value = binascii.a2b_hex(signature_value)
# except (TypeError, ValueError) as e:
# raise InvalidParameter(
# "Failed to decode parameter `signature_value` from hex-encoding", param="signature_value"
# ) from e
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
# digest = self.session_data.digest
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = pyasice.XmlSignature(f.read())
#
# try:
# pyasice.verify(xml_sig.get_certificate_value(), signature_value, digest, prehashed=True)
# except pyasice.SignatureVerificationError as e:
# raise SignatureVerificationError from e
#
# container = pyasice.Container.open(temp_container_file)
#
# xml_sig.set_signature_value(signature_value)
#
# self.finalize_xml_signature(xml_sig)
#
# container.add_signature(xml_sig)
#
# return container
#
# Path: esteid/idcard/signer.py
# class IdCardSigner(Signer):
# def id_code(self) -> str:
# def setup(self, initial_data: dict = None):
# def prepare(self, container: pyasice.Container = None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> pyasice.Container:
. Output only the next line. | def test_idcardsigner_finalize(pyasice_mock, idcard_session_data): |
Predict the next line for this snippet: <|code_start|>
validity = cert_asn1["tbs_certificate"]["validity"].native
valid_from: datetime = validity["not_before"]
valid_to: datetime = validity["not_after"]
return cls(
issuer=issuer.human_friendly,
issuer_serial=str(serial),
subject=personal["common_name"],
valid_from=valid_from.replace(microsecond=0).astimezone(pytz.utc),
valid_to=valid_to.replace(microsecond=0).astimezone(pytz.utc),
)
@attr.s
class ResponderCertificate(Certificate):
pass
@attr.s
class Signer(FromDictMixin):
id_code = attr.ib()
# Note: This should also support common_name argument coming in
full_name = attr.ib()
certificate: Certificate = attr.ib(
validator=attr.validators.instance_of(Certificate), converter=get_instance_converter(Certificate)
)
<|code_end|>
with the help of current file imports:
from datetime import datetime
from typing import List, TYPE_CHECKING, Union
from oscrypto.asymmetric import load_certificate
from oscrypto.asymmetric import Certificate as OsCryptoCertificate
from asn1crypto.cms import Certificate as Asn1CryptoCertificate
from esteid.util import (
camel_2_py,
convert_status,
convert_time,
get_instance_converter,
get_name_from_legacy_common_name,
get_typed_list_converter,
get_typed_list_validator,
)
import attr
import pytz
import pyasice
and context from other files:
# Path: esteid/util.py
# def camel_2_py(the_dict):
# new_dict = {}
# for key, val in the_dict.items():
#
# if len(re.sub(r"([A-Z])", r" \1", key).split()) == len(key):
# parts = [key.lower()]
#
# else:
# key = key.replace("ID", "Id").replace("CRL", "Crl")
# parts = re.sub(r"([A-Z])", r" \1", key).split()
#
# new_dict["_".join([x.lower() for x in parts])] = val
#
# return new_dict
#
# def convert_status(status):
# if isinstance(status, bool):
# return status
#
# return status.lower() == "ok"
#
# def convert_time(timestamp):
# if not timestamp:
# return None
#
# if isinstance(timestamp, datetime):
# if timezone.is_naive(timestamp):
# timestamp = timezone.make_aware(timestamp, timezone.utc)
#
# return timestamp
#
# return timezone.make_aware(datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ"), timezone.utc)
#
# def get_instance_converter(cls, prepare_kwargs=camel_2_py):
# def _convert_instance(value):
# if isinstance(value, (dict, OrderedDict)):
# return cls(**prepare_kwargs(value))
#
# return value
#
# return _convert_instance
#
# def get_name_from_legacy_common_name(common_name):
# common_name = common_name.replace("\\,", ",")
# common_name = common_name.strip().rstrip(",")
#
# parts = common_name.split(",")[:-1]
# parts.reverse()
#
# return " ".join(parts).title()
#
# def get_typed_list_converter(klass):
# converter = get_instance_converter(klass)
#
# def _get_typed_list_converter(value):
# return [converter(x) for x in value]
#
# return _get_typed_list_converter
#
# def get_typed_list_validator(klass):
# def _get_typed_list_validator(inst, attr, value):
# if not isinstance(value, list):
# raise TypeError("Value MUST be a list")
#
# if not all(isinstance(x, klass) for x in value):
# raise TypeError(f"Value MUST be a list of {klass}")
#
# return _get_typed_list_validator
, which may contain function names, class names, or code. Output only the next line. | @staticmethod |
Given snippet: <|code_start|> @classmethod
def from_dict(cls, the_dict):
return cls(**camel_2_py(the_dict))
@attr.s
class CertificatePolicy(FromDictMixin):
oid = attr.ib()
url = attr.ib(default=None)
description = attr.ib(default=None)
@attr.s
class Certificate(FromDictMixin):
issuer = attr.ib()
issuer_serial = attr.ib()
subject = attr.ib()
valid_from: datetime = attr.ib(converter=convert_time)
valid_to: datetime = attr.ib(converter=convert_time)
policies = attr.ib(
default=attr.Factory(list),
validator=[
attr.validators.instance_of(list),
get_typed_list_validator(CertificatePolicy),
],
converter=get_typed_list_converter(CertificatePolicy),
)
@classmethod
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import datetime
from typing import List, TYPE_CHECKING, Union
from oscrypto.asymmetric import load_certificate
from oscrypto.asymmetric import Certificate as OsCryptoCertificate
from asn1crypto.cms import Certificate as Asn1CryptoCertificate
from esteid.util import (
camel_2_py,
convert_status,
convert_time,
get_instance_converter,
get_name_from_legacy_common_name,
get_typed_list_converter,
get_typed_list_validator,
)
import attr
import pytz
import pyasice
and context:
# Path: esteid/util.py
# def camel_2_py(the_dict):
# new_dict = {}
# for key, val in the_dict.items():
#
# if len(re.sub(r"([A-Z])", r" \1", key).split()) == len(key):
# parts = [key.lower()]
#
# else:
# key = key.replace("ID", "Id").replace("CRL", "Crl")
# parts = re.sub(r"([A-Z])", r" \1", key).split()
#
# new_dict["_".join([x.lower() for x in parts])] = val
#
# return new_dict
#
# def convert_status(status):
# if isinstance(status, bool):
# return status
#
# return status.lower() == "ok"
#
# def convert_time(timestamp):
# if not timestamp:
# return None
#
# if isinstance(timestamp, datetime):
# if timezone.is_naive(timestamp):
# timestamp = timezone.make_aware(timestamp, timezone.utc)
#
# return timestamp
#
# return timezone.make_aware(datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ"), timezone.utc)
#
# def get_instance_converter(cls, prepare_kwargs=camel_2_py):
# def _convert_instance(value):
# if isinstance(value, (dict, OrderedDict)):
# return cls(**prepare_kwargs(value))
#
# return value
#
# return _convert_instance
#
# def get_name_from_legacy_common_name(common_name):
# common_name = common_name.replace("\\,", ",")
# common_name = common_name.strip().rstrip(",")
#
# parts = common_name.split(",")[:-1]
# parts.reverse()
#
# return " ".join(parts).title()
#
# def get_typed_list_converter(klass):
# converter = get_instance_converter(klass)
#
# def _get_typed_list_converter(value):
# return [converter(x) for x in value]
#
# return _get_typed_list_converter
#
# def get_typed_list_validator(klass):
# def _get_typed_list_validator(inst, attr, value):
# if not isinstance(value, list):
# raise TypeError("Value MUST be a list")
#
# if not all(isinstance(x, klass) for x in value):
# raise TypeError(f"Value MUST be a list of {klass}")
#
# return _get_typed_list_validator
which might include code, classes, or functions. Output only the next line. | def from_certificate(cls, cert: "Union[bytes, Asn1CryptoCertificate, OsCryptoCertificate]"): |
Predict the next line after this snippet: <|code_start|> def from_dict(cls, the_dict):
return cls(**camel_2_py(the_dict))
@attr.s
class CertificatePolicy(FromDictMixin):
oid = attr.ib()
url = attr.ib(default=None)
description = attr.ib(default=None)
@attr.s
class Certificate(FromDictMixin):
issuer = attr.ib()
issuer_serial = attr.ib()
subject = attr.ib()
valid_from: datetime = attr.ib(converter=convert_time)
valid_to: datetime = attr.ib(converter=convert_time)
policies = attr.ib(
default=attr.Factory(list),
validator=[
attr.validators.instance_of(list),
get_typed_list_validator(CertificatePolicy),
],
converter=get_typed_list_converter(CertificatePolicy),
)
@classmethod
def from_certificate(cls, cert: "Union[bytes, Asn1CryptoCertificate, OsCryptoCertificate]"):
<|code_end|>
using the current file's imports:
from datetime import datetime
from typing import List, TYPE_CHECKING, Union
from oscrypto.asymmetric import load_certificate
from oscrypto.asymmetric import Certificate as OsCryptoCertificate
from asn1crypto.cms import Certificate as Asn1CryptoCertificate
from esteid.util import (
camel_2_py,
convert_status,
convert_time,
get_instance_converter,
get_name_from_legacy_common_name,
get_typed_list_converter,
get_typed_list_validator,
)
import attr
import pytz
import pyasice
and any relevant context from other files:
# Path: esteid/util.py
# def camel_2_py(the_dict):
# new_dict = {}
# for key, val in the_dict.items():
#
# if len(re.sub(r"([A-Z])", r" \1", key).split()) == len(key):
# parts = [key.lower()]
#
# else:
# key = key.replace("ID", "Id").replace("CRL", "Crl")
# parts = re.sub(r"([A-Z])", r" \1", key).split()
#
# new_dict["_".join([x.lower() for x in parts])] = val
#
# return new_dict
#
# def convert_status(status):
# if isinstance(status, bool):
# return status
#
# return status.lower() == "ok"
#
# def convert_time(timestamp):
# if not timestamp:
# return None
#
# if isinstance(timestamp, datetime):
# if timezone.is_naive(timestamp):
# timestamp = timezone.make_aware(timestamp, timezone.utc)
#
# return timestamp
#
# return timezone.make_aware(datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ"), timezone.utc)
#
# def get_instance_converter(cls, prepare_kwargs=camel_2_py):
# def _convert_instance(value):
# if isinstance(value, (dict, OrderedDict)):
# return cls(**prepare_kwargs(value))
#
# return value
#
# return _convert_instance
#
# def get_name_from_legacy_common_name(common_name):
# common_name = common_name.replace("\\,", ",")
# common_name = common_name.strip().rstrip(",")
#
# parts = common_name.split(",")[:-1]
# parts.reverse()
#
# return " ".join(parts).title()
#
# def get_typed_list_converter(klass):
# converter = get_instance_converter(klass)
#
# def _get_typed_list_converter(value):
# return [converter(x) for x in value]
#
# return _get_typed_list_converter
#
# def get_typed_list_validator(klass):
# def _get_typed_list_validator(inst, attr, value):
# if not isinstance(value, list):
# raise TypeError("Value MUST be a list")
#
# if not all(isinstance(x, klass) for x in value):
# raise TypeError(f"Value MUST be a list of {klass}")
#
# return _get_typed_list_validator
. Output only the next line. | if isinstance(cert, bytes): |
Next line prediction: <|code_start|>
if TYPE_CHECKING:
class FromDictMixin(object):
@classmethod
<|code_end|>
. Use current file imports:
(from datetime import datetime
from typing import List, TYPE_CHECKING, Union
from oscrypto.asymmetric import load_certificate
from oscrypto.asymmetric import Certificate as OsCryptoCertificate
from asn1crypto.cms import Certificate as Asn1CryptoCertificate
from esteid.util import (
camel_2_py,
convert_status,
convert_time,
get_instance_converter,
get_name_from_legacy_common_name,
get_typed_list_converter,
get_typed_list_validator,
)
import attr
import pytz
import pyasice)
and context including class names, function names, or small code snippets from other files:
# Path: esteid/util.py
# def camel_2_py(the_dict):
# new_dict = {}
# for key, val in the_dict.items():
#
# if len(re.sub(r"([A-Z])", r" \1", key).split()) == len(key):
# parts = [key.lower()]
#
# else:
# key = key.replace("ID", "Id").replace("CRL", "Crl")
# parts = re.sub(r"([A-Z])", r" \1", key).split()
#
# new_dict["_".join([x.lower() for x in parts])] = val
#
# return new_dict
#
# def convert_status(status):
# if isinstance(status, bool):
# return status
#
# return status.lower() == "ok"
#
# def convert_time(timestamp):
# if not timestamp:
# return None
#
# if isinstance(timestamp, datetime):
# if timezone.is_naive(timestamp):
# timestamp = timezone.make_aware(timestamp, timezone.utc)
#
# return timestamp
#
# return timezone.make_aware(datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ"), timezone.utc)
#
# def get_instance_converter(cls, prepare_kwargs=camel_2_py):
# def _convert_instance(value):
# if isinstance(value, (dict, OrderedDict)):
# return cls(**prepare_kwargs(value))
#
# return value
#
# return _convert_instance
#
# def get_name_from_legacy_common_name(common_name):
# common_name = common_name.replace("\\,", ",")
# common_name = common_name.strip().rstrip(",")
#
# parts = common_name.split(",")[:-1]
# parts.reverse()
#
# return " ".join(parts).title()
#
# def get_typed_list_converter(klass):
# converter = get_instance_converter(klass)
#
# def _get_typed_list_converter(value):
# return [converter(x) for x in value]
#
# return _get_typed_list_converter
#
# def get_typed_list_validator(klass):
# def _get_typed_list_validator(inst, attr, value):
# if not isinstance(value, list):
# raise TypeError("Value MUST be a list")
#
# if not all(isinstance(x, klass) for x in value):
# raise TypeError(f"Value MUST be a list of {klass}")
#
# return _get_typed_list_validator
. Output only the next line. | def from_dict(cls, the_dict): |
Given the code snippet: <|code_start|> )
@classmethod
def from_certificate(cls, cert: "Union[bytes, Asn1CryptoCertificate, OsCryptoCertificate]"):
if isinstance(cert, bytes):
cert = load_certificate(cert)
cert_asn1: "Asn1CryptoCertificate" = getattr(cert, "asn1", cert)
personal = cert_asn1.subject.native
issuer = cert_asn1["tbs_certificate"]["issuer"]
serial = cert_asn1["tbs_certificate"]["serial_number"].native
validity = cert_asn1["tbs_certificate"]["validity"].native
valid_from: datetime = validity["not_before"]
valid_to: datetime = validity["not_after"]
return cls(
issuer=issuer.human_friendly,
issuer_serial=str(serial),
subject=personal["common_name"],
valid_from=valid_from.replace(microsecond=0).astimezone(pytz.utc),
valid_to=valid_to.replace(microsecond=0).astimezone(pytz.utc),
)
@attr.s
class ResponderCertificate(Certificate):
pass
@attr.s
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from typing import List, TYPE_CHECKING, Union
from oscrypto.asymmetric import load_certificate
from oscrypto.asymmetric import Certificate as OsCryptoCertificate
from asn1crypto.cms import Certificate as Asn1CryptoCertificate
from esteid.util import (
camel_2_py,
convert_status,
convert_time,
get_instance_converter,
get_name_from_legacy_common_name,
get_typed_list_converter,
get_typed_list_validator,
)
import attr
import pytz
import pyasice
and context (functions, classes, or occasionally code) from other files:
# Path: esteid/util.py
# def camel_2_py(the_dict):
# new_dict = {}
# for key, val in the_dict.items():
#
# if len(re.sub(r"([A-Z])", r" \1", key).split()) == len(key):
# parts = [key.lower()]
#
# else:
# key = key.replace("ID", "Id").replace("CRL", "Crl")
# parts = re.sub(r"([A-Z])", r" \1", key).split()
#
# new_dict["_".join([x.lower() for x in parts])] = val
#
# return new_dict
#
# def convert_status(status):
# if isinstance(status, bool):
# return status
#
# return status.lower() == "ok"
#
# def convert_time(timestamp):
# if not timestamp:
# return None
#
# if isinstance(timestamp, datetime):
# if timezone.is_naive(timestamp):
# timestamp = timezone.make_aware(timestamp, timezone.utc)
#
# return timestamp
#
# return timezone.make_aware(datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ"), timezone.utc)
#
# def get_instance_converter(cls, prepare_kwargs=camel_2_py):
# def _convert_instance(value):
# if isinstance(value, (dict, OrderedDict)):
# return cls(**prepare_kwargs(value))
#
# return value
#
# return _convert_instance
#
# def get_name_from_legacy_common_name(common_name):
# common_name = common_name.replace("\\,", ",")
# common_name = common_name.strip().rstrip(",")
#
# parts = common_name.split(",")[:-1]
# parts.reverse()
#
# return " ".join(parts).title()
#
# def get_typed_list_converter(klass):
# converter = get_instance_converter(klass)
#
# def _get_typed_list_converter(value):
# return [converter(x) for x in value]
#
# return _get_typed_list_converter
#
# def get_typed_list_validator(klass):
# def _get_typed_list_validator(inst, attr, value):
# if not isinstance(value, list):
# raise TypeError("Value MUST be a list")
#
# if not all(isinstance(x, klass) for x in value):
# raise TypeError(f"Value MUST be a list of {klass}")
#
# return _get_typed_list_validator
. Output only the next line. | class Signer(FromDictMixin): |
Here is a snippet: <|code_start|>
validity = cert_asn1["tbs_certificate"]["validity"].native
valid_from: datetime = validity["not_before"]
valid_to: datetime = validity["not_after"]
return cls(
issuer=issuer.human_friendly,
issuer_serial=str(serial),
subject=personal["common_name"],
valid_from=valid_from.replace(microsecond=0).astimezone(pytz.utc),
valid_to=valid_to.replace(microsecond=0).astimezone(pytz.utc),
)
@attr.s
class ResponderCertificate(Certificate):
pass
@attr.s
class Signer(FromDictMixin):
id_code = attr.ib()
# Note: This should also support common_name argument coming in
full_name = attr.ib()
certificate: Certificate = attr.ib(
validator=attr.validators.instance_of(Certificate), converter=get_instance_converter(Certificate)
)
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from typing import List, TYPE_CHECKING, Union
from oscrypto.asymmetric import load_certificate
from oscrypto.asymmetric import Certificate as OsCryptoCertificate
from asn1crypto.cms import Certificate as Asn1CryptoCertificate
from esteid.util import (
camel_2_py,
convert_status,
convert_time,
get_instance_converter,
get_name_from_legacy_common_name,
get_typed_list_converter,
get_typed_list_validator,
)
import attr
import pytz
import pyasice
and context from other files:
# Path: esteid/util.py
# def camel_2_py(the_dict):
# new_dict = {}
# for key, val in the_dict.items():
#
# if len(re.sub(r"([A-Z])", r" \1", key).split()) == len(key):
# parts = [key.lower()]
#
# else:
# key = key.replace("ID", "Id").replace("CRL", "Crl")
# parts = re.sub(r"([A-Z])", r" \1", key).split()
#
# new_dict["_".join([x.lower() for x in parts])] = val
#
# return new_dict
#
# def convert_status(status):
# if isinstance(status, bool):
# return status
#
# return status.lower() == "ok"
#
# def convert_time(timestamp):
# if not timestamp:
# return None
#
# if isinstance(timestamp, datetime):
# if timezone.is_naive(timestamp):
# timestamp = timezone.make_aware(timestamp, timezone.utc)
#
# return timestamp
#
# return timezone.make_aware(datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ"), timezone.utc)
#
# def get_instance_converter(cls, prepare_kwargs=camel_2_py):
# def _convert_instance(value):
# if isinstance(value, (dict, OrderedDict)):
# return cls(**prepare_kwargs(value))
#
# return value
#
# return _convert_instance
#
# def get_name_from_legacy_common_name(common_name):
# common_name = common_name.replace("\\,", ",")
# common_name = common_name.strip().rstrip(",")
#
# parts = common_name.split(",")[:-1]
# parts.reverse()
#
# return " ".join(parts).title()
#
# def get_typed_list_converter(klass):
# converter = get_instance_converter(klass)
#
# def _get_typed_list_converter(value):
# return [converter(x) for x in value]
#
# return _get_typed_list_converter
#
# def get_typed_list_validator(klass):
# def _get_typed_list_validator(inst, attr, value):
# if not isinstance(value, list):
# raise TypeError("Value MUST be a list")
#
# if not all(isinstance(x, klass) for x in value):
# raise TypeError(f"Value MUST be a list of {klass}")
#
# return _get_typed_list_validator
, which may include functions, classes, or code. Output only the next line. | @staticmethod |
Continue the code snippet: <|code_start|>
sign_session = service.sign(...)
mobileidsigner.save_session_data.assert_called_once_with(
digest=sign_session.digest,
container=container,
xml_sig=xml_sig,
session_id=sign_session.session_id,
)
assert result["verification_code"] == sign_session.verification_code
@patch.object(signer_module, "Container")
@patch.object(signer_module, "XmlSignature")
def test_mobileidsigner_finalize(
XmlSignatureMock, ContainerMock, MID_DEMO_PHONE_EE_OK, MID_DEMO_PIN_EE_OK, mobileidservice, mobileid_session_data
):
mobileidsigner = MobileIdSigner({MobileIdSigner._SESSION_KEY: mobileid_session_data})
with patch.object(mobileidsigner, "finalize_xml_signature"):
result = mobileidsigner.finalize()
XmlSignatureMock.assert_called_once_with(b"xml signature data")
mobileidsigner.finalize_xml_signature.assert_called_once_with(XmlSignatureMock())
xml_sig = XmlSignatureMock(...)
service = mobileidservice.get_instance()
service.sign_status.assert_called_once_with(
<|code_end|>
. Use current file imports:
import base64
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import patch
from esteid.mobileid import MobileIdSigner
from esteid.mobileid import signer as signer_module
from ...exceptions import InvalidIdCode, InvalidParameter, InvalidParameters, SigningSessionDoesNotExist
and context (classes, functions, or code) from other files:
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# phone_number: str
# id_code: str
# language: str
#
# SessionData = MobileIdSessionData
# session_data: MobileIdSessionData
#
# def setup(self, initial_data: dict = None):
# """
# Receives user input via POST: `id_code`, `phone_number`, `language`
# """
# if not isinstance(initial_data, dict):
# raise InvalidParameters("Missing required parameters")
#
# user_input = UserInput(**initial_data)
#
# try:
# user_input.is_valid()
# except (InvalidIdCode, InvalidParameter):
# # Just to be explicit
# raise
# except ValueError as e:
# raise InvalidParameters("Invalid parameters") from e
#
# self.id_code = user_input.id_code
# self.phone_number = user_input.phone_number
# self.language = user_input.language
#
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
#
# service = TranslatedMobileIDService.get_instance()
#
# certificate = service.get_certificate(self.id_code, self.phone_number)
#
# xml_sig = container.prepare_signature(certificate)
#
# sign_session = service.sign(self.id_code, self.phone_number, xml_sig.signed_data(), language=self.language)
#
# self.save_session_data(
# digest=sign_session.digest,
# container=container,
# xml_sig=xml_sig,
# session_id=sign_session.session_id,
# )
#
# return {
# "verification_code": sign_session.verification_code,
# }
#
# def finalize(self, data: dict = None) -> Container:
# digest = self.session_data.digest
# session_id = self.session_data.session_id
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = XmlSignature(f.read())
#
# service = TranslatedMobileIDService.get_instance()
#
# try:
# status = service.sign_status(session_id, xml_sig.get_certificate_value(), digest)
# except ActionInProgress:
# # Just to be explicit about the InProgress status
# raise
#
# xml_sig.set_signature_value(status.signature)
#
# self.finalize_xml_signature(xml_sig)
#
# container = Container.open(temp_container_file)
# container.add_signature(xml_sig)
#
# return container
#
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
# data_obj = self.session_data
# data_obj.session_id = session_id
#
# super().save_session_data(digest=digest, container=container, xml_sig=xml_sig)
#
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# def setup(self, initial_data: dict = None):
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> Container:
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
#
# Path: esteid/exceptions.py
# class InvalidIdCode(InvalidParameter):
# """Invalid ID code (format or checksum don't match)"""
#
# default_message = _("Invalid ID code.")
#
# def __init__(self, message=None, *, param="id_code", **kwargs):
# super().__init__(message, param=param, **kwargs)
#
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
#
# class SigningSessionDoesNotExist(SigningSessionError):
# """A signing session does not exist while expected to exist"""
#
# default_message = _("No signing session found.")
. Output only the next line. | mobileid_session_data["session_id"], |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize(
"data,error",
[
pytest.param(
None,
InvalidParameters,
id="No data",
),
pytest.param(
{},
InvalidParameters,
id="Empty data",
),
pytest.param(
{"id_code": "asdf", "phone_number": "asdf"},
InvalidParameter,
id="Invalid Phone",
),
pytest.param(
{"id_code": "asdf", "phone_number": "+37200000766"},
InvalidIdCode,
id="Invalid ID Code",
),
pytest.param(
{"id_code": "60001019906", "phone_number": "+37200000766"},
None,
id="ID Code and Phone OK",
),
<|code_end|>
, generate the next line using the imports in this file:
import base64
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import patch
from esteid.mobileid import MobileIdSigner
from esteid.mobileid import signer as signer_module
from ...exceptions import InvalidIdCode, InvalidParameter, InvalidParameters, SigningSessionDoesNotExist
and context (functions, classes, or occasionally code) from other files:
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# phone_number: str
# id_code: str
# language: str
#
# SessionData = MobileIdSessionData
# session_data: MobileIdSessionData
#
# def setup(self, initial_data: dict = None):
# """
# Receives user input via POST: `id_code`, `phone_number`, `language`
# """
# if not isinstance(initial_data, dict):
# raise InvalidParameters("Missing required parameters")
#
# user_input = UserInput(**initial_data)
#
# try:
# user_input.is_valid()
# except (InvalidIdCode, InvalidParameter):
# # Just to be explicit
# raise
# except ValueError as e:
# raise InvalidParameters("Invalid parameters") from e
#
# self.id_code = user_input.id_code
# self.phone_number = user_input.phone_number
# self.language = user_input.language
#
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
#
# service = TranslatedMobileIDService.get_instance()
#
# certificate = service.get_certificate(self.id_code, self.phone_number)
#
# xml_sig = container.prepare_signature(certificate)
#
# sign_session = service.sign(self.id_code, self.phone_number, xml_sig.signed_data(), language=self.language)
#
# self.save_session_data(
# digest=sign_session.digest,
# container=container,
# xml_sig=xml_sig,
# session_id=sign_session.session_id,
# )
#
# return {
# "verification_code": sign_session.verification_code,
# }
#
# def finalize(self, data: dict = None) -> Container:
# digest = self.session_data.digest
# session_id = self.session_data.session_id
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = XmlSignature(f.read())
#
# service = TranslatedMobileIDService.get_instance()
#
# try:
# status = service.sign_status(session_id, xml_sig.get_certificate_value(), digest)
# except ActionInProgress:
# # Just to be explicit about the InProgress status
# raise
#
# xml_sig.set_signature_value(status.signature)
#
# self.finalize_xml_signature(xml_sig)
#
# container = Container.open(temp_container_file)
# container.add_signature(xml_sig)
#
# return container
#
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
# data_obj = self.session_data
# data_obj.session_id = session_id
#
# super().save_session_data(digest=digest, container=container, xml_sig=xml_sig)
#
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# def setup(self, initial_data: dict = None):
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> Container:
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
#
# Path: esteid/exceptions.py
# class InvalidIdCode(InvalidParameter):
# """Invalid ID code (format or checksum don't match)"""
#
# default_message = _("Invalid ID code.")
#
# def __init__(self, message=None, *, param="id_code", **kwargs):
# super().__init__(message, param=param, **kwargs)
#
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
#
# class SigningSessionDoesNotExist(SigningSessionError):
# """A signing session does not exist while expected to exist"""
#
# default_message = _("No signing session found.")
. Output only the next line. | pytest.param( |
Given the following code snippet before the placeholder: <|code_start|> InvalidParameters,
id="No data",
),
pytest.param(
{},
InvalidParameters,
id="Empty data",
),
pytest.param(
{"id_code": "asdf", "phone_number": "asdf"},
InvalidParameter,
id="Invalid Phone",
),
pytest.param(
{"id_code": "asdf", "phone_number": "+37200000766"},
InvalidIdCode,
id="Invalid ID Code",
),
pytest.param(
{"id_code": "60001019906", "phone_number": "+37200000766"},
None,
id="ID Code and Phone OK",
),
pytest.param(
{"id_code": "60001019906", "phone_number": "+37200000766", "language": "EST"},
None,
id="ID Code and Phone OK",
),
],
)
<|code_end|>
, predict the next line using imports from the current file:
import base64
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import patch
from esteid.mobileid import MobileIdSigner
from esteid.mobileid import signer as signer_module
from ...exceptions import InvalidIdCode, InvalidParameter, InvalidParameters, SigningSessionDoesNotExist
and context including class names, function names, and sometimes code from other files:
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# phone_number: str
# id_code: str
# language: str
#
# SessionData = MobileIdSessionData
# session_data: MobileIdSessionData
#
# def setup(self, initial_data: dict = None):
# """
# Receives user input via POST: `id_code`, `phone_number`, `language`
# """
# if not isinstance(initial_data, dict):
# raise InvalidParameters("Missing required parameters")
#
# user_input = UserInput(**initial_data)
#
# try:
# user_input.is_valid()
# except (InvalidIdCode, InvalidParameter):
# # Just to be explicit
# raise
# except ValueError as e:
# raise InvalidParameters("Invalid parameters") from e
#
# self.id_code = user_input.id_code
# self.phone_number = user_input.phone_number
# self.language = user_input.language
#
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
#
# service = TranslatedMobileIDService.get_instance()
#
# certificate = service.get_certificate(self.id_code, self.phone_number)
#
# xml_sig = container.prepare_signature(certificate)
#
# sign_session = service.sign(self.id_code, self.phone_number, xml_sig.signed_data(), language=self.language)
#
# self.save_session_data(
# digest=sign_session.digest,
# container=container,
# xml_sig=xml_sig,
# session_id=sign_session.session_id,
# )
#
# return {
# "verification_code": sign_session.verification_code,
# }
#
# def finalize(self, data: dict = None) -> Container:
# digest = self.session_data.digest
# session_id = self.session_data.session_id
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = XmlSignature(f.read())
#
# service = TranslatedMobileIDService.get_instance()
#
# try:
# status = service.sign_status(session_id, xml_sig.get_certificate_value(), digest)
# except ActionInProgress:
# # Just to be explicit about the InProgress status
# raise
#
# xml_sig.set_signature_value(status.signature)
#
# self.finalize_xml_signature(xml_sig)
#
# container = Container.open(temp_container_file)
# container.add_signature(xml_sig)
#
# return container
#
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
# data_obj = self.session_data
# data_obj.session_id = session_id
#
# super().save_session_data(digest=digest, container=container, xml_sig=xml_sig)
#
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# def setup(self, initial_data: dict = None):
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> Container:
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
#
# Path: esteid/exceptions.py
# class InvalidIdCode(InvalidParameter):
# """Invalid ID code (format or checksum don't match)"""
#
# default_message = _("Invalid ID code.")
#
# def __init__(self, message=None, *, param="id_code", **kwargs):
# super().__init__(message, param=param, **kwargs)
#
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
#
# class SigningSessionDoesNotExist(SigningSessionError):
# """A signing session does not exist while expected to exist"""
#
# default_message = _("No signing session found.")
. Output only the next line. | def test_mobileidsigner_setup(data, error): |
Continue the code snippet: <|code_start|> id="Empty data",
),
pytest.param(
{"id_code": "asdf", "phone_number": "asdf"},
InvalidParameter,
id="Invalid Phone",
),
pytest.param(
{"id_code": "asdf", "phone_number": "+37200000766"},
InvalidIdCode,
id="Invalid ID Code",
),
pytest.param(
{"id_code": "60001019906", "phone_number": "+37200000766"},
None,
id="ID Code and Phone OK",
),
pytest.param(
{"id_code": "60001019906", "phone_number": "+37200000766", "language": "EST"},
None,
id="ID Code and Phone OK",
),
],
)
def test_mobileidsigner_setup(data, error):
signer = MobileIdSigner({}, initial=True)
if error:
with pytest.raises(error):
signer.setup(data)
else:
<|code_end|>
. Use current file imports:
import base64
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import patch
from esteid.mobileid import MobileIdSigner
from esteid.mobileid import signer as signer_module
from ...exceptions import InvalidIdCode, InvalidParameter, InvalidParameters, SigningSessionDoesNotExist
and context (classes, functions, or code) from other files:
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# phone_number: str
# id_code: str
# language: str
#
# SessionData = MobileIdSessionData
# session_data: MobileIdSessionData
#
# def setup(self, initial_data: dict = None):
# """
# Receives user input via POST: `id_code`, `phone_number`, `language`
# """
# if not isinstance(initial_data, dict):
# raise InvalidParameters("Missing required parameters")
#
# user_input = UserInput(**initial_data)
#
# try:
# user_input.is_valid()
# except (InvalidIdCode, InvalidParameter):
# # Just to be explicit
# raise
# except ValueError as e:
# raise InvalidParameters("Invalid parameters") from e
#
# self.id_code = user_input.id_code
# self.phone_number = user_input.phone_number
# self.language = user_input.language
#
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
#
# service = TranslatedMobileIDService.get_instance()
#
# certificate = service.get_certificate(self.id_code, self.phone_number)
#
# xml_sig = container.prepare_signature(certificate)
#
# sign_session = service.sign(self.id_code, self.phone_number, xml_sig.signed_data(), language=self.language)
#
# self.save_session_data(
# digest=sign_session.digest,
# container=container,
# xml_sig=xml_sig,
# session_id=sign_session.session_id,
# )
#
# return {
# "verification_code": sign_session.verification_code,
# }
#
# def finalize(self, data: dict = None) -> Container:
# digest = self.session_data.digest
# session_id = self.session_data.session_id
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = XmlSignature(f.read())
#
# service = TranslatedMobileIDService.get_instance()
#
# try:
# status = service.sign_status(session_id, xml_sig.get_certificate_value(), digest)
# except ActionInProgress:
# # Just to be explicit about the InProgress status
# raise
#
# xml_sig.set_signature_value(status.signature)
#
# self.finalize_xml_signature(xml_sig)
#
# container = Container.open(temp_container_file)
# container.add_signature(xml_sig)
#
# return container
#
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
# data_obj = self.session_data
# data_obj.session_id = session_id
#
# super().save_session_data(digest=digest, container=container, xml_sig=xml_sig)
#
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# def setup(self, initial_data: dict = None):
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> Container:
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
#
# Path: esteid/exceptions.py
# class InvalidIdCode(InvalidParameter):
# """Invalid ID code (format or checksum don't match)"""
#
# default_message = _("Invalid ID code.")
#
# def __init__(self, message=None, *, param="id_code", **kwargs):
# super().__init__(message, param=param, **kwargs)
#
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
#
# class SigningSessionDoesNotExist(SigningSessionError):
# """A signing session does not exist while expected to exist"""
#
# default_message = _("No signing session found.")
. Output only the next line. | signer.setup(data) |
Next line prediction: <|code_start|>def test_mobileidsigner_prepare(mobileidsigner, MID_DEMO_PHONE_EE_OK, MID_DEMO_PIN_EE_OK, mobileidservice):
mobileidsigner.setup({"id_code": MID_DEMO_PIN_EE_OK, "phone_number": MID_DEMO_PHONE_EE_OK})
result = mobileidsigner.prepare(None, [])
mobileidsigner.open_container.assert_called_once_with(None, [])
container = mobileidsigner.open_container(...)
mobileidservice.get_instance.assert_called_once()
service = mobileidservice.get_instance()
service.get_certificate.assert_called_once_with(MID_DEMO_PIN_EE_OK, MID_DEMO_PHONE_EE_OK)
cert = service.get_certificate(...)
container.prepare_signature.assert_called_once_with(cert)
xml_sig = mobileidsigner.open_container().prepare_signature(...)
xml_sig.signed_data.assert_called_once()
service.sign.assert_called_once_with(
MID_DEMO_PIN_EE_OK, MID_DEMO_PHONE_EE_OK, xml_sig.signed_data(), language=mobileidsigner.language
)
sign_session = service.sign(...)
mobileidsigner.save_session_data.assert_called_once_with(
digest=sign_session.digest,
container=container,
xml_sig=xml_sig,
<|code_end|>
. Use current file imports:
(import base64
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import patch
from esteid.mobileid import MobileIdSigner
from esteid.mobileid import signer as signer_module
from ...exceptions import InvalidIdCode, InvalidParameter, InvalidParameters, SigningSessionDoesNotExist)
and context including class names, function names, or small code snippets from other files:
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# phone_number: str
# id_code: str
# language: str
#
# SessionData = MobileIdSessionData
# session_data: MobileIdSessionData
#
# def setup(self, initial_data: dict = None):
# """
# Receives user input via POST: `id_code`, `phone_number`, `language`
# """
# if not isinstance(initial_data, dict):
# raise InvalidParameters("Missing required parameters")
#
# user_input = UserInput(**initial_data)
#
# try:
# user_input.is_valid()
# except (InvalidIdCode, InvalidParameter):
# # Just to be explicit
# raise
# except ValueError as e:
# raise InvalidParameters("Invalid parameters") from e
#
# self.id_code = user_input.id_code
# self.phone_number = user_input.phone_number
# self.language = user_input.language
#
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
#
# service = TranslatedMobileIDService.get_instance()
#
# certificate = service.get_certificate(self.id_code, self.phone_number)
#
# xml_sig = container.prepare_signature(certificate)
#
# sign_session = service.sign(self.id_code, self.phone_number, xml_sig.signed_data(), language=self.language)
#
# self.save_session_data(
# digest=sign_session.digest,
# container=container,
# xml_sig=xml_sig,
# session_id=sign_session.session_id,
# )
#
# return {
# "verification_code": sign_session.verification_code,
# }
#
# def finalize(self, data: dict = None) -> Container:
# digest = self.session_data.digest
# session_id = self.session_data.session_id
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = XmlSignature(f.read())
#
# service = TranslatedMobileIDService.get_instance()
#
# try:
# status = service.sign_status(session_id, xml_sig.get_certificate_value(), digest)
# except ActionInProgress:
# # Just to be explicit about the InProgress status
# raise
#
# xml_sig.set_signature_value(status.signature)
#
# self.finalize_xml_signature(xml_sig)
#
# container = Container.open(temp_container_file)
# container.add_signature(xml_sig)
#
# return container
#
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
# data_obj = self.session_data
# data_obj.session_id = session_id
#
# super().save_session_data(digest=digest, container=container, xml_sig=xml_sig)
#
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# def setup(self, initial_data: dict = None):
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> Container:
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
#
# Path: esteid/exceptions.py
# class InvalidIdCode(InvalidParameter):
# """Invalid ID code (format or checksum don't match)"""
#
# default_message = _("Invalid ID code.")
#
# def __init__(self, message=None, *, param="id_code", **kwargs):
# super().__init__(message, param=param, **kwargs)
#
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
#
# class SigningSessionDoesNotExist(SigningSessionError):
# """A signing session does not exist while expected to exist"""
#
# default_message = _("No signing session found.")
. Output only the next line. | session_id=sign_session.session_id, |
Predict the next line for this snippet: <|code_start|> session_id=sign_session.session_id,
)
assert result["verification_code"] == sign_session.verification_code
@patch.object(signer_module, "Container")
@patch.object(signer_module, "XmlSignature")
def test_mobileidsigner_finalize(
XmlSignatureMock, ContainerMock, MID_DEMO_PHONE_EE_OK, MID_DEMO_PIN_EE_OK, mobileidservice, mobileid_session_data
):
mobileidsigner = MobileIdSigner({MobileIdSigner._SESSION_KEY: mobileid_session_data})
with patch.object(mobileidsigner, "finalize_xml_signature"):
result = mobileidsigner.finalize()
XmlSignatureMock.assert_called_once_with(b"xml signature data")
mobileidsigner.finalize_xml_signature.assert_called_once_with(XmlSignatureMock())
xml_sig = XmlSignatureMock(...)
service = mobileidservice.get_instance()
service.sign_status.assert_called_once_with(
mobileid_session_data["session_id"],
xml_sig.get_certificate_value(),
base64.b64decode(mobileid_session_data["digest_b64"]),
)
sign_status = service.sign_status(...)
xml_sig.set_signature_value.assert_called_once_with(sign_status.signature)
<|code_end|>
with the help of current file imports:
import base64
import os
import pytest
from tempfile import NamedTemporaryFile
from time import time
from unittest.mock import patch
from esteid.mobileid import MobileIdSigner
from esteid.mobileid import signer as signer_module
from ...exceptions import InvalidIdCode, InvalidParameter, InvalidParameters, SigningSessionDoesNotExist
and context from other files:
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# phone_number: str
# id_code: str
# language: str
#
# SessionData = MobileIdSessionData
# session_data: MobileIdSessionData
#
# def setup(self, initial_data: dict = None):
# """
# Receives user input via POST: `id_code`, `phone_number`, `language`
# """
# if not isinstance(initial_data, dict):
# raise InvalidParameters("Missing required parameters")
#
# user_input = UserInput(**initial_data)
#
# try:
# user_input.is_valid()
# except (InvalidIdCode, InvalidParameter):
# # Just to be explicit
# raise
# except ValueError as e:
# raise InvalidParameters("Invalid parameters") from e
#
# self.id_code = user_input.id_code
# self.phone_number = user_input.phone_number
# self.language = user_input.language
#
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# container = self.open_container(container, files)
#
# service = TranslatedMobileIDService.get_instance()
#
# certificate = service.get_certificate(self.id_code, self.phone_number)
#
# xml_sig = container.prepare_signature(certificate)
#
# sign_session = service.sign(self.id_code, self.phone_number, xml_sig.signed_data(), language=self.language)
#
# self.save_session_data(
# digest=sign_session.digest,
# container=container,
# xml_sig=xml_sig,
# session_id=sign_session.session_id,
# )
#
# return {
# "verification_code": sign_session.verification_code,
# }
#
# def finalize(self, data: dict = None) -> Container:
# digest = self.session_data.digest
# session_id = self.session_data.session_id
#
# temp_signature_file = self.session_data.temp_signature_file
# temp_container_file = self.session_data.temp_container_file
#
# with open(temp_signature_file, "rb") as f:
# xml_sig = XmlSignature(f.read())
#
# service = TranslatedMobileIDService.get_instance()
#
# try:
# status = service.sign_status(session_id, xml_sig.get_certificate_value(), digest)
# except ActionInProgress:
# # Just to be explicit about the InProgress status
# raise
#
# xml_sig.set_signature_value(status.signature)
#
# self.finalize_xml_signature(xml_sig)
#
# container = Container.open(temp_container_file)
# container.add_signature(xml_sig)
#
# return container
#
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
# data_obj = self.session_data
# data_obj.session_id = session_id
#
# super().save_session_data(digest=digest, container=container, xml_sig=xml_sig)
#
# Path: esteid/mobileid/signer.py
# class MobileIdSigner(Signer):
# def setup(self, initial_data: dict = None):
# def prepare(self, container=None, files: List[DataFile] = None) -> dict:
# def finalize(self, data: dict = None) -> Container:
# def save_session_data(self, *, digest: bytes, container: Container, xml_sig: XmlSignature, session_id: str):
#
# Path: esteid/exceptions.py
# class InvalidIdCode(InvalidParameter):
# """Invalid ID code (format or checksum don't match)"""
#
# default_message = _("Invalid ID code.")
#
# def __init__(self, message=None, *, param="id_code", **kwargs):
# super().__init__(message, param=param, **kwargs)
#
# class InvalidParameter(InvalidParameters):
# """Invalid initialization parameter PARAM received from the request.
#
# Takes a `param` kwarg
# """
#
# default_message = _("Invalid value for parameter {param}.")
#
# def __init__(self, message=None, *, param, **kwargs):
# super().__init__(message)
# self.kwargs = {**kwargs, "param": param}
#
# class InvalidParameters(EsteidError):
# """Invalid initialization parameters received from the request."""
#
# status = HTTPStatus.BAD_REQUEST
#
# default_message = _("Invalid parameters.")
#
# class SigningSessionDoesNotExist(SigningSessionError):
# """A signing session does not exist while expected to exist"""
#
# default_message = _("No signing session found.")
, which may contain function names, class names, or code. Output only the next line. | ContainerMock.open.assert_called_once_with(mobileid_session_data["temp_container_file"]) |
Based on the snippet: <|code_start|>
TEST_TXT = "test.txt"
TEST_TXT_CONTENT = b"Hello"
@pytest.fixture()
def test_txt(tmp_path):
# Can't pass fixtures to parametrize() so we need a well-known file name for a parameterized test.
# tmp_path is pytest's builtin fixture with a temporary path as a pathlib.Path object
with open(tmp_path / TEST_TXT, "wb") as f:
<|code_end|>
, predict the immediate next line with the help of imports:
import base64
import pathlib
import pytest
from django.core.files import File
from ..types import DataFile, InterimSessionData
and context (classes, functions, sometimes code) from other files:
# Path: esteid/signing/types.py
# class DataFile:
# """
# Interface for file objects that are added to signed containers.
#
# Constructor accepts a path to file (a string or a pathlib *Path) or a django File.
#
# Additional arguments include:
# - `mime_type`, defaults to "application/octet-stream";
# - `content` if for any reason the wrapped file's content should be ignored (it won't be read in this case);
# - `file_name`: a custom (base)name of the file as it would appear in the container.
#
# The container cares about 3 attributes:
# * file name (base name only)
# - taken from
# * mime type
# * the content, for calculating hash; `content` is obtained through a call to `read()`.
# """
#
# def __init__(
# self, wraps: Union[str, File, PurePath], mime_type: str = None, content: bytes = None, file_name: str = None
# ):
# if not isinstance(wraps, (str, File, PurePath)):
# raise TypeError(f"Invalid argument. Expected a Django File or path to file, got {type(wraps).__name__}")
#
# self.wrapped_file = wraps
# self.file_name = file_name or (os.path.basename(wraps if isinstance(wraps, str) else wraps.name))
# self.content = content
#
# # Can use the content_type attribute for UploadedFile
# self.mime_type = mime_type or getattr(wraps, "content_type", "application/octet-stream")
#
# def read(self):
# if self.content is None:
# if isinstance(self.wrapped_file, (str, PurePath)):
# with open(self.wrapped_file, "rb") as f:
# self.content = f.read()
# else:
# # ... This doesn't work in Django 1.11 because the `open()` method returns None in that version.
# # with self.wrapped_file.open("rb") as f:
# with self.wrapped_file as f:
# f.open("rb")
# self.content = f.read()
# return self.content
#
# class InterimSessionData(PredictableDict):
# """
# Wrapper for temporary data stored between container preparation and finalization requests
# """
#
# digest_b64: str # stores digest as a base64 encoded string, to allow JSON serialization
# temp_container_file: str
# temp_signature_file: str
# timestamp: int
#
# @property
# def digest(self):
# return base64.b64decode(self.digest_b64)
#
# @digest.setter
# def digest(self, value: bytes):
# self.digest_b64 = base64.b64encode(value).decode()
. Output only the next line. | f.write(TEST_TXT_CONTENT) |
Predict the next line for this snippet: <|code_start|>
TEST_TXT = "test.txt"
TEST_TXT_CONTENT = b"Hello"
@pytest.fixture()
def test_txt(tmp_path):
# Can't pass fixtures to parametrize() so we need a well-known file name for a parameterized test.
# tmp_path is pytest's builtin fixture with a temporary path as a pathlib.Path object
with open(tmp_path / TEST_TXT, "wb") as f:
f.write(TEST_TXT_CONTENT)
yield open(tmp_path / TEST_TXT, "rb")
@pytest.mark.parametrize(
"value,result",
[
pytest.param(
None,
<|code_end|>
with the help of current file imports:
import base64
import pathlib
import pytest
from django.core.files import File
from ..types import DataFile, InterimSessionData
and context from other files:
# Path: esteid/signing/types.py
# class DataFile:
# """
# Interface for file objects that are added to signed containers.
#
# Constructor accepts a path to file (a string or a pathlib *Path) or a django File.
#
# Additional arguments include:
# - `mime_type`, defaults to "application/octet-stream";
# - `content` if for any reason the wrapped file's content should be ignored (it won't be read in this case);
# - `file_name`: a custom (base)name of the file as it would appear in the container.
#
# The container cares about 3 attributes:
# * file name (base name only)
# - taken from
# * mime type
# * the content, for calculating hash; `content` is obtained through a call to `read()`.
# """
#
# def __init__(
# self, wraps: Union[str, File, PurePath], mime_type: str = None, content: bytes = None, file_name: str = None
# ):
# if not isinstance(wraps, (str, File, PurePath)):
# raise TypeError(f"Invalid argument. Expected a Django File or path to file, got {type(wraps).__name__}")
#
# self.wrapped_file = wraps
# self.file_name = file_name or (os.path.basename(wraps if isinstance(wraps, str) else wraps.name))
# self.content = content
#
# # Can use the content_type attribute for UploadedFile
# self.mime_type = mime_type or getattr(wraps, "content_type", "application/octet-stream")
#
# def read(self):
# if self.content is None:
# if isinstance(self.wrapped_file, (str, PurePath)):
# with open(self.wrapped_file, "rb") as f:
# self.content = f.read()
# else:
# # ... This doesn't work in Django 1.11 because the `open()` method returns None in that version.
# # with self.wrapped_file.open("rb") as f:
# with self.wrapped_file as f:
# f.open("rb")
# self.content = f.read()
# return self.content
#
# class InterimSessionData(PredictableDict):
# """
# Wrapper for temporary data stored between container preparation and finalization requests
# """
#
# digest_b64: str # stores digest as a base64 encoded string, to allow JSON serialization
# temp_container_file: str
# temp_signature_file: str
# timestamp: int
#
# @property
# def digest(self):
# return base64.b64decode(self.digest_b64)
#
# @digest.setter
# def digest(self, value: bytes):
# self.digest_b64 = base64.b64encode(value).decode()
, which may contain function names, class names, or code. Output only the next line. | TypeError(""), |
Based on the snippet: <|code_start|>
AuthenticateResult = namedtuple(
"AuthenticateResult",
[
"session_id",
"hash_type",
"hash_value",
"hash_value_b64",
"verification_code",
],
)
AuthenticateStatusResult = namedtuple(
"AuthenticateStatusResult",
[
"document_number",
"certificate", # DER-encoded certificate
"certificate_b64", # Base64-encoded DER-encoded certificate
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import namedtuple
from typing import Optional
from esteid.constants import Countries
from esteid.signing.types import InterimSessionData
from esteid.types import PredictableDict
from esteid.validators import validate_id_code
and context (classes, functions, sometimes code) from other files:
# Path: esteid/constants.py
# class Countries:
# """Mainly used by SmartID, also phone code"""
#
# ESTONIA = "EE"
# LATVIA = "LV"
# LITHUANIA = "LT"
#
# ALL = (ESTONIA, LATVIA, LITHUANIA)
#
# Path: esteid/signing/types.py
# class InterimSessionData(PredictableDict):
# """
# Wrapper for temporary data stored between container preparation and finalization requests
# """
#
# digest_b64: str # stores digest as a base64 encoded string, to allow JSON serialization
# temp_container_file: str
# temp_signature_file: str
# timestamp: int
#
# @property
# def digest(self):
# return base64.b64decode(self.digest_b64)
#
# @digest.setter
# def digest(self, value: bytes):
# self.digest_b64 = base64.b64encode(value).decode()
#
# Path: esteid/types.py
# class PredictableDict(dict):
# """
# Allows attribute-style access to values of a dict.
#
# Define necessary attributes as type annotations on your subclass:
#
# class Z(PredictableDict):
# required_attr: str
# optional_attr: Optional[str]
#
# and you will get nice attribute-style access with type hints.
#
# Validate the presence of all required attributes and type-check all attributes with:
#
# Z(required_attr="test").is_valid()
#
# Subclasses inherit annotated attributes and can override them, just like normal class attributes.
# """
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.__dict__ = self
#
# def is_valid(self, raise_exception=True):
# for attr_name, attr_type in self._get_annotations().items():
# # type -> (type, )
# # Union[T, S] -> U.__args__ == (T, S)
# valid_types = getattr(attr_type, "__args__", (attr_type,))
#
# try:
# val = self[attr_name]
# except KeyError as e:
# # No error for optional fields.
# if type(None) in valid_types:
# # Optional[T] == Union[T, NoneType]
# continue
#
# if not raise_exception:
# return False
# raise ValueError(f"Missing required key {attr_name}") from e
#
# if type(val) not in valid_types:
# if not raise_exception:
# return False
# raise ValueError(f"Wrong type {type(val)} for key {attr_name}")
#
# return True
#
# @classmethod
# def _get_annotations(cls):
# """Collects annotations from all parent classes according to inheritance rules."""
# annotations = {}
# for klass in reversed(cls.__mro__):
# overrides = getattr(klass, "__annotations__", None)
# if overrides:
# annotations.update(overrides)
# return annotations
#
# Path: esteid/validators.py
# def validate_id_code(id_code, country):
# try:
# validator = ID_CODE_VALIDATORS[country]
# except (KeyError, TypeError) as e:
# raise InvalidParameter(f"Unsupported country '{country}'", param="country") from e
#
# if not validator(id_code):
# # Find country name from Countries attributes
# cty = next(name for name, value in iter(Countries.__dict__.items()) if value == country)
# raise InvalidIdCode(f"ID code '{id_code}' is not valid for {cty.capitalize()}")
. Output only the next line. | "certificate_level", |
Predict the next line after this snippet: <|code_start|> "hash_value",
"hash_value_b64",
"verification_code",
],
)
AuthenticateStatusResult = namedtuple(
"AuthenticateStatusResult",
[
"document_number",
"certificate", # DER-encoded certificate
"certificate_b64", # Base64-encoded DER-encoded certificate
"certificate_level",
],
)
SignResult = namedtuple(
"SignResult",
[
"session_id",
"digest",
"verification_code",
],
)
SignStatusResult = namedtuple(
"SignStatusResult",
[
"document_number",
"signature",
<|code_end|>
using the current file's imports:
from collections import namedtuple
from typing import Optional
from esteid.constants import Countries
from esteid.signing.types import InterimSessionData
from esteid.types import PredictableDict
from esteid.validators import validate_id_code
and any relevant context from other files:
# Path: esteid/constants.py
# class Countries:
# """Mainly used by SmartID, also phone code"""
#
# ESTONIA = "EE"
# LATVIA = "LV"
# LITHUANIA = "LT"
#
# ALL = (ESTONIA, LATVIA, LITHUANIA)
#
# Path: esteid/signing/types.py
# class InterimSessionData(PredictableDict):
# """
# Wrapper for temporary data stored between container preparation and finalization requests
# """
#
# digest_b64: str # stores digest as a base64 encoded string, to allow JSON serialization
# temp_container_file: str
# temp_signature_file: str
# timestamp: int
#
# @property
# def digest(self):
# return base64.b64decode(self.digest_b64)
#
# @digest.setter
# def digest(self, value: bytes):
# self.digest_b64 = base64.b64encode(value).decode()
#
# Path: esteid/types.py
# class PredictableDict(dict):
# """
# Allows attribute-style access to values of a dict.
#
# Define necessary attributes as type annotations on your subclass:
#
# class Z(PredictableDict):
# required_attr: str
# optional_attr: Optional[str]
#
# and you will get nice attribute-style access with type hints.
#
# Validate the presence of all required attributes and type-check all attributes with:
#
# Z(required_attr="test").is_valid()
#
# Subclasses inherit annotated attributes and can override them, just like normal class attributes.
# """
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.__dict__ = self
#
# def is_valid(self, raise_exception=True):
# for attr_name, attr_type in self._get_annotations().items():
# # type -> (type, )
# # Union[T, S] -> U.__args__ == (T, S)
# valid_types = getattr(attr_type, "__args__", (attr_type,))
#
# try:
# val = self[attr_name]
# except KeyError as e:
# # No error for optional fields.
# if type(None) in valid_types:
# # Optional[T] == Union[T, NoneType]
# continue
#
# if not raise_exception:
# return False
# raise ValueError(f"Missing required key {attr_name}") from e
#
# if type(val) not in valid_types:
# if not raise_exception:
# return False
# raise ValueError(f"Wrong type {type(val)} for key {attr_name}")
#
# return True
#
# @classmethod
# def _get_annotations(cls):
# """Collects annotations from all parent classes according to inheritance rules."""
# annotations = {}
# for klass in reversed(cls.__mro__):
# overrides = getattr(klass, "__annotations__", None)
# if overrides:
# annotations.update(overrides)
# return annotations
#
# Path: esteid/validators.py
# def validate_id_code(id_code, country):
# try:
# validator = ID_CODE_VALIDATORS[country]
# except (KeyError, TypeError) as e:
# raise InvalidParameter(f"Unsupported country '{country}'", param="country") from e
#
# if not validator(id_code):
# # Find country name from Countries attributes
# cty = next(name for name, value in iter(Countries.__dict__.items()) if value == country)
# raise InvalidIdCode(f"ID code '{id_code}' is not valid for {cty.capitalize()}")
. Output only the next line. | "signature_algorithm", |
Given the code snippet: <|code_start|>
AuthenticateResult = namedtuple(
"AuthenticateResult",
[
"session_id",
"hash_type",
"hash_value",
"hash_value_b64",
"verification_code",
],
)
AuthenticateStatusResult = namedtuple(
"AuthenticateStatusResult",
[
"document_number",
"certificate", # DER-encoded certificate
"certificate_b64", # Base64-encoded DER-encoded certificate
"certificate_level",
],
)
SignResult = namedtuple(
"SignResult",
<|code_end|>
, generate the next line using the imports in this file:
from collections import namedtuple
from typing import Optional
from esteid.constants import Countries
from esteid.signing.types import InterimSessionData
from esteid.types import PredictableDict
from esteid.validators import validate_id_code
and context (functions, classes, or occasionally code) from other files:
# Path: esteid/constants.py
# class Countries:
# """Mainly used by SmartID, also phone code"""
#
# ESTONIA = "EE"
# LATVIA = "LV"
# LITHUANIA = "LT"
#
# ALL = (ESTONIA, LATVIA, LITHUANIA)
#
# Path: esteid/signing/types.py
# class InterimSessionData(PredictableDict):
# """
# Wrapper for temporary data stored between container preparation and finalization requests
# """
#
# digest_b64: str # stores digest as a base64 encoded string, to allow JSON serialization
# temp_container_file: str
# temp_signature_file: str
# timestamp: int
#
# @property
# def digest(self):
# return base64.b64decode(self.digest_b64)
#
# @digest.setter
# def digest(self, value: bytes):
# self.digest_b64 = base64.b64encode(value).decode()
#
# Path: esteid/types.py
# class PredictableDict(dict):
# """
# Allows attribute-style access to values of a dict.
#
# Define necessary attributes as type annotations on your subclass:
#
# class Z(PredictableDict):
# required_attr: str
# optional_attr: Optional[str]
#
# and you will get nice attribute-style access with type hints.
#
# Validate the presence of all required attributes and type-check all attributes with:
#
# Z(required_attr="test").is_valid()
#
# Subclasses inherit annotated attributes and can override them, just like normal class attributes.
# """
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.__dict__ = self
#
# def is_valid(self, raise_exception=True):
# for attr_name, attr_type in self._get_annotations().items():
# # type -> (type, )
# # Union[T, S] -> U.__args__ == (T, S)
# valid_types = getattr(attr_type, "__args__", (attr_type,))
#
# try:
# val = self[attr_name]
# except KeyError as e:
# # No error for optional fields.
# if type(None) in valid_types:
# # Optional[T] == Union[T, NoneType]
# continue
#
# if not raise_exception:
# return False
# raise ValueError(f"Missing required key {attr_name}") from e
#
# if type(val) not in valid_types:
# if not raise_exception:
# return False
# raise ValueError(f"Wrong type {type(val)} for key {attr_name}")
#
# return True
#
# @classmethod
# def _get_annotations(cls):
# """Collects annotations from all parent classes according to inheritance rules."""
# annotations = {}
# for klass in reversed(cls.__mro__):
# overrides = getattr(klass, "__annotations__", None)
# if overrides:
# annotations.update(overrides)
# return annotations
#
# Path: esteid/validators.py
# def validate_id_code(id_code, country):
# try:
# validator = ID_CODE_VALIDATORS[country]
# except (KeyError, TypeError) as e:
# raise InvalidParameter(f"Unsupported country '{country}'", param="country") from e
#
# if not validator(id_code):
# # Find country name from Countries attributes
# cty = next(name for name, value in iter(Countries.__dict__.items()) if value == country)
# raise InvalidIdCode(f"ID code '{id_code}' is not valid for {cty.capitalize()}")
. Output only the next line. | [ |
Given the following code snippet before the placeholder: <|code_start|>
AuthenticateResult = namedtuple(
"AuthenticateResult",
[
"session_id",
<|code_end|>
, predict the next line using imports from the current file:
from collections import namedtuple
from typing import Optional
from esteid.constants import Countries
from esteid.signing.types import InterimSessionData
from esteid.types import PredictableDict
from esteid.validators import validate_id_code
and context including class names, function names, and sometimes code from other files:
# Path: esteid/constants.py
# class Countries:
# """Mainly used by SmartID, also phone code"""
#
# ESTONIA = "EE"
# LATVIA = "LV"
# LITHUANIA = "LT"
#
# ALL = (ESTONIA, LATVIA, LITHUANIA)
#
# Path: esteid/signing/types.py
# class InterimSessionData(PredictableDict):
# """
# Wrapper for temporary data stored between container preparation and finalization requests
# """
#
# digest_b64: str # stores digest as a base64 encoded string, to allow JSON serialization
# temp_container_file: str
# temp_signature_file: str
# timestamp: int
#
# @property
# def digest(self):
# return base64.b64decode(self.digest_b64)
#
# @digest.setter
# def digest(self, value: bytes):
# self.digest_b64 = base64.b64encode(value).decode()
#
# Path: esteid/types.py
# class PredictableDict(dict):
# """
# Allows attribute-style access to values of a dict.
#
# Define necessary attributes as type annotations on your subclass:
#
# class Z(PredictableDict):
# required_attr: str
# optional_attr: Optional[str]
#
# and you will get nice attribute-style access with type hints.
#
# Validate the presence of all required attributes and type-check all attributes with:
#
# Z(required_attr="test").is_valid()
#
# Subclasses inherit annotated attributes and can override them, just like normal class attributes.
# """
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.__dict__ = self
#
# def is_valid(self, raise_exception=True):
# for attr_name, attr_type in self._get_annotations().items():
# # type -> (type, )
# # Union[T, S] -> U.__args__ == (T, S)
# valid_types = getattr(attr_type, "__args__", (attr_type,))
#
# try:
# val = self[attr_name]
# except KeyError as e:
# # No error for optional fields.
# if type(None) in valid_types:
# # Optional[T] == Union[T, NoneType]
# continue
#
# if not raise_exception:
# return False
# raise ValueError(f"Missing required key {attr_name}") from e
#
# if type(val) not in valid_types:
# if not raise_exception:
# return False
# raise ValueError(f"Wrong type {type(val)} for key {attr_name}")
#
# return True
#
# @classmethod
# def _get_annotations(cls):
# """Collects annotations from all parent classes according to inheritance rules."""
# annotations = {}
# for klass in reversed(cls.__mro__):
# overrides = getattr(klass, "__annotations__", None)
# if overrides:
# annotations.update(overrides)
# return annotations
#
# Path: esteid/validators.py
# def validate_id_code(id_code, country):
# try:
# validator = ID_CODE_VALIDATORS[country]
# except (KeyError, TypeError) as e:
# raise InvalidParameter(f"Unsupported country '{country}'", param="country") from e
#
# if not validator(id_code):
# # Find country name from Countries attributes
# cty = next(name for name, value in iter(Countries.__dict__.items()) if value == country)
# raise InvalidIdCode(f"ID code '{id_code}' is not valid for {cty.capitalize()}")
. Output only the next line. | "hash_type", |
Predict the next line for this snippet: <|code_start|>
def test_context_processors_esteid_services(override_esteid_settings):
test_settings = {
"ESTEID_DEMO": 1,
"ID_CARD_ENABLED": 2,
"MOBILE_ID_ENABLED": 3,
"MOBILE_ID_TEST_MODE": 4,
"SMART_ID_ENABLED": 5,
<|code_end|>
with the help of current file imports:
from esteid import context_processors
and context from other files:
# Path: esteid/context_processors.py
# def esteid_services(*_, **__):
, which may contain function names, class names, or code. Output only the next line. | "SMART_ID_TEST_MODE": 6, |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.parametrize(
"expected_verification_code,hash_raw",
[
("7712", b"Hello World!"),
("3404", b"You broke it, didn't you."),
("0914", b"Weeeeeeeeeeeeeeeeeeeeee[bzzt]"),
],
)
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from esteid.constants import HASH_SHA256
from esteid.smartid.utils import get_verification_code
from esteid.util import generate_hash
and context including class names, function names, and sometimes code from other files:
# Path: esteid/constants.py
# HASH_SHA256 = "SHA256"
#
# Path: esteid/smartid/utils.py
# def get_verification_code(hash_value):
# """Compute Smart-ID verification code from a hash
#
# Verification Code is computed with: `integer(SHA256(hash)[-2:-1]) mod 10000`
#
# 1. Take SHA256 result of hash_value
# 2. Extract 2 rightmost bytes from it
# 3. Interpret them as a big-endian unsigned short
# 4. Take the last 4 digits in decimal
#
# Note: SHA256 is always used, e.g. the algorithm used when generating the hash does not matter
#
# based on https://github.com/SK-EID/smart-id-documentation#612-computing-the-verification-code
# """
# digest = hashlib.sha256(hash_value).digest()
# raw_value = struct.unpack(">H", digest[-2:])[0] % 10000
#
# return f"{raw_value:04}"
#
# Path: esteid/util.py
# def generate_hash(algorithm, data):
# """Hash the data with the supplied algorithm
#
# https://github.com/SK-EID/smart-id-documentation#33-hash-algorithms
# https://github.com/SK-EID/MID#231-supported-hashing-algorithms
# """
# if algorithm.upper() not in HASH_ALGORITHMS:
# raise ValueError(f"Unsupported algorithm {algorithm}")
#
# hash_method = getattr(hashlib, algorithm.lower())
# digest = hash_method(data).digest()
#
# return digest
. Output only the next line. | def test_verification_code_generator(expected_verification_code, hash_raw): |
Next line prediction: <|code_start|>
@pytest.mark.parametrize(
"expected_verification_code,hash_raw",
[
("7712", b"Hello World!"),
("3404", b"You broke it, didn't you."),
("0914", b"Weeeeeeeeeeeeeeeeeeeeee[bzzt]"),
<|code_end|>
. Use current file imports:
(import pytest
from esteid.constants import HASH_SHA256
from esteid.smartid.utils import get_verification_code
from esteid.util import generate_hash)
and context including class names, function names, or small code snippets from other files:
# Path: esteid/constants.py
# HASH_SHA256 = "SHA256"
#
# Path: esteid/smartid/utils.py
# def get_verification_code(hash_value):
# """Compute Smart-ID verification code from a hash
#
# Verification Code is computed with: `integer(SHA256(hash)[-2:-1]) mod 10000`
#
# 1. Take SHA256 result of hash_value
# 2. Extract 2 rightmost bytes from it
# 3. Interpret them as a big-endian unsigned short
# 4. Take the last 4 digits in decimal
#
# Note: SHA256 is always used, e.g. the algorithm used when generating the hash does not matter
#
# based on https://github.com/SK-EID/smart-id-documentation#612-computing-the-verification-code
# """
# digest = hashlib.sha256(hash_value).digest()
# raw_value = struct.unpack(">H", digest[-2:])[0] % 10000
#
# return f"{raw_value:04}"
#
# Path: esteid/util.py
# def generate_hash(algorithm, data):
# """Hash the data with the supplied algorithm
#
# https://github.com/SK-EID/smart-id-documentation#33-hash-algorithms
# https://github.com/SK-EID/MID#231-supported-hashing-algorithms
# """
# if algorithm.upper() not in HASH_ALGORITHMS:
# raise ValueError(f"Unsupported algorithm {algorithm}")
#
# hash_method = getattr(hashlib, algorithm.lower())
# digest = hash_method(data).digest()
#
# return digest
. Output only the next line. | ], |
Predict the next line after this snippet: <|code_start|>
# 3rd Party
# Local Apps
class WelcomeEmail(generics.EmailSendable, GrapevineModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="welcome_emails")
try:
# In Django 1.7, this is finally addressed!
objects = WelcomeEmailQuerySet.as_manager()
except AttributeError:
# This handles Django <= 1.6
objects = PassThroughManager.for_queryset_class(WelcomeEmailQuerySet)()
class Meta:
verbose_name = "Welcome Email"
verbose_name_plural = "Welcome Emails"
def as_str(self):
return "Welcome Email to {0}".format(self.user)
def get_template_name(self):
return "emails/welcome.html"
def get_raw_subject(self):
return "Welcome to Acme Inc, {{ sendable.user }}!"
def get_recipients(self):
<|code_end|>
using the current file's imports:
from django.conf import settings
from django.db import models
from grapevine import generics
from grapevine.models.base import GrapevineModel
from model_utils.managers import PassThroughManager
from .querysets import WelcomeEmailQuerySet
and any relevant context from other files:
# Path: grapevine/generics.py
# class EmailSendable(mixins.Emailable, mixins.SendableMixin):
# class Meta(mixins.SendableMixin.Meta):
# class EmailTemplateSendable(mixins.Emailable,
# mixins.TemplateSendableMixin):
# class Meta(mixins.TemplateSendableMixin.Meta):
#
# Path: grapevine/models/base.py
# class GrapevineModel(GrapevineLogicModel, GrapevineTimeKeepingModel):
#
# class Meta:
# abstract = True
#
# Path: tests/core/querysets.py
# class WelcomeEmailQuerySet(SendableQuerySet):
# """Custom functions would ultimately go here"""
. Output only the next line. | return {"to": [self.user.email], "bcc": ["top@secret.com"]} |
Continue the code snippet: <|code_start|>from __future__ import unicode_literals
# Django
# 3rd Party
# Local Apps
class WelcomeEmail(generics.EmailSendable, GrapevineModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="welcome_emails")
try:
# In Django 1.7, this is finally addressed!
objects = WelcomeEmailQuerySet.as_manager()
except AttributeError:
# This handles Django <= 1.6
objects = PassThroughManager.for_queryset_class(WelcomeEmailQuerySet)()
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.db import models
from grapevine import generics
from grapevine.models.base import GrapevineModel
from model_utils.managers import PassThroughManager
from .querysets import WelcomeEmailQuerySet
and context (classes, functions, or code) from other files:
# Path: grapevine/generics.py
# class EmailSendable(mixins.Emailable, mixins.SendableMixin):
# class Meta(mixins.SendableMixin.Meta):
# class EmailTemplateSendable(mixins.Emailable,
# mixins.TemplateSendableMixin):
# class Meta(mixins.TemplateSendableMixin.Meta):
#
# Path: grapevine/models/base.py
# class GrapevineModel(GrapevineLogicModel, GrapevineTimeKeepingModel):
#
# class Meta:
# abstract = True
#
# Path: tests/core/querysets.py
# class WelcomeEmailQuerySet(SendableQuerySet):
# """Custom functions would ultimately go here"""
. Output only the next line. | class Meta: |
Given snippet: <|code_start|>
@property
def admin_view_info(self):
return '%s_%s' % self.model_meta_info
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
if obj:
context['additional_object_tools'] = self.additional_object_tools(obj)
return super(BaseModelAdmin, self).render_change_form(request, context, add, change, form_url, obj)
def additional_object_tools(self, obj):
tool_urls = []
excludes = self.get_additional_object_tool_excludes(obj)
for relationship in obj._meta.related_objects:
# Skip all excludes
if relationship.get_accessor_name() in excludes:
continue
remote_field_name = relationship.field.name
try:
url = reverse('admin:%s_%s_changelist' % (relationship.model._meta.app_label, relationship.model._meta.model_name,))
url += '?%s=%s' % (remote_field_name, obj.pk,)
display_name = "View %s" % (relationship.get_accessor_name().title(),)
display_name = display_name.replace('_', ' ')
tool_urls.append({
'url': url,
'display_name': display_name
})
except NoReverseMatch:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url
from django.contrib import admin, messages
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, redirect
from grapevine.emails.filters import OnSpecificDateListFilter
from grapevine.utils import render_view
and context:
# Path: grapevine/emails/filters.py
# class OnSpecificDateListFilter(admin.FieldListFilter):
#
# format = 'YYYY-MM-DD'
# endswith = '__date'
#
# def __init__(self, field, request, params, model, model_admin, field_path):
# super(OnSpecificDateListFilter, self).__init__(field, request, params, model, model_admin, field_path)
#
# def expected_parameters(self):
# return [self.field_path + self.endswith]
#
# def lookups(self, request, model_admin):
# return []
#
# @property
# def qs_value(self):
# return self.field_path + self.endswith
#
# def choices(self, cl):
# for x in range(31):
# date = timezone.now()
# # By default, offer 15 days ago to 15 days from now
# date = date + datetime.timedelta(days=(x - 15))
# values = {
# self.qs_value: '%s-%s-%s' % (date.year, date.month, date.day,)
# }
# yield {
# 'selected': self.used_parameters.get(self.qs_value, None) == values[self.qs_value],
# 'query_string': cl.get_query_string(values),
# 'display': date.strftime('%a %b %d, %Y')
# }
#
# def queryset(self, request, queryset):
# processed_params = self.process_used_parameters()
# return queryset.filter(**processed_params)
#
# def process_used_parameters(self):
# """
# Because we accept a querystring value like "my_field__date=2014-01-01",
# which doesn't make sense by itself to the ORM, we have to do some parsing.
# """
# processed_params = {}
# for key, value in self.used_parameters.items():
# if key.endswith(self.endswith):
# # Split into ``field_name`` and "date" on the "__"
# key_field, key_suffix = key.split('__')
#
# # Split the date, too
# year, month, day = value.split('-')
#
# processed_params[key_field + '__year'] = int(year)
# processed_params[key_field + '__month'] = int(month)
# processed_params[key_field + '__day'] = int(day)
# else:
# processed_params[key] = value
# return processed_params
#
# Path: grapevine/utils.py
# def render_view(request, template_name, context={}):
# return render_to_response(template_name, context, context_instance=RequestContext(request))
which might include code, classes, or functions. Output only the next line. | pass |
Here is a snippet: <|code_start|> return (self.model._meta.app_label, self.model._meta.model_name,)
@property
def admin_view_info(self):
return '%s_%s' % self.model_meta_info
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
if obj:
context['additional_object_tools'] = self.additional_object_tools(obj)
return super(BaseModelAdmin, self).render_change_form(request, context, add, change, form_url, obj)
def additional_object_tools(self, obj):
tool_urls = []
excludes = self.get_additional_object_tool_excludes(obj)
for relationship in obj._meta.related_objects:
# Skip all excludes
if relationship.get_accessor_name() in excludes:
continue
remote_field_name = relationship.field.name
try:
url = reverse('admin:%s_%s_changelist' % (relationship.model._meta.app_label, relationship.model._meta.model_name,))
url += '?%s=%s' % (remote_field_name, obj.pk,)
display_name = "View %s" % (relationship.get_accessor_name().title(),)
display_name = display_name.replace('_', ' ')
tool_urls.append({
'url': url,
'display_name': display_name
})
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import url
from django.contrib import admin, messages
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, redirect
from grapevine.emails.filters import OnSpecificDateListFilter
from grapevine.utils import render_view
and context from other files:
# Path: grapevine/emails/filters.py
# class OnSpecificDateListFilter(admin.FieldListFilter):
#
# format = 'YYYY-MM-DD'
# endswith = '__date'
#
# def __init__(self, field, request, params, model, model_admin, field_path):
# super(OnSpecificDateListFilter, self).__init__(field, request, params, model, model_admin, field_path)
#
# def expected_parameters(self):
# return [self.field_path + self.endswith]
#
# def lookups(self, request, model_admin):
# return []
#
# @property
# def qs_value(self):
# return self.field_path + self.endswith
#
# def choices(self, cl):
# for x in range(31):
# date = timezone.now()
# # By default, offer 15 days ago to 15 days from now
# date = date + datetime.timedelta(days=(x - 15))
# values = {
# self.qs_value: '%s-%s-%s' % (date.year, date.month, date.day,)
# }
# yield {
# 'selected': self.used_parameters.get(self.qs_value, None) == values[self.qs_value],
# 'query_string': cl.get_query_string(values),
# 'display': date.strftime('%a %b %d, %Y')
# }
#
# def queryset(self, request, queryset):
# processed_params = self.process_used_parameters()
# return queryset.filter(**processed_params)
#
# def process_used_parameters(self):
# """
# Because we accept a querystring value like "my_field__date=2014-01-01",
# which doesn't make sense by itself to the ORM, we have to do some parsing.
# """
# processed_params = {}
# for key, value in self.used_parameters.items():
# if key.endswith(self.endswith):
# # Split into ``field_name`` and "date" on the "__"
# key_field, key_suffix = key.split('__')
#
# # Split the date, too
# year, month, day = value.split('-')
#
# processed_params[key_field + '__year'] = int(year)
# processed_params[key_field + '__month'] = int(month)
# processed_params[key_field + '__day'] = int(day)
# else:
# processed_params[key] = value
# return processed_params
#
# Path: grapevine/utils.py
# def render_view(request, template_name, context={}):
# return render_to_response(template_name, context, context_instance=RequestContext(request))
, which may include functions, classes, or code. Output only the next line. | except NoReverseMatch: |
Predict the next line after this snippet: <|code_start|># 3rd Party
# from celery import shared_task
try:
# This library isn't absolutely required until you
# want to use the SendGrid backend
except ImportError:
pass
# Local Apps
class EmailBackend(GrapevineEmailBackend):
DISPLAY_NAME = "sendgrid"
IMPORT_PATH = "grapevine.emails.backends.SendGridEmailBackend"
# These are SendGrid variables that have a simple format of
# `name` - enabled - {0|1}
SIMPLE_VARIABLE_MAP = {
"should_show_unsubscribe_link": "subscriptiontrack",
"should_track_clicks": "clicktrack",
"should_track_opens": "opentrack"
}
# Keys here are SendGrid event names, values are
# Grapevine event names
EVENTS_MAP = {
# Only need to list values here that do not map
# exactly (after first letter capitalization)
<|code_end|>
using the current file's imports:
import time
import json
import sendgrid
import grapevine
from django.conf import settings
from django.core.mail.message import EmailMessage
from django.db import transaction
from .base import GrapevineEmailBackend
from grapevine.settings import grapevine_settings
and any relevant context from other files:
# Path: grapevine/emails/backends/base.py
# class GrapevineEmailBackend(BaseEmailBackend):
# # Used to register a callback url for the 3rd party
# DISPLAY_NAME = None
#
# # Used to process catalog events
# IMPORT_PATH = None
#
# LISTENS_FOR_EVENTS = True
#
# def get_urls(self):
# urls = []
# if self.LISTENS_FOR_EVENTS:
# urls.append(
# url(r'^backends/{0}/events/$'.format(self.DISPLAY_NAME), self.events_webhook, name="{0}-events-webhook".format(self.DISPLAY_NAME)),
# )
# return urls
#
# def process_event(self, event):
# """
# This method must only be implemented if this backend
# communicates with a specific email sending provider that
# offers webhooks for email events.
# """
# raise NotImplementedError()
#
# def datetime_from_seconds(self, timestamp):
# """
# Takes a timestamp (like 1337966815) and turns it into
# something like this: datetime.datetime(2012, 5, 16, 15, 46, 40, tzinfo=<UTC>)
# """
# datetime_obj = datetime.datetime.utcfromtimestamp(timestamp)
# return timezone.make_aware(datetime_obj, timezone.get_default_timezone())
#
# @classmethod
# def debugify_message(cls, message):
# message.to = [grapevine_settings.DEBUG_EMAIL_ADDRESS]
# message.cc = []
# message.bcc = []
#
# return message
#
# @classmethod
# def finalize_message(cls, message):
# """
# Where the ``DEBUG`` setting and unsubscribe list are honored.
#
# Note that this works for the Django ``EmailMessage`` class as well
# as the SendGrid ``mail.Mail()`` class, as the two store recipients
# internally the same way.
# """
# # Strip out all recipients if this is a (localhost-style)
# # TEST_EMAIL.
# if grapevine_settings.DEBUG:
# message = cls.debugify_message(message)
#
# # Compile a grand list of all recipient lists
# recipient_lists = [getattr(message, 'to', []), getattr(message, 'cc', []), getattr(message, 'bcc', [])]
# for recipient_list in recipient_lists:
# indicies_to_pop = []
# for index, recipient in enumerate(recipient_list):
# try:
# # Remove any remaining unsubscribed emails
# name, address = parse_email(recipient)
# unsubscribed = grapevine.emails.models.UnsubscribedAddress.objects.get(
# address=address
# )
# indicies_to_pop.append(index)
# except grapevine.emails.models.UnsubscribedAddress.DoesNotExist:
# pass
#
# # Must loop over this list in reverse to not change
# # the indicies of elements after the one's we remove
# indicies_to_pop.reverse()
# for index in indicies_to_pop:
# recipient_list.pop(index)
#
# return message
#
# @csrf_exempt
# def events_webhook(self, request):
# """
# Responds to {POST /grapevine/backends/:DISPLAY_NAME/events/}
# """
# # Using the ``require_POST`` decorator causes problems
# if request.method != 'POST':
# return HttpResponse(status=405)
#
# try:
# backend = grapevine.emails.models.EmailBackend.objects.filter(path=self.IMPORT_PATH)[0]
# except IndexError:
# backend = grapevine.emails.models.EmailBackend.objects.create(path=self.IMPORT_PATH)
#
# # Pull out the payload from request.POST as per
# # https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.POST
# grapevine.emails.models.RawEvent.objects.create(
# backend=backend, payload=request.body,
# remote_ip=request.META['REMOTE_ADDR'])
#
# # A 200 tells SendGrid we successfully accepted this event payload
# return HttpResponse(status=200)
#
# Path: grapevine/settings.py
# USER_SETTINGS = getattr(settings, 'GRAPEVINE', {})
# DEFAULTS = {
# 'SENDER_CLASS': 'grapevine.engines.SynchronousSender',
# 'EMAIL_BACKEND': None,
# 'DEBUG_EMAIL_ADDRESS': 'test@email.com',
# }
# GLOBAL_DEFAULTS = (
# 'EMAIL_BACKEND',
# 'DEBUG',
# )
# IMPORTABLE_SETTINGS = (
# 'SENDER_CLASS',
# )
# def perform_import(val, setting_name):
# def import_from_string(val, setting_name):
# def __init__(self, user_settings=None, defaults=None,
# global_settings_keys=None, importable_settings=None, django_settings=None):
# def __getattr__(self, attr):
# class GrapevineSettings(object):
. Output only the next line. | "spamreport": "Spam Report" |
Given snippet: <|code_start|>from __future__ import unicode_literals
# Django
# 3rd Party
class UserFactory(factory.django.DjangoModelFactory):
username = factory.fuzzy.FuzzyText(length=10)
first_name = factory.fuzzy.FuzzyText(length=10)
last_name = factory.fuzzy.FuzzyText(length=10)
email = factory.LazyAttribute(lambda a: '{0}.{1}@gmail.com'.format(a.first_name, a.last_name).lower())
class Meta:
model = get_user_model()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.auth import get_user_model
from factory import fuzzy
from grapevine.emails import models
import factory
and context:
# Path: grapevine/emails/models.py
# class Email(Transport):
# class Meta:
# class EmailRecipient(GrapevineModel):
# class Meta:
# class EmailBackend(GrapevineModel):
# class Meta:
# class EmailVariable(GrapevineModel):
# class Meta:
# class RawEvent(GrapevineModel):
# class Meta:
# class Event(GrapevineModel):
# class Meta:
# class EmailEvent(GrapevineModel):
# class Meta:
# class UnsubscribedAddress(GrapevineModel):
# class Meta:
# def get_absolute_url(self):
# def ensure_from_email(self):
# def ensure_reply_to(self):
# def ensure_subject(self):
# def __str__(self):
# def get_main_recipient(self):
# def save(self, *args, **kwargs):
# def determine_backend(**kwargs):
# def extra_transport_data(sendable, **kwargs):
# def add_tos(self, recipients):
# def add_ccs(self, recipients):
# def add_bccs(self, recipients):
# def add_recipient(self, recipient, recipient_type):
# def add_recipients(self, recipients):
# def add_variable(self, key, value):
# def to(self):
# def cc(self):
# def bcc(self):
# def _send(self, backend=None, fail_silently=False, **kwargs):
# def is_spam(self):
# def is_opened(self):
# def is_clicked(self):
# def cached_events(self):
# def find_event_by_name(self, name):
# def __str__(self):
# def prepare_for_email(self):
# def determine_domain(self):
# def save(self, *args, **kwargs):
# def kls(self):
# def __str__(self):
# def get_connection(self, fail_silently=False, **kwargs):
# def get_headers(self, email):
# def as_message(self, email):
# def finalize_message(self, message):
# def send(self, email, fail_silently=False, **kwargs):
# def _send(self, msg, **kwargs):
# def __str__(self):
# def async_process(raw_event_id):
# def process(self):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# TO = 1
# CC = 2
# BCC = 3
# TYPES = (
# (TO, 'To',),
# (CC, 'CC',),
# (BCC, 'BCC',),
# )
which might include code, classes, or functions. Output only the next line. | class EmailFactory(factory.django.DjangoModelFactory): |
Predict the next line for this snippet: <|code_start|># Sys
try:
except ImportError:
try:
except:
# Django
# Local
<|code_end|>
with the help of current file imports:
import json
import requests
from cStringIO import StringIO
from StringIO import StringIO
from io import StringIO
from django.conf import settings
from django.core.mail.message import sanitize_address
from grapevine.emails.backends.base import GrapevineEmailBackend
and context from other files:
# Path: grapevine/emails/backends/base.py
# class GrapevineEmailBackend(BaseEmailBackend):
# # Used to register a callback url for the 3rd party
# DISPLAY_NAME = None
#
# # Used to process catalog events
# IMPORT_PATH = None
#
# LISTENS_FOR_EVENTS = True
#
# def get_urls(self):
# urls = []
# if self.LISTENS_FOR_EVENTS:
# urls.append(
# url(r'^backends/{0}/events/$'.format(self.DISPLAY_NAME), self.events_webhook, name="{0}-events-webhook".format(self.DISPLAY_NAME)),
# )
# return urls
#
# def process_event(self, event):
# """
# This method must only be implemented if this backend
# communicates with a specific email sending provider that
# offers webhooks for email events.
# """
# raise NotImplementedError()
#
# def datetime_from_seconds(self, timestamp):
# """
# Takes a timestamp (like 1337966815) and turns it into
# something like this: datetime.datetime(2012, 5, 16, 15, 46, 40, tzinfo=<UTC>)
# """
# datetime_obj = datetime.datetime.utcfromtimestamp(timestamp)
# return timezone.make_aware(datetime_obj, timezone.get_default_timezone())
#
# @classmethod
# def debugify_message(cls, message):
# message.to = [grapevine_settings.DEBUG_EMAIL_ADDRESS]
# message.cc = []
# message.bcc = []
#
# return message
#
# @classmethod
# def finalize_message(cls, message):
# """
# Where the ``DEBUG`` setting and unsubscribe list are honored.
#
# Note that this works for the Django ``EmailMessage`` class as well
# as the SendGrid ``mail.Mail()`` class, as the two store recipients
# internally the same way.
# """
# # Strip out all recipients if this is a (localhost-style)
# # TEST_EMAIL.
# if grapevine_settings.DEBUG:
# message = cls.debugify_message(message)
#
# # Compile a grand list of all recipient lists
# recipient_lists = [getattr(message, 'to', []), getattr(message, 'cc', []), getattr(message, 'bcc', [])]
# for recipient_list in recipient_lists:
# indicies_to_pop = []
# for index, recipient in enumerate(recipient_list):
# try:
# # Remove any remaining unsubscribed emails
# name, address = parse_email(recipient)
# unsubscribed = grapevine.emails.models.UnsubscribedAddress.objects.get(
# address=address
# )
# indicies_to_pop.append(index)
# except grapevine.emails.models.UnsubscribedAddress.DoesNotExist:
# pass
#
# # Must loop over this list in reverse to not change
# # the indicies of elements after the one's we remove
# indicies_to_pop.reverse()
# for index in indicies_to_pop:
# recipient_list.pop(index)
#
# return message
#
# @csrf_exempt
# def events_webhook(self, request):
# """
# Responds to {POST /grapevine/backends/:DISPLAY_NAME/events/}
# """
# # Using the ``require_POST`` decorator causes problems
# if request.method != 'POST':
# return HttpResponse(status=405)
#
# try:
# backend = grapevine.emails.models.EmailBackend.objects.filter(path=self.IMPORT_PATH)[0]
# except IndexError:
# backend = grapevine.emails.models.EmailBackend.objects.create(path=self.IMPORT_PATH)
#
# # Pull out the payload from request.POST as per
# # https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.POST
# grapevine.emails.models.RawEvent.objects.create(
# backend=backend, payload=request.body,
# remote_ip=request.META['REMOTE_ADDR'])
#
# # A 200 tells SendGrid we successfully accepted this event payload
# return HttpResponse(status=200)
, which may contain function names, class names, or code. Output only the next line. | class MailgunAPIError(Exception): |
Here is a snippet: <|code_start|>from __future__ import unicode_literals
# Django
# Local Apps
class GrapevineEmailBackend(BaseEmailBackend):
# Used to register a callback url for the 3rd party
DISPLAY_NAME = None
# Used to process catalog events
IMPORT_PATH = None
LISTENS_FOR_EVENTS = True
def get_urls(self):
urls = []
if self.LISTENS_FOR_EVENTS:
urls.append(
url(r'^backends/{0}/events/$'.format(self.DISPLAY_NAME), self.events_webhook, name="{0}-events-webhook".format(self.DISPLAY_NAME)),
)
<|code_end|>
. Write the next line using the current file imports:
import datetime
import grapevine
from django.conf.urls import url
from django.core.mail.backends.base import BaseEmailBackend
from django.http import HttpResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from grapevine.settings import grapevine_settings
from grapevine.emails.utils import parse_email
and context from other files:
# Path: grapevine/settings.py
# USER_SETTINGS = getattr(settings, 'GRAPEVINE', {})
# DEFAULTS = {
# 'SENDER_CLASS': 'grapevine.engines.SynchronousSender',
# 'EMAIL_BACKEND': None,
# 'DEBUG_EMAIL_ADDRESS': 'test@email.com',
# }
# GLOBAL_DEFAULTS = (
# 'EMAIL_BACKEND',
# 'DEBUG',
# )
# IMPORTABLE_SETTINGS = (
# 'SENDER_CLASS',
# )
# def perform_import(val, setting_name):
# def import_from_string(val, setting_name):
# def __init__(self, user_settings=None, defaults=None,
# global_settings_keys=None, importable_settings=None, django_settings=None):
# def __getattr__(self, attr):
# class GrapevineSettings(object):
#
# Path: grapevine/emails/utils.py
# def parse_email(address):
# """
# Returns "Marco Polo", "marco@polo.com" from "Marco Polo <marco@polo.com"
# Returns "", "marco@polo.com" from "marco@polo.com"
# """
# if ' ' in address.strip():
# assert '<' in address and '>' in address, "Invalid address structure: %s" % (address,)
# parts = address.split(' ')
# name = ' '.join(parts[:-1])
# address = parts[-1][1:-1]
#
# return name, address
# else:
# return "", address
, which may include functions, classes, or code. Output only the next line. | return urls |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
# Django
# Local Apps
class GrapevineEmailBackend(BaseEmailBackend):
# Used to register a callback url for the 3rd party
DISPLAY_NAME = None
# Used to process catalog events
IMPORT_PATH = None
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import grapevine
from django.conf.urls import url
from django.core.mail.backends.base import BaseEmailBackend
from django.http import HttpResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from grapevine.settings import grapevine_settings
from grapevine.emails.utils import parse_email
and context including class names, function names, and sometimes code from other files:
# Path: grapevine/settings.py
# USER_SETTINGS = getattr(settings, 'GRAPEVINE', {})
# DEFAULTS = {
# 'SENDER_CLASS': 'grapevine.engines.SynchronousSender',
# 'EMAIL_BACKEND': None,
# 'DEBUG_EMAIL_ADDRESS': 'test@email.com',
# }
# GLOBAL_DEFAULTS = (
# 'EMAIL_BACKEND',
# 'DEBUG',
# )
# IMPORTABLE_SETTINGS = (
# 'SENDER_CLASS',
# )
# def perform_import(val, setting_name):
# def import_from_string(val, setting_name):
# def __init__(self, user_settings=None, defaults=None,
# global_settings_keys=None, importable_settings=None, django_settings=None):
# def __getattr__(self, attr):
# class GrapevineSettings(object):
#
# Path: grapevine/emails/utils.py
# def parse_email(address):
# """
# Returns "Marco Polo", "marco@polo.com" from "Marco Polo <marco@polo.com"
# Returns "", "marco@polo.com" from "marco@polo.com"
# """
# if ' ' in address.strip():
# assert '<' in address and '>' in address, "Invalid address structure: %s" % (address,)
# parts = address.split(' ')
# name = ' '.join(parts[:-1])
# address = parts[-1][1:-1]
#
# return name, address
# else:
# return "", address
. Output only the next line. | LISTENS_FOR_EVENTS = True |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
# Django
# Local Apps
class EmailSendable(mixins.Emailable, mixins.SendableMixin):
class Meta(mixins.SendableMixin.Meta):
abstract = True
if 'tablets' in settings.INSTALLED_APPS:
class EmailTemplateSendable(mixins.Emailable,
mixins.TemplateSendableMixin):
class Meta(mixins.TemplateSendableMixin.Meta):
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from grapevine import mixins
and context (functions, classes, or occasionally code) from other files:
# Path: grapevine/mixins.py
# class SendableMixin(models.Model):
# class Meta:
# class TemplateSendableMixin(SendableMixin):
# class Meta(SendableMixin.Meta):
# class Emailable(object):
# def save(self, *args, **kwargs):
# def is_sent(self):
# def is_spam(self):
# def is_opened(self):
# def is_clicked(self):
# def get_absolute_url(self):
# def message(self):
# def message(self, value):
# def denote_as_queued(self):
# def delete_from_queue(self):
# def default_scheduled_send_time(self):
# def get_template(self, template_name=None):
# def get_template_name(self):
# def compile_context(self):
# def get_context(self):
# def _get_recipients(self, recipient_address=None):
# def get_normalized_recipients(self):
# def get_recipients(self):
# def get_raw_subject(self):
# def get_subject(self):
# def get_raw_from_email(self):
# def get_from_email(self):
# def get_raw_reply_to(self):
# def get_reply_to(self):
# def text_body(self):
# def html_body(self):
# def html_body(self, value):
# def render(self, template_name=None, context=None):
# def _render(self, template, context):
# def alter_transport(self, transport, **kwargs):
# def get_transport_class(self):
# def as_transport(self, recipient_address=None, is_test=False, **kwargs):
# def async_send(cls, sendable_id, *args, **kwargs):
# def send(self, recipient_address=None, is_test=False, **kwargs):
# def send_test(self, recipient_address, **kwargs):
# def confirm_individual_sendability(self):
# def get_template_name(self):
# def get_raw_subject(self):
# def get_raw_reply_to(self):
# def get_raw_from_email(self):
# def get_template(self, template_name=None):
# def get_transport_class():
# def remove_unsubscribe_link(self, transport):
# def track_clicks(self, transport):
# def track_opens(self, transport):
# def add_ganalytic(self, transport, key, value):
. Output only the next line. | abstract = True |
Given the following code snippet before the placeholder: <|code_start|> select_related = ['article__site_owner', 'contributor__user']
def get_queryset(self):
queryset = super(UserDetailView, self).get_queryset()
return queryset.select_related(*self.select_related)
class UserRedirectView(LoginRequiredMixin, RedirectView):
permanent = False
def get_redirect_url(self):
return reverse("users:detail", args=(self.request.user.id,))
class UserUpdateView(LoginRequiredMixin, UpdateView):
form_class = UserForm
# we already imported User in the view code above, remember?
model = User
# send the user back to their own page after a successful update
def get_success_url(self):
return reverse("users:detail", args=(self.request.user.id,))
def get_object(self):
# Only get the User record for the user making the request
return User.objects.get(username=self.request.user.username)
<|code_end|>
, predict the next line using imports from the current file:
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from django.views.generic import ListView
from braces.views import LoginRequiredMixin, SelectRelatedMixin
from .forms import UserForm
from .models import User
and context including class names, function names, and sometimes code from other files:
# Path: companionpages/users/forms.py
# class UserForm(forms.ModelForm):
#
# class Meta:
# # Set this form to use the User model.
# model = User
#
# fields = ("first_name", "last_name", "public_name", "affiliation", "biography", "country")
#
# Path: companionpages/users/models.py
# class User(AbstractUser):
# # from AbstractUser we have
# # firstname, lastname, email, username
#
# public_name = models.CharField(max_length=150, blank=True, verbose_name=_(u'Public Name'), help_text=_(u'Publically displayed name'))
# biography = models.TextField(max_length=400, blank=True, verbose_name=_(u'Biography'))
# affiliation = models.CharField(max_length=200, verbose_name=_(u'Affiliation'), blank=True)
# country = models.CharField(max_length=200, verbose_name=_(u'Country'), blank=True)
# urls = JSONField(default="{}", verbose_name=_(u'URLs'))
#
# def __unicode__(self):
# return self.email
. Output only the next line. | class UserListView(LoginRequiredMixin, ListView): |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Import the reverse lookup function
# view imports
class UserDetailView(LoginRequiredMixin, SelectRelatedMixin, DetailView):
model = User
select_related = ['article__site_owner', 'contributor__user']
def get_queryset(self):
queryset = super(UserDetailView, self).get_queryset()
return queryset.select_related(*self.select_related)
class UserRedirectView(LoginRequiredMixin, RedirectView):
<|code_end|>
. Use current file imports:
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from django.views.generic import ListView
from braces.views import LoginRequiredMixin, SelectRelatedMixin
from .forms import UserForm
from .models import User
and context (classes, functions, or code) from other files:
# Path: companionpages/users/forms.py
# class UserForm(forms.ModelForm):
#
# class Meta:
# # Set this form to use the User model.
# model = User
#
# fields = ("first_name", "last_name", "public_name", "affiliation", "biography", "country")
#
# Path: companionpages/users/models.py
# class User(AbstractUser):
# # from AbstractUser we have
# # firstname, lastname, email, username
#
# public_name = models.CharField(max_length=150, blank=True, verbose_name=_(u'Public Name'), help_text=_(u'Publically displayed name'))
# biography = models.TextField(max_length=400, blank=True, verbose_name=_(u'Biography'))
# affiliation = models.CharField(max_length=200, verbose_name=_(u'Affiliation'), blank=True)
# country = models.CharField(max_length=200, verbose_name=_(u'Country'), blank=True)
# urls = JSONField(default="{}", verbose_name=_(u'URLs'))
#
# def __unicode__(self):
# return self.email
. Output only the next line. | permanent = False |
Continue the code snippet: <|code_start|>
def tearDown(self):
if os.path.isdir(self.db):
shutil.rmtree(self.db)
def create_db(self, files):
self.db = tempfile.mkdtemp()
for filename, content in files.items():
open(os.path.join(self.db, filename), 'w+').write(content)
def test_yamlbackend_load(self):
f1 = """
---
key: value
"""
f2 = """
---
key2: value2
"""
files = {'f1.yaml': f1, 'f2.yaml': f2}
self.create_db(files)
backend = YAMLBackend(db_path=self.db)
backend.load_db()
default_data, data = backend.get_data()
self.assertEqual(default_data, None)
self.assertEqual(len(data), 2)
def test_yamlbackend_load_with_default(self):
f1 = """
---
<|code_end|>
. Use current file imports:
import os
import shutil
import tempfile
from unittest import TestCase
from repoxplorer.index.yamlbackend import YAMLBackend
and context (classes, functions, or code) from other files:
# Path: repoxplorer/index/yamlbackend.py
# class YAMLBackend(object):
# def __init__(self, db_path, db_default_file=None, db_cache_path=None):
# """ Class to read YAML files from a DB path.
# db_default_file: is the path to a trusted file usually
# computed from an already verified data source.
# db_path: directory where data can be read. This is
# supposed to be user provided data to be verified
# by the caller and could overwrite data from the
# default_file.
# db_cache_path: directory to store cache files
# """
# self.db_path = db_path or conf.get('db_path')
# self.db_default_file = db_default_file
# self.db_cache_path = (
# db_cache_path or conf.get('db_cache_path') or self.db_path)
#
# self.default_data = None
# self.data = []
# # List of hashes
# self.hashes = []
#
# def load_db(self):
# def check_ext(f):
# return f.endswith('.yaml') or f.endswith('.yml')
#
# def load(path):
# data = None
# logger.debug("Check cache for %s ..." % path)
# basename = os.path.basename(path)
# if not os.path.isdir(self.db_path):
# os.makedirs(self.db_path)
# if self.db_cache_path and not os.path.isdir(self.db_cache_path):
# os.makedirs(self.db_cache_path)
# cached_hash_path = os.path.join(
# self.db_cache_path, basename + '.hash')
# cached_data_path = os.path.join(
# self.db_cache_path, basename + '.cached')
# hash = SHA.new(open(path).read().encode(
# errors='ignore')).hexdigest()
# if (os.path.isfile(cached_hash_path) and
# os.path.isfile(cached_data_path)):
# cached_hash = pickle.load(open(cached_hash_path, 'rb'))
# if cached_hash == hash:
# logger.debug("Reading %s from cache ..." % path)
# data = pickle.load(open(cached_data_path, 'rb'))
# self.hashes.append(hash)
# if not data:
# logger.debug("Reading %s from file ..." % path)
# try:
# data = yaml.load(
# open(path, 'rb'), Loader=NoDatesSafeLoader)
# except Exception as e:
# raise YAMLDBException(
# "YAML format corrupted in file %s (%s)" % (path, e))
# pickle.dump(
# data, open(cached_data_path, 'wb'),
# pickle.HIGHEST_PROTOCOL)
# pickle.dump(
# hash, open(cached_hash_path, 'wb'),
# pickle.HIGHEST_PROTOCOL)
# self.hashes.append(hash)
# return data
#
# if self.db_default_file:
# self.default_data = load(self.db_default_file)
#
# yamlfiles = [f for f in os.listdir(self.db_path) if check_ext(f)]
# yamlfiles.sort()
# for f in yamlfiles:
# path = os.path.join(self.db_path, f)
# if path == self.db_default_file:
# continue
# self.data.append(load(path))
#
# def get_data(self):
# """ Return the full raw data structure.
# """
# return self.default_data, self.data
. Output only the next line. | key: value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.