Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|> #
account = Account.objects.get(id=1)
self.assertEqual(account.id, 1)
self.assertEqual(account.email, 'john@example.com')
account = Account.objects.get(email='paul@example.com')
self.assertEqual(account.id, 2)
self.assertEqual(account.email, 'paul@example.com')
# All
accounts = Account.objects.all()
self.assertEqual(accounts.count(), 2)
self.assertEqual(accounts[0].id, 1)
self.assertEqual(accounts[0].email, 'john@example.com')
self.assertEqual(accounts[1].id, 2)
self.assertEqual(accounts[1].email, 'paul@example.com')
# filter
accounts = Account.objects.filter(email='paul@example.com')
self.assertEqual(accounts.count(), 1)
self.assertEqual(accounts[0].id, 2)
self.assertEqual(accounts[0].email, 'paul@example.com')
#
# Relationships
# Typical relationships applications
#
# One to One
<|code_end|>
. Use current file imports:
from django.utils.timezone import now
from rest_framework.test import APITestCase
from django_roa.db.exceptions import ROAException
from .models import Account, Article, Tag, Reporter
and context (classes, functions, or code) from other files:
# Path: examples/django_rest_framework/frontend/frontend/models.py
# class Account(CommonROAModel):
# id = models.IntegerField(primary_key=True) # don't forget it !
# email = models.CharField(max_length=30)
#
# api_base_name = 'accounts'
#
# @classmethod
# def serializer(cls):
# from .serializers import AccountSerializer
# return AccountSerializer
#
# class Article(CommonROAModel):
# id = models.IntegerField(primary_key=True) # don't forget it !
# headline = models.CharField(max_length=100)
# pub_date = models.DateField()
# reporter = models.ForeignKey(Reporter, related_name='articles')
#
# api_base_name = 'articles'
#
# @classmethod
# def serializer(cls):
# from .serializers import ArticleSerializer
# return ArticleSerializer
#
# class Tag(CommonROAModel):
# id = models.IntegerField(primary_key=True) # don't forget it !
# label = models.CharField(max_length=30)
# articles = models.ManyToManyField(Article, related_name='tags')
#
# api_base_name = 'tags'
#
# @classmethod
# def serializer(cls):
# from .serializers import TagSerializer
# return TagSerializer
#
# class Reporter(CommonROAModel):
# id = models.IntegerField(primary_key=True) # don't forget it !
# account = models.OneToOneField(Account)
# first_name = models.CharField(max_length=30)
# last_name = models.CharField(max_length=30)
#
# api_base_name = 'reporters'
#
# @classmethod
# def serializer(cls):
# from .serializers import ReporterSerializer
# return ReporterSerializer
. Output only the next line. | reporter = Reporter.objects.get(id=1) |
Next line prediction: <|code_start|>
# API
router = routers.DefaultRouter()
router.register(r'accounts', AccountViewSet, base_name='account')
router.register(r'reporters', ReporterViewSet, base_name='reporter')
<|code_end|>
. Use current file imports:
(from rest_framework import routers
from .api.views import AccountViewSet, ReporterViewSet, ArticleViewSet, \
TagViewSet, ReversedArticleViewSet, ReversedReporterViewSet, \
ReversedTagViewSet, ReversedAccountViewSet)
and context including class names, function names, or small code snippets from other files:
# Path: examples/django_rest_framework/backend/backend/api/views.py
# class AccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = AccountSerializer
#
# class ReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReporterSerializer
#
# class ArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ArticleSerializer
#
# class TagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = TagSerializer
# # Do not paginate the tags, for unpaginated testing
# paginate_by = None
#
# class ReversedArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ReversedArticleSerializer
#
# class ReversedReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReversedReporterSerializer
#
# class ReversedTagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = ReversedTagSerializer
#
# class ReversedAccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = ReversedAccountSerializer
. Output only the next line. | router.register(r'articles', ArticleViewSet, base_name='article') |
Next line prediction: <|code_start|>
# API
router = routers.DefaultRouter()
router.register(r'accounts', AccountViewSet, base_name='account')
router.register(r'reporters', ReporterViewSet, base_name='reporter')
router.register(r'articles', ArticleViewSet, base_name='article')
<|code_end|>
. Use current file imports:
(from rest_framework import routers
from .api.views import AccountViewSet, ReporterViewSet, ArticleViewSet, \
TagViewSet, ReversedArticleViewSet, ReversedReporterViewSet, \
ReversedTagViewSet, ReversedAccountViewSet)
and context including class names, function names, or small code snippets from other files:
# Path: examples/django_rest_framework/backend/backend/api/views.py
# class AccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = AccountSerializer
#
# class ReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReporterSerializer
#
# class ArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ArticleSerializer
#
# class TagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = TagSerializer
# # Do not paginate the tags, for unpaginated testing
# paginate_by = None
#
# class ReversedArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ReversedArticleSerializer
#
# class ReversedReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReversedReporterSerializer
#
# class ReversedTagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = ReversedTagSerializer
#
# class ReversedAccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = ReversedAccountSerializer
. Output only the next line. | router.register(r'tags', TagViewSet, base_name='tag') |
Predict the next line for this snippet: <|code_start|>
# API
router = routers.DefaultRouter()
router.register(r'accounts', AccountViewSet, base_name='account')
router.register(r'reporters', ReporterViewSet, base_name='reporter')
router.register(r'articles', ArticleViewSet, base_name='article')
router.register(r'tags', TagViewSet, base_name='tag')
router.register(r'reversed/tags', ReversedTagViewSet, base_name='reversedtag')
<|code_end|>
with the help of current file imports:
from rest_framework import routers
from .api.views import AccountViewSet, ReporterViewSet, ArticleViewSet, \
TagViewSet, ReversedArticleViewSet, ReversedReporterViewSet, \
ReversedTagViewSet, ReversedAccountViewSet
and context from other files:
# Path: examples/django_rest_framework/backend/backend/api/views.py
# class AccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = AccountSerializer
#
# class ReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReporterSerializer
#
# class ArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ArticleSerializer
#
# class TagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = TagSerializer
# # Do not paginate the tags, for unpaginated testing
# paginate_by = None
#
# class ReversedArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ReversedArticleSerializer
#
# class ReversedReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReversedReporterSerializer
#
# class ReversedTagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = ReversedTagSerializer
#
# class ReversedAccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = ReversedAccountSerializer
, which may contain function names, class names, or code. Output only the next line. | router.register(r'reversed/articles', ReversedArticleViewSet, base_name='reversedarticle') |
Based on the snippet: <|code_start|>
# API
router = routers.DefaultRouter()
router.register(r'accounts', AccountViewSet, base_name='account')
router.register(r'reporters', ReporterViewSet, base_name='reporter')
router.register(r'articles', ArticleViewSet, base_name='article')
router.register(r'tags', TagViewSet, base_name='tag')
router.register(r'reversed/tags', ReversedTagViewSet, base_name='reversedtag')
router.register(r'reversed/articles', ReversedArticleViewSet, base_name='reversedarticle')
<|code_end|>
, predict the immediate next line with the help of imports:
from rest_framework import routers
from .api.views import AccountViewSet, ReporterViewSet, ArticleViewSet, \
TagViewSet, ReversedArticleViewSet, ReversedReporterViewSet, \
ReversedTagViewSet, ReversedAccountViewSet
and context (classes, functions, sometimes code) from other files:
# Path: examples/django_rest_framework/backend/backend/api/views.py
# class AccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = AccountSerializer
#
# class ReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReporterSerializer
#
# class ArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ArticleSerializer
#
# class TagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = TagSerializer
# # Do not paginate the tags, for unpaginated testing
# paginate_by = None
#
# class ReversedArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ReversedArticleSerializer
#
# class ReversedReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReversedReporterSerializer
#
# class ReversedTagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = ReversedTagSerializer
#
# class ReversedAccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = ReversedAccountSerializer
. Output only the next line. | router.register(r'reversed/reporters', ReversedReporterViewSet, base_name='reversedreporter') |
Predict the next line after this snippet: <|code_start|>
# API
router = routers.DefaultRouter()
router.register(r'accounts', AccountViewSet, base_name='account')
router.register(r'reporters', ReporterViewSet, base_name='reporter')
router.register(r'articles', ArticleViewSet, base_name='article')
router.register(r'tags', TagViewSet, base_name='tag')
<|code_end|>
using the current file's imports:
from rest_framework import routers
from .api.views import AccountViewSet, ReporterViewSet, ArticleViewSet, \
TagViewSet, ReversedArticleViewSet, ReversedReporterViewSet, \
ReversedTagViewSet, ReversedAccountViewSet
and any relevant context from other files:
# Path: examples/django_rest_framework/backend/backend/api/views.py
# class AccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = AccountSerializer
#
# class ReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReporterSerializer
#
# class ArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ArticleSerializer
#
# class TagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = TagSerializer
# # Do not paginate the tags, for unpaginated testing
# paginate_by = None
#
# class ReversedArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ReversedArticleSerializer
#
# class ReversedReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReversedReporterSerializer
#
# class ReversedTagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = ReversedTagSerializer
#
# class ReversedAccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = ReversedAccountSerializer
. Output only the next line. | router.register(r'reversed/tags', ReversedTagViewSet, base_name='reversedtag') |
Predict the next line after this snippet: <|code_start|>
# API
router = routers.DefaultRouter()
router.register(r'accounts', AccountViewSet, base_name='account')
router.register(r'reporters', ReporterViewSet, base_name='reporter')
router.register(r'articles', ArticleViewSet, base_name='article')
router.register(r'tags', TagViewSet, base_name='tag')
router.register(r'reversed/tags', ReversedTagViewSet, base_name='reversedtag')
router.register(r'reversed/articles', ReversedArticleViewSet, base_name='reversedarticle')
router.register(r'reversed/reporters', ReversedReporterViewSet, base_name='reversedreporter')
<|code_end|>
using the current file's imports:
from rest_framework import routers
from .api.views import AccountViewSet, ReporterViewSet, ArticleViewSet, \
TagViewSet, ReversedArticleViewSet, ReversedReporterViewSet, \
ReversedTagViewSet, ReversedAccountViewSet
and any relevant context from other files:
# Path: examples/django_rest_framework/backend/backend/api/views.py
# class AccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = AccountSerializer
#
# class ReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReporterSerializer
#
# class ArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ArticleSerializer
#
# class TagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = TagSerializer
# # Do not paginate the tags, for unpaginated testing
# paginate_by = None
#
# class ReversedArticleViewSet(ModelViewSet):
# queryset = Article.objects.all()
# serializer_class = ReversedArticleSerializer
#
# class ReversedReporterViewSet(ModelViewSet):
# queryset = Reporter.objects.all()
# serializer_class = ReversedReporterSerializer
#
# class ReversedTagViewSet(ModelViewSet):
# queryset = Tag.objects.all()
# serializer_class = ReversedTagSerializer
#
# class ReversedAccountViewSet(ModelViewSet):
# queryset = Account.objects.all()
# serializer_class = ReversedAccountSerializer
. Output only the next line. | router.register(r'reversed/accounts', ReversedAccountViewSet, base_name='reversedaccount') |
Here is a snippet: <|code_start|>
# Filters and permissions are declared in settings
class AccountViewSet(ModelViewSet):
queryset = Account.objects.all()
serializer_class = AccountSerializer
class ReporterViewSet(ModelViewSet):
<|code_end|>
. Write the next line using the current file imports:
from .mixins import ModelViewSet
from .models import Account, Reporter, Article, Tag
from .serializers import AccountSerializer, ReporterSerializer, ArticleSerializer, \
TagSerializer, ReversedReporterSerializer, ReversedArticleSerializer, \
ReversedTagSerializer, ReversedAccountSerializer
and context from other files:
# Path: examples/django_rest_framework/backend/backend/api/mixins.py
# class ModelViewSet(FilterByKeyMixin, viewsets.ModelViewSet):
# pass
#
# Path: examples/django_rest_framework/backend/backend/api/models.py
# class Account(models.Model):
# email = models.CharField(max_length=30)
#
# class Reporter(models.Model):
# account = models.OneToOneField(Account, related_name='reporter')
# first_name = models.CharField(max_length=30)
# last_name = models.CharField(max_length=30)
#
# class Article(models.Model):
# headline = models.CharField(max_length=100)
# pub_date = models.DateField()
# reporter = models.ForeignKey(Reporter, related_name='articles')
#
# class Tag(models.Model):
# label = models.CharField(max_length=30)
# articles = models.ManyToManyField(Article, related_name='tags')
, which may include functions, classes, or code. Output only the next line. | queryset = Reporter.objects.all() |
Using the snippet: <|code_start|>
# Filters and permissions are declared in settings
class AccountViewSet(ModelViewSet):
queryset = Account.objects.all()
serializer_class = AccountSerializer
class ReporterViewSet(ModelViewSet):
queryset = Reporter.objects.all()
serializer_class = ReporterSerializer
class ArticleViewSet(ModelViewSet):
<|code_end|>
, determine the next line of code. You have imports:
from .mixins import ModelViewSet
from .models import Account, Reporter, Article, Tag
from .serializers import AccountSerializer, ReporterSerializer, ArticleSerializer, \
TagSerializer, ReversedReporterSerializer, ReversedArticleSerializer, \
ReversedTagSerializer, ReversedAccountSerializer
and context (class names, function names, or code) available:
# Path: examples/django_rest_framework/backend/backend/api/mixins.py
# class ModelViewSet(FilterByKeyMixin, viewsets.ModelViewSet):
# pass
#
# Path: examples/django_rest_framework/backend/backend/api/models.py
# class Account(models.Model):
# email = models.CharField(max_length=30)
#
# class Reporter(models.Model):
# account = models.OneToOneField(Account, related_name='reporter')
# first_name = models.CharField(max_length=30)
# last_name = models.CharField(max_length=30)
#
# class Article(models.Model):
# headline = models.CharField(max_length=100)
# pub_date = models.DateField()
# reporter = models.ForeignKey(Reporter, related_name='articles')
#
# class Tag(models.Model):
# label = models.CharField(max_length=30)
# articles = models.ManyToManyField(Article, related_name='tags')
. Output only the next line. | queryset = Article.objects.all() |
Predict the next line after this snippet: <|code_start|>
# Filters and permissions are declared in settings
class AccountViewSet(ModelViewSet):
queryset = Account.objects.all()
serializer_class = AccountSerializer
class ReporterViewSet(ModelViewSet):
queryset = Reporter.objects.all()
serializer_class = ReporterSerializer
class ArticleViewSet(ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class TagViewSet(ModelViewSet):
<|code_end|>
using the current file's imports:
from .mixins import ModelViewSet
from .models import Account, Reporter, Article, Tag
from .serializers import AccountSerializer, ReporterSerializer, ArticleSerializer, \
TagSerializer, ReversedReporterSerializer, ReversedArticleSerializer, \
ReversedTagSerializer, ReversedAccountSerializer
and any relevant context from other files:
# Path: examples/django_rest_framework/backend/backend/api/mixins.py
# class ModelViewSet(FilterByKeyMixin, viewsets.ModelViewSet):
# pass
#
# Path: examples/django_rest_framework/backend/backend/api/models.py
# class Account(models.Model):
# email = models.CharField(max_length=30)
#
# class Reporter(models.Model):
# account = models.OneToOneField(Account, related_name='reporter')
# first_name = models.CharField(max_length=30)
# last_name = models.CharField(max_length=30)
#
# class Article(models.Model):
# headline = models.CharField(max_length=100)
# pub_date = models.DateField()
# reporter = models.ForeignKey(Reporter, related_name='articles')
#
# class Tag(models.Model):
# label = models.CharField(max_length=30)
# articles = models.ManyToManyField(Article, related_name='tags')
. Output only the next line. | queryset = Tag.objects.all() |
Given the code snippet: <|code_start|> return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
<|code_end|>
, generate the next line using the imports in this file:
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
and context (functions, classes, or occasionally code) from other files:
# Path: followup/models.py
# class ContactResult(models.Model):
# '''Abstract base model for representing the resolution to a followup
# attempt with a patient (e.g. no answer w/ voicemail).'''
#
# name = models.CharField(max_length=100, primary_key=True)
# attempt_again = models.BooleanField(
# default=False,
# help_text="True if outcome means the pt should be contacted again.")
# patient_reached = models.BooleanField(
# default=True,
# help_text="True if outcome means they reached the patient")
#
# def __str__(self):
# return self.name
#
# class NoAptReason(models.Model):
# '''Simple text-contiaining class for storing the different kinds of
# clinics a patient can be referred to (e.g. PCP, ortho, etc.)'''
#
# name = models.CharField(max_length=100, primary_key=True)
#
# def __str__(self):
# return self.name
#
# class NoShowReason(models.Model):
# '''Simple text-contiaining class for storing the different reasons a
# patient might not have gone to a scheduled appointment.'''
#
# name = models.CharField(max_length=100, primary_key=True)
#
# def __str__(self):
# return self.name
. Output only the next line. | ContactResult, |
Given snippet: <|code_start|>
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
and context:
# Path: followup/models.py
# class ContactResult(models.Model):
# '''Abstract base model for representing the resolution to a followup
# attempt with a patient (e.g. no answer w/ voicemail).'''
#
# name = models.CharField(max_length=100, primary_key=True)
# attempt_again = models.BooleanField(
# default=False,
# help_text="True if outcome means the pt should be contacted again.")
# patient_reached = models.BooleanField(
# default=True,
# help_text="True if outcome means they reached the patient")
#
# def __str__(self):
# return self.name
#
# class NoAptReason(models.Model):
# '''Simple text-contiaining class for storing the different kinds of
# clinics a patient can be referred to (e.g. PCP, ortho, etc.)'''
#
# name = models.CharField(max_length=100, primary_key=True)
#
# def __str__(self):
# return self.name
#
# class NoShowReason(models.Model):
# '''Simple text-contiaining class for storing the different reasons a
# patient might not have gone to a scheduled appointment.'''
#
# name = models.CharField(max_length=100, primary_key=True)
#
# def __str__(self):
# return self.name
which might include code, classes, or functions. Output only the next line. | NoAptReason, |
Given the code snippet: <|code_start|> PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
<|code_end|>
, generate the next line using the imports in this file:
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
and context (functions, classes, or occasionally code) from other files:
# Path: followup/models.py
# class ContactResult(models.Model):
# '''Abstract base model for representing the resolution to a followup
# attempt with a patient (e.g. no answer w/ voicemail).'''
#
# name = models.CharField(max_length=100, primary_key=True)
# attempt_again = models.BooleanField(
# default=False,
# help_text="True if outcome means the pt should be contacted again.")
# patient_reached = models.BooleanField(
# default=True,
# help_text="True if outcome means they reached the patient")
#
# def __str__(self):
# return self.name
#
# class NoAptReason(models.Model):
# '''Simple text-contiaining class for storing the different kinds of
# clinics a patient can be referred to (e.g. PCP, ortho, etc.)'''
#
# name = models.CharField(max_length=100, primary_key=True)
#
# def __str__(self):
# return self.name
#
# class NoShowReason(models.Model):
# '''Simple text-contiaining class for storing the different reasons a
# patient might not have gone to a scheduled appointment.'''
#
# name = models.CharField(max_length=100, primary_key=True)
#
# def __str__(self):
# return self.name
. Output only the next line. | NoShowReason, |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
def dashboard_dispatch(request):
"""Redirect an incoming user to the appropriate dashboard.
Falls back to the 'home' url.
"""
provider_type = request.session['clintype_pk']
dashboard_dispatch = settings.OSLER_PROVIDERTYPE_DASHBOARDS
if provider_type in dashboard_dispatch:
return redirect(dashboard_dispatch[provider_type])
else:
return redirect(settings.OSLER_DEFAULT_DASHBOARD)
def dashboard_attending(request):
provider = request.user.provider
<|code_end|>
with the help of current file imports:
from django.shortcuts import render, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.conf import settings
from workup.models import ClinicDate
from pttrack.models import Patient
and context from other files:
# Path: workup/models.py
# class ClinicDate(models.Model):
#
# class Meta(object):
# ordering = ["-clinic_date"]
#
# clinic_type = models.ForeignKey(ClinicType)
#
# clinic_date = models.DateField()
#
# def __str__(self):
# return (str(self.clinic_type) + " on " +
# datetime.datetime.strftime(self.clinic_date, '%A, %B %d, %Y'))
#
# def number_of_notes(self):
# return self.workup_set.count()
#
# def infer_attendings(self):
# qs = Provider.objects.filter(
# Q(attending_physician__clinic_day=self) |
# Q(signed_workups__clinic_day=self)).distinct()
#
# return qs
#
# def infer_volunteers(self):
# return Provider.objects.filter(Q(workup__clinic_day=self) |
# Q(other_volunteer__clinic_day=self)) \
# .distinct()
#
# def infer_coordinators(self):
# cd = self.clinic_date
#
# written_timeframe = (
# Q(actionitem__written_datetime__lte=cd) &
# Q(actionitem__written_datetime__gte=cd -
# datetime.timedelta(days=1))
# )
#
# cleared_timeframe = (
# Q(pttrack_actionitem_completed__completion_date__lte=cd) &
# Q(pttrack_actionitem_completed__completion_date__gte=cd -
# datetime.timedelta(days=1))
# )
#
# coordinator_set = Provider.objects \
# .filter(written_timeframe | cleared_timeframe)\
# .distinct()
#
# return coordinator_set
, which may contain function names, class names, or code. Output only the next line. | clinic_list = ClinicDate.objects.filter(workup__attending=provider) |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
class TestPatientContactForm(TestCase):
"""
Tests the beahvior of the PatientContactForm which has a lot of
complicated logic around valid form submission
"""
fixtures = ['pttrack']
def setUp(self):
""" Provides the same context in all the tests """
log_in_provider(self.client, build_provider())
<|code_end|>
, generate the next line using the imports in this file:
from builtins import zip
from django.test import TestCase
from itertools import *
from django.core.urlresolvers import reverse
from django.utils.timezone import now
from followup.models import (
ContactMethod, NoAptReason, NoShowReason, ContactResult)
from pttrack.models import (
Gender, Patient, Provider, ProviderType, ReferralType, ReferralLocation
)
from . import forms
from . import models
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
import datetime
and context (functions, classes, or occasionally code) from other files:
# Path: followup/models.py
# class NoShowReason(models.Model):
# class NoAptReason(models.Model):
# class ContactResult(models.Model):
# class Followup(Note):
# class Meta(object):
# class GeneralFollowup(Followup):
# class VaccineFollowup(Followup):
# class LabFollowup(Followup):
# class ReferralFollowup(Followup):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def type(self):
# def short_text(self):
# def attribution(self):
# def written_date(self):
# def __str__(self):
# def type(self):
# def short_text(self):
# def type(self):
# def short_text(self):
# def type(self):
# def short_text(self):
# SUBSQ_DOSE_HELP = "Has the patient committed to coming back for another dose?"
# DOSE_DATE_HELP = "When does the patient want to get their next dose (if applicable)?"
# CS_HELP = "Were you able to communicate the results?"
# REFTYPE_HELP = "What kind of provider was the patient referred to?"
# APP_HELP = "Where is the appointment?"
# PTSHOW_OPTS = [("Yes", "Yes"),
# ("No", "No"),
# ("Not yet", "Not yet")]
# PTSHOW_HELP = "Did the patient show up to the appointment?"
# NOAPT_HELP = "If the patient didn't make an appointment, why not?"
# NOSHOW_HELP = "If the patient didn't go to appointment, why not?"
. Output only the next line. | self.contact_method = ContactMethod.objects.create( |
Given snippet: <|code_start|> name='COH', address='Euclid Ave.')
refloc.care_availiable.add(reftype)
self.referral = models.Referral.objects.create(
comments="Needs his back checked",
status=models.Referral.STATUS_PENDING,
kind=reftype,
author=Provider.objects.first(),
author_type=ProviderType.objects.first(),
patient=self.pt
)
self.referral.location.add(refloc)
self.followup_request = models.FollowupRequest.objects.create(
referral=self.referral,
contact_instructions="Call him",
due_date=datetime.date(2018, 9, 0o1),
author=Provider.objects.first(),
author_type=ProviderType.objects.first(),
patient=self.pt
)
self.successful_res = ContactResult.objects.create(
name="Got him", patient_reached=True)
self.unsuccessful_res = ContactResult.objects.create(
name="Disaster", patient_reached=False)
# Need to update referral location
self.referral_location = ReferralLocation.objects.create(
name="Franklin's Back Adjustment",
address="1435 Sillypants Drive")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from builtins import zip
from django.test import TestCase
from itertools import *
from django.core.urlresolvers import reverse
from django.utils.timezone import now
from followup.models import (
ContactMethod, NoAptReason, NoShowReason, ContactResult)
from pttrack.models import (
Gender, Patient, Provider, ProviderType, ReferralType, ReferralLocation
)
from . import forms
from . import models
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
import datetime
and context:
# Path: followup/models.py
# class NoShowReason(models.Model):
# class NoAptReason(models.Model):
# class ContactResult(models.Model):
# class Followup(Note):
# class Meta(object):
# class GeneralFollowup(Followup):
# class VaccineFollowup(Followup):
# class LabFollowup(Followup):
# class ReferralFollowup(Followup):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def type(self):
# def short_text(self):
# def attribution(self):
# def written_date(self):
# def __str__(self):
# def type(self):
# def short_text(self):
# def type(self):
# def short_text(self):
# def type(self):
# def short_text(self):
# SUBSQ_DOSE_HELP = "Has the patient committed to coming back for another dose?"
# DOSE_DATE_HELP = "When does the patient want to get their next dose (if applicable)?"
# CS_HELP = "Were you able to communicate the results?"
# REFTYPE_HELP = "What kind of provider was the patient referred to?"
# APP_HELP = "Where is the appointment?"
# PTSHOW_OPTS = [("Yes", "Yes"),
# ("No", "No"),
# ("Not yet", "Not yet")]
# PTSHOW_HELP = "Did the patient show up to the appointment?"
# NOAPT_HELP = "If the patient didn't make an appointment, why not?"
# NOSHOW_HELP = "If the patient didn't go to appointment, why not?"
which might include code, classes, or functions. Output only the next line. | self.noapt_reason = NoAptReason.objects.create( |
Given the following code snippet before the placeholder: <|code_start|>
self.referral = models.Referral.objects.create(
comments="Needs his back checked",
status=models.Referral.STATUS_PENDING,
kind=reftype,
author=Provider.objects.first(),
author_type=ProviderType.objects.first(),
patient=self.pt
)
self.referral.location.add(refloc)
self.followup_request = models.FollowupRequest.objects.create(
referral=self.referral,
contact_instructions="Call him",
due_date=datetime.date(2018, 9, 0o1),
author=Provider.objects.first(),
author_type=ProviderType.objects.first(),
patient=self.pt
)
self.successful_res = ContactResult.objects.create(
name="Got him", patient_reached=True)
self.unsuccessful_res = ContactResult.objects.create(
name="Disaster", patient_reached=False)
# Need to update referral location
self.referral_location = ReferralLocation.objects.create(
name="Franklin's Back Adjustment",
address="1435 Sillypants Drive")
self.noapt_reason = NoAptReason.objects.create(
name="better things to do")
<|code_end|>
, predict the next line using imports from the current file:
from builtins import zip
from django.test import TestCase
from itertools import *
from django.core.urlresolvers import reverse
from django.utils.timezone import now
from followup.models import (
ContactMethod, NoAptReason, NoShowReason, ContactResult)
from pttrack.models import (
Gender, Patient, Provider, ProviderType, ReferralType, ReferralLocation
)
from . import forms
from . import models
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
import datetime
and context including class names, function names, and sometimes code from other files:
# Path: followup/models.py
# class NoShowReason(models.Model):
# class NoAptReason(models.Model):
# class ContactResult(models.Model):
# class Followup(Note):
# class Meta(object):
# class GeneralFollowup(Followup):
# class VaccineFollowup(Followup):
# class LabFollowup(Followup):
# class ReferralFollowup(Followup):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def type(self):
# def short_text(self):
# def attribution(self):
# def written_date(self):
# def __str__(self):
# def type(self):
# def short_text(self):
# def type(self):
# def short_text(self):
# def type(self):
# def short_text(self):
# SUBSQ_DOSE_HELP = "Has the patient committed to coming back for another dose?"
# DOSE_DATE_HELP = "When does the patient want to get their next dose (if applicable)?"
# CS_HELP = "Were you able to communicate the results?"
# REFTYPE_HELP = "What kind of provider was the patient referred to?"
# APP_HELP = "Where is the appointment?"
# PTSHOW_OPTS = [("Yes", "Yes"),
# ("No", "No"),
# ("Not yet", "Not yet")]
# PTSHOW_HELP = "Did the patient show up to the appointment?"
# NOAPT_HELP = "If the patient didn't make an appointment, why not?"
# NOSHOW_HELP = "If the patient didn't go to appointment, why not?"
. Output only the next line. | self.noshow_reason = NoShowReason.objects.create( |
Predict the next line after this snippet: <|code_start|> date_of_birth=datetime.date(1990, 0o1, 0o1),
patient_comfortable_with_english=False,
preferred_contact_method=self.contact_method,
)
reftype = ReferralType.objects.create(
name="Specialty", is_fqhc=False)
refloc = ReferralLocation.objects.create(
name='COH', address='Euclid Ave.')
refloc.care_availiable.add(reftype)
self.referral = models.Referral.objects.create(
comments="Needs his back checked",
status=models.Referral.STATUS_PENDING,
kind=reftype,
author=Provider.objects.first(),
author_type=ProviderType.objects.first(),
patient=self.pt
)
self.referral.location.add(refloc)
self.followup_request = models.FollowupRequest.objects.create(
referral=self.referral,
contact_instructions="Call him",
due_date=datetime.date(2018, 9, 0o1),
author=Provider.objects.first(),
author_type=ProviderType.objects.first(),
patient=self.pt
)
<|code_end|>
using the current file's imports:
from builtins import zip
from django.test import TestCase
from itertools import *
from django.core.urlresolvers import reverse
from django.utils.timezone import now
from followup.models import (
ContactMethod, NoAptReason, NoShowReason, ContactResult)
from pttrack.models import (
Gender, Patient, Provider, ProviderType, ReferralType, ReferralLocation
)
from . import forms
from . import models
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
from pttrack.test_views import log_in_provider, build_provider
import datetime
and any relevant context from other files:
# Path: followup/models.py
# class NoShowReason(models.Model):
# class NoAptReason(models.Model):
# class ContactResult(models.Model):
# class Followup(Note):
# class Meta(object):
# class GeneralFollowup(Followup):
# class VaccineFollowup(Followup):
# class LabFollowup(Followup):
# class ReferralFollowup(Followup):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def type(self):
# def short_text(self):
# def attribution(self):
# def written_date(self):
# def __str__(self):
# def type(self):
# def short_text(self):
# def type(self):
# def short_text(self):
# def type(self):
# def short_text(self):
# SUBSQ_DOSE_HELP = "Has the patient committed to coming back for another dose?"
# DOSE_DATE_HELP = "When does the patient want to get their next dose (if applicable)?"
# CS_HELP = "Were you able to communicate the results?"
# REFTYPE_HELP = "What kind of provider was the patient referred to?"
# APP_HELP = "Where is the appointment?"
# PTSHOW_OPTS = [("Yes", "Yes"),
# ("No", "No"),
# ("Not yet", "Not yet")]
# PTSHOW_HELP = "Did the patient show up to the appointment?"
# NOAPT_HELP = "If the patient didn't make an appointment, why not?"
# NOSHOW_HELP = "If the patient didn't go to appointment, why not?"
. Output only the next line. | self.successful_res = ContactResult.objects.create( |
Predict the next line for this snippet: <|code_start|> url(r'^(?P<pt_id>[0-9]+)/document/$',
views.DocumentCreate.as_view(),
name="new-document"),
url(r'^document/(?P<pk>[0-9]+)$',
DetailView.as_view(model=models.Document),
name="document-detail"),
url(r'^document/update/(?P<pk>[0-9]+)$',
views.DocumentUpdate.as_view(),
name="document-update"),
# MISC
url(r'^about/',
TemplateView.as_view(template_name='pttrack/about.html'),
name='about'),
]
def wrap_url(url, no_wrap=[], login_only=[], provider_only=[],
updated_provider_only=[]):
'''
Wrap URL in decorators as appropriate.
'''
if url.name in no_wrap:
# do not wrap at all, fully public
pass
elif url.name in login_only:
url.callback = login_required(url.callback)
elif url.name in provider_only:
<|code_end|>
with the help of current file imports:
from django.conf.urls import url
from django.views.generic import DetailView
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from .decorators import provider_required, clintype_required, \
provider_update_required
from . import models
from . import views
and context from other files:
# Path: pttrack/decorators.py
# def provider_required(func):
# return user_passes_test(provider_exists, login_url=reverse_lazy('new-provider'))(func)
#
# def clintype_required(func):
# return session_passes_test(clintype_set, fail_url=reverse_lazy('choose-clintype'))(func)
#
# def provider_update_required(func):
# return user_passes_test(provider_has_updated, login_url=reverse_lazy('provider-update'))(func)
, which may contain function names, class names, or code. Output only the next line. | url.callback = provider_required(url.callback) |
Given the code snippet: <|code_start|>
# MISC
url(r'^about/',
TemplateView.as_view(template_name='pttrack/about.html'),
name='about'),
]
def wrap_url(url, no_wrap=[], login_only=[], provider_only=[],
updated_provider_only=[]):
'''
Wrap URL in decorators as appropriate.
'''
if url.name in no_wrap:
# do not wrap at all, fully public
pass
elif url.name in login_only:
url.callback = login_required(url.callback)
elif url.name in provider_only:
url.callback = provider_required(url.callback)
url.callback = login_required(url.callback)
elif url.name in updated_provider_only:
url.callback = provider_update_required(url.callback)
url.callback = provider_required(url.callback)
url.callback = login_required(url.callback)
else: # wrap in everything
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import url
from django.views.generic import DetailView
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from .decorators import provider_required, clintype_required, \
provider_update_required
from . import models
from . import views
and context (functions, classes, or occasionally code) from other files:
# Path: pttrack/decorators.py
# def provider_required(func):
# return user_passes_test(provider_exists, login_url=reverse_lazy('new-provider'))(func)
#
# def clintype_required(func):
# return session_passes_test(clintype_set, fail_url=reverse_lazy('choose-clintype'))(func)
#
# def provider_update_required(func):
# return user_passes_test(provider_has_updated, login_url=reverse_lazy('provider-update'))(func)
. Output only the next line. | url.callback = clintype_required(url.callback) |
Given the following code snippet before the placeholder: <|code_start|> DetailView.as_view(model=models.Document),
name="document-detail"),
url(r'^document/update/(?P<pk>[0-9]+)$',
views.DocumentUpdate.as_view(),
name="document-update"),
# MISC
url(r'^about/',
TemplateView.as_view(template_name='pttrack/about.html'),
name='about'),
]
def wrap_url(url, no_wrap=[], login_only=[], provider_only=[],
updated_provider_only=[]):
'''
Wrap URL in decorators as appropriate.
'''
if url.name in no_wrap:
# do not wrap at all, fully public
pass
elif url.name in login_only:
url.callback = login_required(url.callback)
elif url.name in provider_only:
url.callback = provider_required(url.callback)
url.callback = login_required(url.callback)
elif url.name in updated_provider_only:
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import url
from django.views.generic import DetailView
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from .decorators import provider_required, clintype_required, \
provider_update_required
from . import models
from . import views
and context including class names, function names, and sometimes code from other files:
# Path: pttrack/decorators.py
# def provider_required(func):
# return user_passes_test(provider_exists, login_url=reverse_lazy('new-provider'))(func)
#
# def clintype_required(func):
# return session_passes_test(clintype_set, fail_url=reverse_lazy('choose-clintype'))(func)
#
# def provider_update_required(func):
# return user_passes_test(provider_has_updated, login_url=reverse_lazy('provider-update'))(func)
. Output only the next line. | url.callback = provider_update_required(url.callback) |
Using the snippet: <|code_start|>
unwrapped_urlconf = [ # pylint: disable=invalid-name
url(r'^(?P<pt_id>[0-9]+)/referral/$',
views.ReferralFollowupCreate.as_view(),
name='new-referral-followup'),
url(r'^(?P<pt_id>[0-9]+)/(?P<ftype>[\w]+)/$',
views.FollowupCreate.as_view(),
name='new-followup'),
url(r'^(?P<pt_id>[0-9]+)/$',
views.followup_choice,
name='followup-choice'),
url(r'^referral/(?P<pk>[0-9]+)/$',
views.ReferralFollowupUpdate.as_view(),
{"model": "Referral"},
name="followup"), # parameter 'model' to identify from others w/ name
url(r'^lab/(?P<pk>[0-9]+)/$',
views.LabFollowupUpdate.as_view(),
{"model": "Lab"},
name="followup"),
url(r'^vaccine/(?P<pk>[0-9]+)/$',
views.VaccineFollowupUpdate.as_view(),
{"model": "Vaccine"},
name="followup"),
url(r'^general/(?P<pk>[0-9]+)/$',
views.GeneralFollowupUpdate.as_view(),
{"model": "General"},
name="followup"),
]
wrap_config = {}
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import url
from pttrack.urls import wrap_url
from . import views
and context (class names, function names, or code) available:
# Path: pttrack/urls.py
# def wrap_url(url, no_wrap=[], login_only=[], provider_only=[],
# updated_provider_only=[]):
# '''
# Wrap URL in decorators as appropriate.
# '''
# if url.name in no_wrap:
# # do not wrap at all, fully public
# pass
#
# elif url.name in login_only:
# url.callback = login_required(url.callback)
#
# elif url.name in provider_only:
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# elif url.name in updated_provider_only:
# url.callback = provider_update_required(url.callback)
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# else: # wrap in everything
# url.callback = clintype_required(url.callback)
# url.callback = provider_update_required(url.callback)
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# return url
. Output only the next line. | urlpatterns = [wrap_url(url, **wrap_config) for url in unwrapped_urlconf] |
Using the snippet: <|code_start|>from __future__ import unicode_literals
unwrapped_urlconf = [
url(r'^dispatch/$',
views.dashboard_dispatch,
name='dashboard-dispatch'),
url(r'^attending/$',
views.dashboard_attending,
name='dashboard-attending'),
]
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import url
from pttrack.urls import wrap_url
from . import views
and context (class names, function names, or code) available:
# Path: pttrack/urls.py
# def wrap_url(url, no_wrap=[], login_only=[], provider_only=[],
# updated_provider_only=[]):
# '''
# Wrap URL in decorators as appropriate.
# '''
# if url.name in no_wrap:
# # do not wrap at all, fully public
# pass
#
# elif url.name in login_only:
# url.callback = login_required(url.callback)
#
# elif url.name in provider_only:
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# elif url.name in updated_provider_only:
# url.callback = provider_update_required(url.callback)
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# else: # wrap in everything
# url.callback = clintype_required(url.callback)
# url.callback = provider_update_required(url.callback)
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# return url
. Output only the next line. | urlpatterns = [wrap_url(u, **{}) for u in unwrapped_urlconf] |
Predict the next line after this snippet: <|code_start|>from __future__ import unicode_literals
def get_clindates():
'''Get the clinic dates associated with today.'''
clindates = models.ClinicDate.objects.filter(
clinic_date=now().date())
return clindates
def new_note_dispatch(request, pt_id):
note_types = {
'Standard Note': reverse("new-workup", args=(pt_id,)),
'Clinical Psychology Note': reverse("new-progress-note", args=(pt_id,)),
}
return render(request, 'workup/new-note-dispatch.html',
{'note_types': note_types})
<|code_end|>
using the current file's imports:
from builtins import str
from django.shortcuts import get_object_or_404, render
from django.http import (HttpResponseRedirect, HttpResponseServerError,
HttpResponse)
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template.loader import get_template
from django.utils.timezone import now
from django.views.generic.edit import FormView
from django.conf import settings
from pttrack.views import NoteFormView, NoteUpdate, get_current_provider_type
from pttrack.models import Patient, ProviderType
from xhtml2pdf import pisa
from . import models
from . import forms
from tempfile import TemporaryFile
and any relevant context from other files:
# Path: pttrack/views.py
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
. Output only the next line. | class WorkupCreate(NoteFormView): |
Given the code snippet: <|code_start|> wu_previous = pt.latest_workup()
if wu_previous is not None:
date_string = wu_previous.written_datetime.strftime("%B %d, %Y")
for field in settings.OSLER_WORKUP_COPY_FORWARD_FIELDS:
initial[field] = settings.OSLER_WORKUP_COPY_FORWARD_MESSAGE.\
format(date=date_string,
contents=getattr(wu_previous, field))
return initial
def form_valid(self, form):
pt = get_object_or_404(Patient, pk=self.kwargs['pt_id'])
active_provider_type = get_object_or_404(
ProviderType,
pk=self.request.session['clintype_pk'])
wu = form.save(commit=False)
wu.patient = pt
wu.author = self.request.user.provider
wu.author_type = get_current_provider_type(self.request)
if wu.author_type.signs_charts:
wu.sign(self.request.user, active_provider_type)
wu.save()
form.save_m2m()
return HttpResponseRedirect(reverse("patient-detail", args=(pt.id,)))
<|code_end|>
, generate the next line using the imports in this file:
from builtins import str
from django.shortcuts import get_object_or_404, render
from django.http import (HttpResponseRedirect, HttpResponseServerError,
HttpResponse)
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template.loader import get_template
from django.utils.timezone import now
from django.views.generic.edit import FormView
from django.conf import settings
from pttrack.views import NoteFormView, NoteUpdate, get_current_provider_type
from pttrack.models import Patient, ProviderType
from xhtml2pdf import pisa
from . import models
from . import forms
from tempfile import TemporaryFile
and context (functions, classes, or occasionally code) from other files:
# Path: pttrack/views.py
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
. Output only the next line. | class WorkupUpdate(NoteUpdate): |
Using the snippet: <|code_start|> 'done in the admin panel by a user with sufficient ',
'privileges (e.g. coordinator).')
def get_initial(self):
initial = super(WorkupCreate, self).get_initial()
pt = get_object_or_404(Patient, pk=self.kwargs['pt_id'])
# self.get() checks for >= 1 ClinicDay
initial['clinic_day'] = get_clindates().first()
initial['ros'] = "Default: reviewed and negative"
wu_previous = pt.latest_workup()
if wu_previous is not None:
date_string = wu_previous.written_datetime.strftime("%B %d, %Y")
for field in settings.OSLER_WORKUP_COPY_FORWARD_FIELDS:
initial[field] = settings.OSLER_WORKUP_COPY_FORWARD_MESSAGE.\
format(date=date_string,
contents=getattr(wu_previous, field))
return initial
def form_valid(self, form):
pt = get_object_or_404(Patient, pk=self.kwargs['pt_id'])
active_provider_type = get_object_or_404(
ProviderType,
pk=self.request.session['clintype_pk'])
wu = form.save(commit=False)
wu.patient = pt
wu.author = self.request.user.provider
<|code_end|>
, determine the next line of code. You have imports:
from builtins import str
from django.shortcuts import get_object_or_404, render
from django.http import (HttpResponseRedirect, HttpResponseServerError,
HttpResponse)
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template.loader import get_template
from django.utils.timezone import now
from django.views.generic.edit import FormView
from django.conf import settings
from pttrack.views import NoteFormView, NoteUpdate, get_current_provider_type
from pttrack.models import Patient, ProviderType
from xhtml2pdf import pisa
from . import models
from . import forms
from tempfile import TemporaryFile
and context (class names, function names, or code) available:
# Path: pttrack/views.py
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
. Output only the next line. | wu.author_type = get_current_provider_type(self.request) |
Here is a snippet: <|code_start|>from __future__ import unicode_literals
class Command(BaseCommand):
help = '''Email attendings when they have unattested workups.'''
def handle(self, *args, **options):
<|code_end|>
. Write the next line using the current file imports:
from builtins import str
from django.core.urlresolvers import reverse
from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from pttrack.models import Provider
from workup.models import Workup
and context from other files:
# Path: workup/models.py
# class Workup(AttestableNote):
# '''Datamodel of a workup. Has fields specific to each part of an exam,
# along with SNHC-specific info about where the patient has been referred for
# continuity care.'''
#
# attending = models.ForeignKey(
# Provider, null=True, blank=True, related_name="attending_physician",
# validators=[validate_attending],
# help_text="Which attending saw the patient?")
# other_volunteer = models.ManyToManyField(
# Provider, blank=True, related_name="other_volunteer",
# help_text="Which other volunteer(s) did you work with (if any)?")
#
# clinic_day = models.ForeignKey(
# ClinicDate, help_text="When was the patient seen?")
#
# chief_complaint = models.CharField(max_length=1000, verbose_name="CC")
# diagnosis = models.CharField(max_length=1000, verbose_name="Dx")
# diagnosis_categories = models.ManyToManyField(DiagnosisType)
#
# HPI = models.TextField(verbose_name="HPI")
# PMH_PSH = models.TextField(verbose_name="PMH/PSH")
# meds = models.TextField(verbose_name="Medications")
# allergies = models.TextField()
# fam_hx = models.TextField(verbose_name="Family History")
# soc_hx = models.TextField(verbose_name="Social History")
# ros = models.TextField(verbose_name="ROS")
#
# # represented internally in per min
# hr = models.PositiveSmallIntegerField(
# blank=True, null=True, verbose_name="Heart Rate")
#
# # represented internally as mmHg
# bp_sys = models.PositiveSmallIntegerField(
# blank=True, null=True, verbose_name="Systolic",
# validators=[workup_validators.validate_bp_systolic])
# bp_dia = models.PositiveSmallIntegerField(
# blank=True, null=True, verbose_name="Diastolic",
# validators=[workup_validators.validate_bp_diastolic])
#
# # represented internally in per min
# rr = models.PositiveSmallIntegerField(
# blank=True, null=True, verbose_name="Respiratory Rate")
#
# # represented internally in Fahrenheit
# t = models.DecimalField(
# max_digits=4, decimal_places=1,
# blank=True, null=True,
# verbose_name="Temperature")
#
# # represented internally as inches
# height = models.PositiveSmallIntegerField(
# blank=True, null=True)
# # represented internally as kg
# weight = models.DecimalField(
# max_digits=5, decimal_places=1,
# blank=True, null=True)
#
# pe = models.TextField(verbose_name="Physical Examination")
#
# labs_ordered_quest = models.TextField(
# blank=True, null=True, verbose_name="Labs Ordered from Quest")
# labs_ordered_internal = models.TextField(
# blank=True, null=True, verbose_name="Labs Ordered Internally")
#
# rx = models.TextField(blank=True, null=True,
# verbose_name="Prescription Orders")
#
# got_voucher = models.BooleanField(default=False)
# voucher_amount = models.DecimalField(
# max_digits=6, decimal_places=2, blank=True, null=True,
# validators=[MinValueValidator(0)])
# patient_pays = models.DecimalField(
# max_digits=6, decimal_places=2, blank=True, null=True,
# validators=[MinValueValidator(0)])
#
# got_imaging_voucher = models.BooleanField(default=False)
# imaging_voucher_amount = models.DecimalField(
# max_digits=6, decimal_places=2, blank=True, null=True,
# validators=[MinValueValidator(0)])
# patient_pays_imaging = models.DecimalField(
# max_digits=6, decimal_places=2, blank=True, null=True,
# validators=[MinValueValidator(0)])
#
# # Please note that these are no longer shown on the form and will not
# # be filled out because the referral app handles this functionality
# referral_type = models.ManyToManyField(ReferralType, blank=True)
# referral_location = models.ManyToManyField(ReferralLocation, blank=True)
#
# will_return = models.BooleanField(default=False,
# help_text="Will the pt. return to SNHC?")
#
# A_and_P = models.TextField()
#
# signer = models.ForeignKey(Provider,
# blank=True, null=True,
# related_name="signed_workups",
# validators=[validate_attending])
# signed_date = models.DateTimeField(blank=True, null=True)
#
# history = HistoricalRecords()
#
# def short_text(self):
# '''
# Return the 'short text' representation of this Note. In this case, it's
# simply the CC
# '''
# return self.chief_complaint
#
# # TODO: this is not consistent with the written datetime that we see for
# # the rest of the Note subclasses.
# def written_date(self):
# '''
# Returns the date (not datetime) this workup was written on.
# '''
# return self.clinic_day.clinic_date
#
# def url(self):
# return reverse('workup', args=(self.pk,))
#
# def __str__(self):
# return self.patient.name() + " on " + str(self.clinic_day.clinic_date)
, which may include functions, classes, or code. Output only the next line. | unsigned_wus = Workup.objects.filter(signer=None) |
Next line prediction: <|code_start|>from __future__ import unicode_literals
class AppointmentForm(ModelForm):
class Meta(object):
<|code_end|>
. Use current file imports:
(from builtins import object
from django.forms import ModelForm, TimeInput
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from bootstrap3_datetime.widgets import DateTimePicker
from .models import Appointment)
and context including class names, function names, or small code snippets from other files:
# Path: appointment/models.py
# class Appointment(Note):
#
# class Meta(object):
# ordering = ["-clindate", "-clintime"]
#
# PSYCH_NIGHT = 'PSYCH_NIGHT'
# ACUTE_FOLLOWUP = 'ACUTE_FOLLOWUP'
# CHRONIC_CARE = 'CHRONIC_CARE'
# VACCINE = 'VACCINE'
# APPOINTMENT_TYPES = (
# (PSYCH_NIGHT, 'Psych Night'),
# (ACUTE_FOLLOWUP, 'Acute Followup'),
# (CHRONIC_CARE, 'Chronic Care'),
# (VACCINE, "Vaccine Followup")
# )
#
# clindate = models.DateField(verbose_name="Appointment Date")
# clintime = models.TimeField(
# verbose_name="Time of Appointment",
# default=generate_default_appointment_time)
# appointment_type = models.CharField(
# max_length=15, choices=APPOINTMENT_TYPES,
# verbose_name='Appointment Type', default=CHRONIC_CARE)
# comment = models.TextField(
# help_text="What should happen at this appointment?")
#
# pt_showed = models.NullBooleanField(
# verbose_name="Patient Showed",
# blank=True, help_text="Did the patient come to this appointment?")
#
# history = HistoricalRecords()
#
# def __str__(self):
# return "Appointment ({type}) for {name} on {date}".format(
# type=self.verbose_appointment_type(),
# name=self.patient.name(),
# date=str(self.clindate))
#
# def verbose_appointment_type(self):
# appointment_type_index = list(zip(*self.APPOINTMENT_TYPES))[0].index(
# self.appointment_type)
#
# return self.APPOINTMENT_TYPES[appointment_type_index][1]
#
# def clean(self):
# ids = Appointment.objects.filter(clindate=self.clindate).\
# values_list('id', flat=True)
#
# if (ids.count() >= settings.OSLER_MAX_APPOINTMENTS and
# self.id not in ids):
# raise ValidationError(
# "Osler is configured only to allow %s appointments per day" %
# settings.OSLER_MAX_APPOINTMENTS)
. Output only the next line. | model = Appointment |
Continue the code snippet: <|code_start|> url(r'^(?P<pk>[0-9]+)/error/$',
views.error_workup,
name="workup-error"),
url(r'^(?P<pk>[0-9]+)/pdf/$',
views.pdf_workup,
name="workup-pdf"),
# PROGRESS NOTES
url(r'^(?P<pt_id>[0-9]+)/psychnote/$',
views.ProgressNoteCreate.as_view(),
name="new-progress-note"),
url(r'^psychnote/update/(?P<pk>[0-9]+)$',
views.ProgressNoteUpdate.as_view(),
name="progress-note-update"),
url(r'^psychnote/sign/(?P<pk>[0-9]+)$',
views.sign_progress_note,
name='progress-note-sign'),
url(r'^psychnote/(?P<pk>[0-9]+)$',
DetailView.as_view(model=models.ProgressNote),
name="progress-note-detail"),
url(r'^(?P<pt_id>[0-9]+)/clindate/$',
views.ClinicDateCreate.as_view(),
name="new-clindate"),
url(r'^clindates/$',
views.clinic_date_list,
name="clindate-list")
]
wrap_config = {}
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from pttrack.urls import wrap_url
from django.views.generic import DetailView
from . import models
from . import views
and context (classes, functions, or code) from other files:
# Path: pttrack/urls.py
# def wrap_url(url, no_wrap=[], login_only=[], provider_only=[],
# updated_provider_only=[]):
# '''
# Wrap URL in decorators as appropriate.
# '''
# if url.name in no_wrap:
# # do not wrap at all, fully public
# pass
#
# elif url.name in login_only:
# url.callback = login_required(url.callback)
#
# elif url.name in provider_only:
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# elif url.name in updated_provider_only:
# url.callback = provider_update_required(url.callback)
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# else: # wrap in everything
# url.callback = clintype_required(url.callback)
# url.callback = provider_update_required(url.callback)
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# return url
. Output only the next line. | urlpatterns = [wrap_url(url, **wrap_config) for url in unwrapped_urlconf] |
Using the snippet: <|code_start|>from __future__ import unicode_literals
def apt_dict():
apt = {'clindate': now().date(),
'clintime': time(9, 0),
'appointment_type': 'PSYCH_NIGHT',
'comment': 'stuff',
'author': Provider.objects.first(),
'author_type': ProviderType.objects.first(),
'patient': Patient.objects.first().id}
return(apt)
class TestAppointmentForm(TestCase):
fixtures = ['pttrack.json']
def setUp(self):
apt = apt_dict()
self.apt = apt
<|code_end|>
, determine the next line of code. You have imports:
from django.test import TestCase
from django.utils.timezone import now
from pttrack.models import Provider, ProviderType, Patient
from datetime import time
from .forms import AppointmentForm
and context (class names, function names, or code) available:
# Path: appointment/forms.py
# class AppointmentForm(ModelForm):
#
# class Meta(object):
# model = Appointment
# fields = ['clindate', 'clintime', 'appointment_type', 'comment',
# 'patient']
#
# widgets = {
# 'clindate': DateTimePicker(options={"format": "YYYY-MM-DD"}),
# 'clintime': TimeInput(format='%H:%M')}
#
# def __init__(self, *args, **kwargs):
# super(AppointmentForm, self).__init__(*args, **kwargs)
# self.helper = FormHelper(self)
# self.helper.add_input(Submit('submit', 'Submit'))
. Output only the next line. | form = AppointmentForm(data=apt) |
Based on the snippet: <|code_start|>from __future__ import unicode_literals
class TestAppointmentViews(TestCase):
fixtures = ['pttrack', 'workup']
def setUp(self):
self.all_roles_provider = build_provider()
log_in_provider(self.client, self.all_roles_provider)
self.apt = models.Appointment.objects.create(
comment='test this stuff',
clindate=now().date(),
clintime=time(9, 0),
appointment_type='PSYCH_NIGHT',
author=Provider.objects.first(),
author_type=ProviderType.objects.filter(signs_charts=False).first(),
patient=Patient.objects.first())
def test_new_appointment_view(self):
# Getting to new appointment view
response = self.client.get(reverse("appointment-new"))
self.assertEqual(response.status_code, 200)
# Posting new appointment
<|code_end|>
, predict the immediate next line with the help of imports:
from builtins import range
from datetime import timedelta, time
from django.test import TestCase
from django.utils.timezone import now
from django.core.urlresolvers import reverse
from pttrack.models import Provider, ProviderType, Patient
from pttrack.test_views import log_in_provider, build_provider
from .test_forms import apt_dict
from . import models
import re
and context (classes, functions, sometimes code) from other files:
# Path: appointment/test_forms.py
# def apt_dict():
# apt = {'clindate': now().date(),
# 'clintime': time(9, 0),
# 'appointment_type': 'PSYCH_NIGHT',
# 'comment': 'stuff',
# 'author': Provider.objects.first(),
# 'author_type': ProviderType.objects.first(),
# 'patient': Patient.objects.first().id}
#
# return(apt)
. Output only the next line. | response = self.client.post(reverse("appointment-new"), data=apt_dict()) |
Using the snippet: <|code_start|>from __future__ import unicode_literals
def followup_choice(request, pt_id):
'''Prompt the user to choose a follow up type.'''
pt = get_object_or_404(Patient, pk=pt_id)
return render(request, 'pttrack/followup-choice.html', {'patient': pt})
<|code_end|>
, determine the next line of code. You have imports:
from django.shortcuts import get_object_or_404, render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from pttrack.models import Patient
from pttrack.views import NoteUpdate, NoteFormView, get_current_provider_type
from . import forms
from . import models
and context (class names, function names, or code) available:
# Path: pttrack/views.py
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
. Output only the next line. | class FollowupUpdate(NoteUpdate): |
Given the code snippet: <|code_start|>
def get_success_url(self):
pt = self.object.patient
return reverse("patient-detail", args=(pt.id, ))
class ReferralFollowupUpdate(FollowupUpdate):
model = models.ReferralFollowup
form_class = forms.ReferralFollowup
note_type = "Referral Followup"
class LabFollowupUpdate(FollowupUpdate):
model = models.LabFollowup
form_class = forms.LabFollowup
note_type = "Lab Followup"
class VaccineFollowupUpdate(FollowupUpdate):
model = models.VaccineFollowup
form_class = forms.VaccineFollowup
note_type = "Vaccine Followup"
class GeneralFollowupUpdate(FollowupUpdate):
model = models.GeneralFollowup
form_class = forms.GeneralFollowup
note_type = "General Followup"
<|code_end|>
, generate the next line using the imports in this file:
from django.shortcuts import get_object_or_404, render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from pttrack.models import Patient
from pttrack.views import NoteUpdate, NoteFormView, get_current_provider_type
from . import forms
from . import models
and context (functions, classes, or occasionally code) from other files:
# Path: pttrack/views.py
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
. Output only the next line. | class FollowupCreate(NoteFormView): |
Given the code snippet: <|code_start|>
class FollowupCreate(NoteFormView):
'''A view for creating a new Followup'''
template_name = 'pttrack/form_submission.html'
note_type = "Followup"
def get_form_class(self, **kwargs):
ftype = self.kwargs['ftype']
futypes = {'labs': forms.LabFollowup,
'vaccine': forms.VaccineFollowup,
'general': forms.GeneralFollowup}
return futypes[ftype]
def get_followup_model(self):
'''Get the subtype of Followup model used by the FollowupForm used by
this FollowupCreate view.'''
# I have no idea if this is the right way to do this. It seems a bit
# dirty.
return self.get_form_class().Meta.model
def form_valid(self, form):
pt = get_object_or_404(Patient, pk=self.kwargs['pt_id'])
fu = form.save(commit=False)
fu.patient = pt
fu.author = self.request.user.provider
<|code_end|>
, generate the next line using the imports in this file:
from django.shortcuts import get_object_or_404, render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from pttrack.models import Patient
from pttrack.views import NoteUpdate, NoteFormView, get_current_provider_type
from . import forms
from . import models
and context (functions, classes, or occasionally code) from other files:
# Path: pttrack/views.py
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
. Output only the next line. | fu.author_type = get_current_provider_type(self.request) |
Here is a snippet: <|code_start|> raise ValueError(
"Provider {p} doesn't have role {r}!".format(
p=user.provider, r=active_role))
if active_role.signs_charts:
assert active_role in user.provider.clinical_roles.all()
self.signed_date = now()
self.signer = user.provider
else:
raise ValueError("You must be an attending to sign workups.")
def signed(self):
'''Has this workup been attested? Returns True if yes, False if no.'''
return self.signer is not None
def attribution(self):
'''Builds an attribution string of the form Doe, John on DATE'''
return " ".join([str(self.author), "on", str(self.written_date())])
class ProgressNote(AttestableNote):
title = models.CharField(max_length=200)
text = models.TextField()
history = HistoricalRecords()
signer = models.ForeignKey(Provider,
blank=True, null=True,
related_name="signed_progress_notes",
<|code_end|>
. Write the next line using the current file imports:
from builtins import str
from builtins import object
from django.db import models
from django.db.models import Q
from django.utils.timezone import now
from simple_history.models import HistoricalRecords
from django.core.urlresolvers import reverse
from django.core.validators import MinValueValidator
from pttrack.models import Note, Provider, ReferralLocation, ReferralType
from pttrack.validators import validate_attending
from . import validators as workup_validators
import datetime
and context from other files:
# Path: pttrack/validators.py
# def validate_attending(value):
# '''
# Verify that a provider has attending priviledges.
# '''
#
# Provider = apps.get_model('pttrack', 'Provider')
# attending = Provider.objects.get(pk=value)
#
# if not attending.clinical_roles.filter(signs_charts=True).exists():
# raise ValidationError("This provider is not allowed to sign charts.")
, which may include functions, classes, or code. Output only the next line. | validators=[validate_attending]) |
Predict the next line after this snippet: <|code_start|> """Mark a patient as having not shown to an appointment
"""
apt = get_object_or_404(Appointment, pk=pk)
apt.pt_showed = False
apt.save()
return HttpResponseRedirect(reverse("appointment-list"))
def mark_arrived(request, pk):
"""Mark a patient as having arrived to an appointment
"""
apt = get_object_or_404(Appointment, pk=pk)
apt.pt_showed = True
apt.save()
return HttpResponseRedirect(reverse("patient-update", args=(apt.patient.pk,)))
class AppointmentUpdate(NoteUpdate):
template_name = "pttrack/form-update.html"
model = Appointment
form_class = AppointmentForm
note_type = "Appointment"
success_url = "/appointment/list"
<|code_end|>
using the current file's imports:
import collections
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404, HttpResponseRedirect
from django.utils.timezone import now
from pttrack.views import NoteFormView, NoteUpdate, get_current_provider_type
from pttrack.models import Patient
from .models import Appointment
from .forms import AppointmentForm
and any relevant context from other files:
# Path: pttrack/views.py
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
#
# Path: appointment/models.py
# class Appointment(Note):
#
# class Meta(object):
# ordering = ["-clindate", "-clintime"]
#
# PSYCH_NIGHT = 'PSYCH_NIGHT'
# ACUTE_FOLLOWUP = 'ACUTE_FOLLOWUP'
# CHRONIC_CARE = 'CHRONIC_CARE'
# VACCINE = 'VACCINE'
# APPOINTMENT_TYPES = (
# (PSYCH_NIGHT, 'Psych Night'),
# (ACUTE_FOLLOWUP, 'Acute Followup'),
# (CHRONIC_CARE, 'Chronic Care'),
# (VACCINE, "Vaccine Followup")
# )
#
# clindate = models.DateField(verbose_name="Appointment Date")
# clintime = models.TimeField(
# verbose_name="Time of Appointment",
# default=generate_default_appointment_time)
# appointment_type = models.CharField(
# max_length=15, choices=APPOINTMENT_TYPES,
# verbose_name='Appointment Type', default=CHRONIC_CARE)
# comment = models.TextField(
# help_text="What should happen at this appointment?")
#
# pt_showed = models.NullBooleanField(
# verbose_name="Patient Showed",
# blank=True, help_text="Did the patient come to this appointment?")
#
# history = HistoricalRecords()
#
# def __str__(self):
# return "Appointment ({type}) for {name} on {date}".format(
# type=self.verbose_appointment_type(),
# name=self.patient.name(),
# date=str(self.clindate))
#
# def verbose_appointment_type(self):
# appointment_type_index = list(zip(*self.APPOINTMENT_TYPES))[0].index(
# self.appointment_type)
#
# return self.APPOINTMENT_TYPES[appointment_type_index][1]
#
# def clean(self):
# ids = Appointment.objects.filter(clindate=self.clindate).\
# values_list('id', flat=True)
#
# if (ids.count() >= settings.OSLER_MAX_APPOINTMENTS and
# self.id not in ids):
# raise ValidationError(
# "Osler is configured only to allow %s appointments per day" %
# settings.OSLER_MAX_APPOINTMENTS)
#
# Path: appointment/forms.py
# class AppointmentForm(ModelForm):
#
# class Meta(object):
# model = Appointment
# fields = ['clindate', 'clintime', 'appointment_type', 'comment',
# 'patient']
#
# widgets = {
# 'clindate': DateTimePicker(options={"format": "YYYY-MM-DD"}),
# 'clintime': TimeInput(format='%H:%M')}
#
# def __init__(self, *args, **kwargs):
# super(AppointmentForm, self).__init__(*args, **kwargs)
# self.helper = FormHelper(self)
# self.helper.add_input(Submit('submit', 'Submit'))
. Output only the next line. | class AppointmentCreate(NoteFormView): |
Given the following code snippet before the placeholder: <|code_start|> else:
d[a.clindate] = [a]
return render(request, 'appointment/appointment_list.html',
{'appointments_by_date': d})
def mark_no_show(request, pk):
"""Mark a patient as having not shown to an appointment
"""
apt = get_object_or_404(Appointment, pk=pk)
apt.pt_showed = False
apt.save()
return HttpResponseRedirect(reverse("appointment-list"))
def mark_arrived(request, pk):
"""Mark a patient as having arrived to an appointment
"""
apt = get_object_or_404(Appointment, pk=pk)
apt.pt_showed = True
apt.save()
return HttpResponseRedirect(reverse("patient-update", args=(apt.patient.pk,)))
<|code_end|>
, predict the next line using imports from the current file:
import collections
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404, HttpResponseRedirect
from django.utils.timezone import now
from pttrack.views import NoteFormView, NoteUpdate, get_current_provider_type
from pttrack.models import Patient
from .models import Appointment
from .forms import AppointmentForm
and context including class names, function names, and sometimes code from other files:
# Path: pttrack/views.py
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
#
# Path: appointment/models.py
# class Appointment(Note):
#
# class Meta(object):
# ordering = ["-clindate", "-clintime"]
#
# PSYCH_NIGHT = 'PSYCH_NIGHT'
# ACUTE_FOLLOWUP = 'ACUTE_FOLLOWUP'
# CHRONIC_CARE = 'CHRONIC_CARE'
# VACCINE = 'VACCINE'
# APPOINTMENT_TYPES = (
# (PSYCH_NIGHT, 'Psych Night'),
# (ACUTE_FOLLOWUP, 'Acute Followup'),
# (CHRONIC_CARE, 'Chronic Care'),
# (VACCINE, "Vaccine Followup")
# )
#
# clindate = models.DateField(verbose_name="Appointment Date")
# clintime = models.TimeField(
# verbose_name="Time of Appointment",
# default=generate_default_appointment_time)
# appointment_type = models.CharField(
# max_length=15, choices=APPOINTMENT_TYPES,
# verbose_name='Appointment Type', default=CHRONIC_CARE)
# comment = models.TextField(
# help_text="What should happen at this appointment?")
#
# pt_showed = models.NullBooleanField(
# verbose_name="Patient Showed",
# blank=True, help_text="Did the patient come to this appointment?")
#
# history = HistoricalRecords()
#
# def __str__(self):
# return "Appointment ({type}) for {name} on {date}".format(
# type=self.verbose_appointment_type(),
# name=self.patient.name(),
# date=str(self.clindate))
#
# def verbose_appointment_type(self):
# appointment_type_index = list(zip(*self.APPOINTMENT_TYPES))[0].index(
# self.appointment_type)
#
# return self.APPOINTMENT_TYPES[appointment_type_index][1]
#
# def clean(self):
# ids = Appointment.objects.filter(clindate=self.clindate).\
# values_list('id', flat=True)
#
# if (ids.count() >= settings.OSLER_MAX_APPOINTMENTS and
# self.id not in ids):
# raise ValidationError(
# "Osler is configured only to allow %s appointments per day" %
# settings.OSLER_MAX_APPOINTMENTS)
#
# Path: appointment/forms.py
# class AppointmentForm(ModelForm):
#
# class Meta(object):
# model = Appointment
# fields = ['clindate', 'clintime', 'appointment_type', 'comment',
# 'patient']
#
# widgets = {
# 'clindate': DateTimePicker(options={"format": "YYYY-MM-DD"}),
# 'clintime': TimeInput(format='%H:%M')}
#
# def __init__(self, *args, **kwargs):
# super(AppointmentForm, self).__init__(*args, **kwargs)
# self.helper = FormHelper(self)
# self.helper.add_input(Submit('submit', 'Submit'))
. Output only the next line. | class AppointmentUpdate(NoteUpdate): |
Predict the next line after this snippet: <|code_start|>
def mark_arrived(request, pk):
"""Mark a patient as having arrived to an appointment
"""
apt = get_object_or_404(Appointment, pk=pk)
apt.pt_showed = True
apt.save()
return HttpResponseRedirect(reverse("patient-update", args=(apt.patient.pk,)))
class AppointmentUpdate(NoteUpdate):
template_name = "pttrack/form-update.html"
model = Appointment
form_class = AppointmentForm
note_type = "Appointment"
success_url = "/appointment/list"
class AppointmentCreate(NoteFormView):
template_name = 'appointment/form_submission.html'
note_type = "Appointment"
form_class = AppointmentForm
success_url = "list"
def form_valid(self, form):
appointment = form.save(commit=False)
appointment.author = self.request.user.provider
<|code_end|>
using the current file's imports:
import collections
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404, HttpResponseRedirect
from django.utils.timezone import now
from pttrack.views import NoteFormView, NoteUpdate, get_current_provider_type
from pttrack.models import Patient
from .models import Appointment
from .forms import AppointmentForm
and any relevant context from other files:
# Path: pttrack/views.py
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
#
# Path: appointment/models.py
# class Appointment(Note):
#
# class Meta(object):
# ordering = ["-clindate", "-clintime"]
#
# PSYCH_NIGHT = 'PSYCH_NIGHT'
# ACUTE_FOLLOWUP = 'ACUTE_FOLLOWUP'
# CHRONIC_CARE = 'CHRONIC_CARE'
# VACCINE = 'VACCINE'
# APPOINTMENT_TYPES = (
# (PSYCH_NIGHT, 'Psych Night'),
# (ACUTE_FOLLOWUP, 'Acute Followup'),
# (CHRONIC_CARE, 'Chronic Care'),
# (VACCINE, "Vaccine Followup")
# )
#
# clindate = models.DateField(verbose_name="Appointment Date")
# clintime = models.TimeField(
# verbose_name="Time of Appointment",
# default=generate_default_appointment_time)
# appointment_type = models.CharField(
# max_length=15, choices=APPOINTMENT_TYPES,
# verbose_name='Appointment Type', default=CHRONIC_CARE)
# comment = models.TextField(
# help_text="What should happen at this appointment?")
#
# pt_showed = models.NullBooleanField(
# verbose_name="Patient Showed",
# blank=True, help_text="Did the patient come to this appointment?")
#
# history = HistoricalRecords()
#
# def __str__(self):
# return "Appointment ({type}) for {name} on {date}".format(
# type=self.verbose_appointment_type(),
# name=self.patient.name(),
# date=str(self.clindate))
#
# def verbose_appointment_type(self):
# appointment_type_index = list(zip(*self.APPOINTMENT_TYPES))[0].index(
# self.appointment_type)
#
# return self.APPOINTMENT_TYPES[appointment_type_index][1]
#
# def clean(self):
# ids = Appointment.objects.filter(clindate=self.clindate).\
# values_list('id', flat=True)
#
# if (ids.count() >= settings.OSLER_MAX_APPOINTMENTS and
# self.id not in ids):
# raise ValidationError(
# "Osler is configured only to allow %s appointments per day" %
# settings.OSLER_MAX_APPOINTMENTS)
#
# Path: appointment/forms.py
# class AppointmentForm(ModelForm):
#
# class Meta(object):
# model = Appointment
# fields = ['clindate', 'clintime', 'appointment_type', 'comment',
# 'patient']
#
# widgets = {
# 'clindate': DateTimePicker(options={"format": "YYYY-MM-DD"}),
# 'clintime': TimeInput(format='%H:%M')}
#
# def __init__(self, *args, **kwargs):
# super(AppointmentForm, self).__init__(*args, **kwargs)
# self.helper = FormHelper(self)
# self.helper.add_input(Submit('submit', 'Submit'))
. Output only the next line. | appointment.author_type = get_current_provider_type(self.request) |
Continue the code snippet: <|code_start|> return render(request, 'appointment/appointment_list.html',
{'appointments_by_date': d})
def mark_no_show(request, pk):
"""Mark a patient as having not shown to an appointment
"""
apt = get_object_or_404(Appointment, pk=pk)
apt.pt_showed = False
apt.save()
return HttpResponseRedirect(reverse("appointment-list"))
def mark_arrived(request, pk):
"""Mark a patient as having arrived to an appointment
"""
apt = get_object_or_404(Appointment, pk=pk)
apt.pt_showed = True
apt.save()
return HttpResponseRedirect(reverse("patient-update", args=(apt.patient.pk,)))
class AppointmentUpdate(NoteUpdate):
template_name = "pttrack/form-update.html"
model = Appointment
<|code_end|>
. Use current file imports:
import collections
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404, HttpResponseRedirect
from django.utils.timezone import now
from pttrack.views import NoteFormView, NoteUpdate, get_current_provider_type
from pttrack.models import Patient
from .models import Appointment
from .forms import AppointmentForm
and context (classes, functions, or code) from other files:
# Path: pttrack/views.py
# class NoteFormView(FormView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type and patient into the context.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteCreate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteFormView, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# if 'pt_id' in self.kwargs:
# context['patient'] = mymodels.Patient.objects. \
# get(pk=self.kwargs['pt_id'])
#
# return context
#
# class NoteUpdate(UpdateView):
# note_type = None
#
# def get_context_data(self, **kwargs):
# '''Inject self.note_type as the note type.'''
#
# if self.note_type is None:
# raise ImproperlyConfigured("NoteUpdate view must have" +
# "'note_type' variable set.")
#
# context = super(NoteUpdate, self).get_context_data(**kwargs)
# context['note_type'] = self.note_type
#
# return context
#
# # TODO: add shared form_valid code here from all subclasses.
#
# def get_current_provider_type(request):
# '''
# Given the request, produce the ProviderType of the logged in user. This is
# done using session data.
# '''
# return get_object_or_404(mymodels.ProviderType,
# pk=request.session['clintype_pk'])
#
# Path: appointment/models.py
# class Appointment(Note):
#
# class Meta(object):
# ordering = ["-clindate", "-clintime"]
#
# PSYCH_NIGHT = 'PSYCH_NIGHT'
# ACUTE_FOLLOWUP = 'ACUTE_FOLLOWUP'
# CHRONIC_CARE = 'CHRONIC_CARE'
# VACCINE = 'VACCINE'
# APPOINTMENT_TYPES = (
# (PSYCH_NIGHT, 'Psych Night'),
# (ACUTE_FOLLOWUP, 'Acute Followup'),
# (CHRONIC_CARE, 'Chronic Care'),
# (VACCINE, "Vaccine Followup")
# )
#
# clindate = models.DateField(verbose_name="Appointment Date")
# clintime = models.TimeField(
# verbose_name="Time of Appointment",
# default=generate_default_appointment_time)
# appointment_type = models.CharField(
# max_length=15, choices=APPOINTMENT_TYPES,
# verbose_name='Appointment Type', default=CHRONIC_CARE)
# comment = models.TextField(
# help_text="What should happen at this appointment?")
#
# pt_showed = models.NullBooleanField(
# verbose_name="Patient Showed",
# blank=True, help_text="Did the patient come to this appointment?")
#
# history = HistoricalRecords()
#
# def __str__(self):
# return "Appointment ({type}) for {name} on {date}".format(
# type=self.verbose_appointment_type(),
# name=self.patient.name(),
# date=str(self.clindate))
#
# def verbose_appointment_type(self):
# appointment_type_index = list(zip(*self.APPOINTMENT_TYPES))[0].index(
# self.appointment_type)
#
# return self.APPOINTMENT_TYPES[appointment_type_index][1]
#
# def clean(self):
# ids = Appointment.objects.filter(clindate=self.clindate).\
# values_list('id', flat=True)
#
# if (ids.count() >= settings.OSLER_MAX_APPOINTMENTS and
# self.id not in ids):
# raise ValidationError(
# "Osler is configured only to allow %s appointments per day" %
# settings.OSLER_MAX_APPOINTMENTS)
#
# Path: appointment/forms.py
# class AppointmentForm(ModelForm):
#
# class Meta(object):
# model = Appointment
# fields = ['clindate', 'clintime', 'appointment_type', 'comment',
# 'patient']
#
# widgets = {
# 'clindate': DateTimePicker(options={"format": "YYYY-MM-DD"}),
# 'clintime': TimeInput(format='%H:%M')}
#
# def __init__(self, *args, **kwargs):
# super(AppointmentForm, self).__init__(*args, **kwargs)
# self.helper = FormHelper(self)
# self.helper.add_input(Submit('submit', 'Submit'))
. Output only the next line. | form_class = AppointmentForm |
Using the snippet: <|code_start|>from __future__ import unicode_literals
# pylint: disable=I0011
unwrapped_urlpatterns = [ # pylint: disable=invalid-name
url(r'^pt_list/$',
views.PtList.as_view(),
name='pt_list_api'),
]
wrap_config = {}
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import url
from pttrack.urls import wrap_url
from . import views
from rest_framework.urlpatterns import format_suffix_patterns
and context (class names, function names, or code) available:
# Path: pttrack/urls.py
# def wrap_url(url, no_wrap=[], login_only=[], provider_only=[],
# updated_provider_only=[]):
# '''
# Wrap URL in decorators as appropriate.
# '''
# if url.name in no_wrap:
# # do not wrap at all, fully public
# pass
#
# elif url.name in login_only:
# url.callback = login_required(url.callback)
#
# elif url.name in provider_only:
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# elif url.name in updated_provider_only:
# url.callback = provider_update_required(url.callback)
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# else: # wrap in everything
# url.callback = clintype_required(url.callback)
# url.callback = provider_update_required(url.callback)
# url.callback = provider_required(url.callback)
# url.callback = login_required(url.callback)
#
# return url
. Output only the next line. | urlpatterns = [wrap_url(url, **wrap_config) for url in unwrapped_urlpatterns] |
Using the snippet: <|code_start|>
template_name = 'demographics/demographics-create.html'
form_class = DemographicsForm
def get_context_data(self, **kwargs):
context = super(DemographicsCreate, self).get_context_data(**kwargs)
if 'pt_id' in self.kwargs:
context['patient'] = Patient.objects.get(pk=self.kwargs['pt_id'])
return context
def form_valid(self, form):
pt = get_object_or_404(Patient, pk=self.kwargs['pt_id'])
dg = form.save(commit=False)
dg.creation_date = datetime.date.today()
dg.patient = pt
try:
with transaction.atomic():
dg.save()
pt.save()
form.save_m2m()
form.save()
return HttpResponseRedirect(reverse("patient-detail",
args=(pt.id,)))
except IntegrityError:
# Create form object containing data from current entry in database
<|code_end|>
, determine the next line of code. You have imports:
import datetime
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView, UpdateView
from django.core.urlresolvers import reverse
from django.db import IntegrityError, transaction
from django.forms.models import model_to_dict
from django.shortcuts import render
from .models import Demographics
from .forms import DemographicsForm
from pttrack.models import Patient
and context (class names, function names, or code) available:
# Path: demographics/models.py
# class Demographics(models.Model):
#
# NULL_BOOLEAN_CHOICES = (
# (None, "Not Answered"),
# (True, "Yes"),
# (False, "No")
# )
#
# patient = models.OneToOneField(Patient, null=True)
#
# creation_date = models.DateField(blank=True, null=True)
#
# chronic_condition = models.ManyToManyField(ChronicCondition, blank=True)
#
# has_insurance = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
#
# ER_visit_last_year = models.NullBooleanField(
# verbose_name="Visited ER in the Past Year",
# choices=NULL_BOOLEAN_CHOICES)
#
# last_date_physician_visit = models.DateField(
# blank=True, null=True,
# verbose_name="Date of Patient's Last Visit to Physician or ER")
#
# resource_access = models.ManyToManyField(
# ResourceAccess, blank=True,
# verbose_name="Access to Resources")
#
# lives_alone = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
#
# dependents = models.PositiveSmallIntegerField(
# blank=True, null=True, verbose_name="Number of Dependents")
#
# currently_employed = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
#
# work_status = models.ForeignKey(WorkStatus, blank=True, null=True)
#
# education_level = models.ForeignKey(EducationLevel, blank=True, null=True)
#
# annual_income = models.ForeignKey(IncomeRange, blank=True, null=True)
#
# transportation = models.ForeignKey(
# TransportationOption, blank=True, null=True)
#
# history = HistoricalRecords()
#
# Path: demographics/forms.py
# class DemographicsForm(ModelForm):
#
# class Meta(object):
# model = models.Demographics
# exclude = ['patient', 'creation_date']
# widgets = {'last_date_physician_visit': DateTimePicker(options={"format": "MM/DD/YYYY"})}
#
# def __init__(self, *args, **kwargs):
# super(DemographicsForm, self).__init__(*args, **kwargs)
#
# self.helper = FormHelper()
# self.helper.form_method = 'post'
#
# self.helper.layout = Layout(
# Fieldset('Medical',
# 'has_insurance',
# 'ER_visit_last_year',
# 'last_date_physician_visit',
# 'chronic_condition'),
# Fieldset('Social',
# 'lives_alone',
# 'dependents',
# 'resource_access',
# 'transportation'),
# Fieldset('Employment',
# 'currently_employed',
# 'education_level',
# 'work_status',
# 'annual_income')
# )
#
# self.helper.add_input(Submit('submit', 'Submit'))
. Output only the next line. | dg_old = Demographics.objects.get(patient=pt.id) |
Using the snippet: <|code_start|>from __future__ import unicode_literals
# Create your views here.
class DemographicsCreate(FormView):
template_name = 'demographics/demographics-create.html'
<|code_end|>
, determine the next line of code. You have imports:
import datetime
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView, UpdateView
from django.core.urlresolvers import reverse
from django.db import IntegrityError, transaction
from django.forms.models import model_to_dict
from django.shortcuts import render
from .models import Demographics
from .forms import DemographicsForm
from pttrack.models import Patient
and context (class names, function names, or code) available:
# Path: demographics/models.py
# class Demographics(models.Model):
#
# NULL_BOOLEAN_CHOICES = (
# (None, "Not Answered"),
# (True, "Yes"),
# (False, "No")
# )
#
# patient = models.OneToOneField(Patient, null=True)
#
# creation_date = models.DateField(blank=True, null=True)
#
# chronic_condition = models.ManyToManyField(ChronicCondition, blank=True)
#
# has_insurance = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
#
# ER_visit_last_year = models.NullBooleanField(
# verbose_name="Visited ER in the Past Year",
# choices=NULL_BOOLEAN_CHOICES)
#
# last_date_physician_visit = models.DateField(
# blank=True, null=True,
# verbose_name="Date of Patient's Last Visit to Physician or ER")
#
# resource_access = models.ManyToManyField(
# ResourceAccess, blank=True,
# verbose_name="Access to Resources")
#
# lives_alone = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
#
# dependents = models.PositiveSmallIntegerField(
# blank=True, null=True, verbose_name="Number of Dependents")
#
# currently_employed = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
#
# work_status = models.ForeignKey(WorkStatus, blank=True, null=True)
#
# education_level = models.ForeignKey(EducationLevel, blank=True, null=True)
#
# annual_income = models.ForeignKey(IncomeRange, blank=True, null=True)
#
# transportation = models.ForeignKey(
# TransportationOption, blank=True, null=True)
#
# history = HistoricalRecords()
#
# Path: demographics/forms.py
# class DemographicsForm(ModelForm):
#
# class Meta(object):
# model = models.Demographics
# exclude = ['patient', 'creation_date']
# widgets = {'last_date_physician_visit': DateTimePicker(options={"format": "MM/DD/YYYY"})}
#
# def __init__(self, *args, **kwargs):
# super(DemographicsForm, self).__init__(*args, **kwargs)
#
# self.helper = FormHelper()
# self.helper.form_method = 'post'
#
# self.helper.layout = Layout(
# Fieldset('Medical',
# 'has_insurance',
# 'ER_visit_last_year',
# 'last_date_physician_visit',
# 'chronic_condition'),
# Fieldset('Social',
# 'lives_alone',
# 'dependents',
# 'resource_access',
# 'transportation'),
# Fieldset('Employment',
# 'currently_employed',
# 'education_level',
# 'work_status',
# 'annual_income')
# )
#
# self.helper.add_input(Submit('submit', 'Submit'))
. Output only the next line. | form_class = DemographicsForm |
Given the following code snippet before the placeholder: <|code_start|> 'timestamp',
)
search_fields = (
'user__username', 'user__first_name', 'user__last_name', 'user__email',
'url', 'role__short_name'
)
# change_list_template = 'admin/pageview-log-summary.html'
# date_hierarchy = 'timestamp'
# We cannot call super().get_fields(request, obj) because that method calls
# get_readonly_fields(request, obj), causing infinite recursion. Ditto for
# super().get_form(request, obj). So we assume the default ModelForm.
def get_readonly_fields(self, request, obj=None):
return self.fields or [f.name for f in self.model._meta.fields]
def has_add_permission(self, request):
return False
# Allow viewing objects but not actually changing them.
def has_change_permission(self, request, obj=None):
return (request.method in ['GET', 'HEAD'] and
super(admin.ModelAdmin, self).has_change_permission(
request, obj))
def has_delete_permission(self, request, obj=None):
return False
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from .models import PageviewRecord
and context including class names, function names, and sometimes code from other files:
# Path: audit/models.py
# class PageviewRecord(models.Model):
#
# HTTP_METHODS = ['GET', 'POST', 'HEAD', 'PUT', 'PATCH', 'DELETE',
# 'CONNECT', 'OPTIONS', 'TRACE']
#
# user = models.ForeignKey(User, blank=True, null=True)
# user_ip = models.GenericIPAddressField()
# role = models.ForeignKey(core_models.ProviderType,
# blank=True, null=True)
#
# method = models.CharField(
# max_length=max(len(v) for v in HTTP_METHODS),
# choices=[(v, v) for v in HTTP_METHODS])
#
# url = models.URLField(max_length=256)
# referrer = models.URLField(max_length=256, blank=True, null=True)
#
# status_code = models.PositiveSmallIntegerField()
#
# timestamp = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return '%s by %s to %s at %s' % (self.method, self.user, self.url,
# self.timestamp)
. Output only the next line. | admin.site.register(PageviewRecord, PageviewRecordAdmin) |
Given snippet: <|code_start|>from __future__ import unicode_literals
class TestAudit(TestCase):
fixtures = ['pttrack.json']
def setUp(self):
self.client = Client()
def test_audit_unicode(self):
"""Check that unicode works for TestAudit
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from builtins import str
from django.test import TestCase, override_settings
from django.test import Client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from pttrack.models import ProviderType
from pttrack.test_views import build_provider, log_in_provider
from .models import PageviewRecord
from .middleware import AuditMiddleware
and context:
# Path: audit/models.py
# class PageviewRecord(models.Model):
#
# HTTP_METHODS = ['GET', 'POST', 'HEAD', 'PUT', 'PATCH', 'DELETE',
# 'CONNECT', 'OPTIONS', 'TRACE']
#
# user = models.ForeignKey(User, blank=True, null=True)
# user_ip = models.GenericIPAddressField()
# role = models.ForeignKey(core_models.ProviderType,
# blank=True, null=True)
#
# method = models.CharField(
# max_length=max(len(v) for v in HTTP_METHODS),
# choices=[(v, v) for v in HTTP_METHODS])
#
# url = models.URLField(max_length=256)
# referrer = models.URLField(max_length=256, blank=True, null=True)
#
# status_code = models.PositiveSmallIntegerField()
#
# timestamp = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return '%s by %s to %s at %s' % (self.method, self.user, self.url,
# self.timestamp)
which might include code, classes, or functions. Output only the next line. | p = PageviewRecord.objects.create( |
Given the following code snippet before the placeholder: <|code_start|> self.assertIn('opt=OPT', stdout.getvalue())
def test_args_missing(self):
with captured(out(), err()) as (stdout, stderr):
with mock_args([]):
with self.assertRaises(SystemExit):
RequiredArgCommand.main()
# Py2 and Py3 argparse have different messages
self.assertIn('error: ', stderr.getvalue())
self.assertIn('-r/--req', stderr.getvalue())
self.assertIn('required', stderr.getvalue())
def test_args_logging_level(self):
with captured(out(), err()) as (stdout, stderr):
with mock_args([]):
TestCommand.main()
self.assertIn('logging_level=%s' % logging.WARNING, stdout.getvalue())
with captured(out(), err()) as (stdout, stderr):
with mock_args(['--verbose']):
TestCommand.main()
self.assertIn('logging_level=%s' % logging.INFO, stdout.getvalue())
with captured(out(), err()) as (stdout, stderr):
with mock_args(['--debug']):
TestCommand.main()
self.assertIn('logging_level=%s' % logging.DEBUG, stdout.getvalue())
def test_config(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import logging
from abduct import captured, out, err
from caravan.tests.util import InTempDir, mock_args
from caravan.commands.base import BaseCommand
and context including class names, function names, and sometimes code from other files:
# Path: caravan/tests/util.py
# class InTempDir(object):
#
# def __enter__(self):
# self._tmpdir = os.path.realpath(tempfile.mkdtemp())
# self._pwd = os.getcwd()
# os.chdir(self._tmpdir)
# return self
#
# def __exit__(self, *args):
# os.chdir(self._pwd)
#
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/base.py
# class BaseCommand(object):
#
# """Base class for command-line tools."""
#
# default_config_section = 'caravan'
#
# CHILD_POLICIES = [
# 'TERMINATE',
# 'REQUEST_CANCEL',
# 'ABANDON',
# ]
#
# @classmethod
# def main(cls):
# """Setuptools console-script entrypoint"""
# cmd = cls()
# cmd._parse_args()
# cmd._setup_logging()
# response = cmd._run()
# output = cmd._handle_response(response)
# if output is not None:
# print(output)
#
# def _parse_args(self):
# args = sys.argv[1:]
#
# # Config only parser
# config_parser = argparse.ArgumentParser(description=self.description,
# add_help=False)
# config_parser.add_argument('-c', '--config',
# help='config file for setup.')
# config_parser.add_argument('--config-section',
# default=self.default_config_section,
# help='section of the config file for '
# 'setup.')
# config_args, remaining_args = config_parser.parse_known_args()
#
# # Full parser
# parser = argparse.ArgumentParser(description=self.description,
# parents=[config_parser])
# self._setup_base_arguments(parser)
# self.setup_arguments(parser)
#
# # Read defaults from config file
# if config_args.config:
# cp = configparser.RawConfigParser()
# with open(config_args.config) as fp:
# cp.readfp(fp)
# config_items = cp.items(config_args.config_section)
#
# valid_options = [option_string
# for action in parser._actions
# for option_string in action.option_strings]
# nargs_options = {option_string: action.nargs
# for action in parser._actions
# for option_string in action.option_strings}
#
# for option, value in config_items:
# option_string = '--%s' % option
#
# if option_string in valid_options:
# if nargs_options.get(option_string) == '+':
# value = value.split()
# option_args = [option_string] + value
# else:
# option_args = [option_string, value]
# args.extend(option_args)
#
# self.args = parser.parse_args(args)
#
# def _setup_base_arguments(self, parser):
# parser.add_argument('--logging-config',
# dest='logging_config',
# help='Optional config file for logging.'
# ' Default to config_uri')
# parser.add_argument('--verbose',
# dest='logging_level',
# default=logging.WARNING,
# action='store_const',
# const=logging.INFO)
# parser.add_argument('--debug',
# dest='logging_level',
# default=logging.WARNING,
# action='store_const',
# const=logging.DEBUG)
#
# def _setup_logging(self):
# if self.args.logging_config:
# logging.config.fileConfig(self.args.logging_config)
# elif self.args.config:
# try:
# logging.config.fileConfig(self.args.config)
# except (configparser.NoSectionError, KeyError):
# pass
# else:
# logging.basicConfig(level=self.args.logging_level)
#
# def _run(self):
# logging.debug('Run command with args: %s', self.args)
# try:
# return self.run()
# except KeyboardInterrupt:
# sys.exit(1)
#
# def _handle_response(self, response):
# if response is None:
# return "Success."
# elif isinstance(response, six.string_types):
# return response
# elif isinstance(response, list):
# if len(response) == 0:
# return 'No results.'
# if hasattr(self, 'formatter'):
# response = map(self.formatter, response)
# return tabulate(response, headers='keys', tablefmt="plain")
. Output only the next line. | with InTempDir(): |
Predict the next line for this snippet: <|code_start|>
LOGGING_CONFIG_FILE_DATA = """
[loggers]
keys = root
[logger_root]
level = DEBUG
handlers = console
[handlers]
keys = console
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = DEBUG
formatter = console
[formatters]
keys = console
[formatter_console]
format = %(message)s
"""
class Test(unittest.TestCase):
def test_args_optional(self):
with captured(out(), err()) as (stdout, stderr):
<|code_end|>
with the help of current file imports:
import unittest
import logging
from abduct import captured, out, err
from caravan.tests.util import InTempDir, mock_args
from caravan.commands.base import BaseCommand
and context from other files:
# Path: caravan/tests/util.py
# class InTempDir(object):
#
# def __enter__(self):
# self._tmpdir = os.path.realpath(tempfile.mkdtemp())
# self._pwd = os.getcwd()
# os.chdir(self._tmpdir)
# return self
#
# def __exit__(self, *args):
# os.chdir(self._pwd)
#
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/base.py
# class BaseCommand(object):
#
# """Base class for command-line tools."""
#
# default_config_section = 'caravan'
#
# CHILD_POLICIES = [
# 'TERMINATE',
# 'REQUEST_CANCEL',
# 'ABANDON',
# ]
#
# @classmethod
# def main(cls):
# """Setuptools console-script entrypoint"""
# cmd = cls()
# cmd._parse_args()
# cmd._setup_logging()
# response = cmd._run()
# output = cmd._handle_response(response)
# if output is not None:
# print(output)
#
# def _parse_args(self):
# args = sys.argv[1:]
#
# # Config only parser
# config_parser = argparse.ArgumentParser(description=self.description,
# add_help=False)
# config_parser.add_argument('-c', '--config',
# help='config file for setup.')
# config_parser.add_argument('--config-section',
# default=self.default_config_section,
# help='section of the config file for '
# 'setup.')
# config_args, remaining_args = config_parser.parse_known_args()
#
# # Full parser
# parser = argparse.ArgumentParser(description=self.description,
# parents=[config_parser])
# self._setup_base_arguments(parser)
# self.setup_arguments(parser)
#
# # Read defaults from config file
# if config_args.config:
# cp = configparser.RawConfigParser()
# with open(config_args.config) as fp:
# cp.readfp(fp)
# config_items = cp.items(config_args.config_section)
#
# valid_options = [option_string
# for action in parser._actions
# for option_string in action.option_strings]
# nargs_options = {option_string: action.nargs
# for action in parser._actions
# for option_string in action.option_strings}
#
# for option, value in config_items:
# option_string = '--%s' % option
#
# if option_string in valid_options:
# if nargs_options.get(option_string) == '+':
# value = value.split()
# option_args = [option_string] + value
# else:
# option_args = [option_string, value]
# args.extend(option_args)
#
# self.args = parser.parse_args(args)
#
# def _setup_base_arguments(self, parser):
# parser.add_argument('--logging-config',
# dest='logging_config',
# help='Optional config file for logging.'
# ' Default to config_uri')
# parser.add_argument('--verbose',
# dest='logging_level',
# default=logging.WARNING,
# action='store_const',
# const=logging.INFO)
# parser.add_argument('--debug',
# dest='logging_level',
# default=logging.WARNING,
# action='store_const',
# const=logging.DEBUG)
#
# def _setup_logging(self):
# if self.args.logging_config:
# logging.config.fileConfig(self.args.logging_config)
# elif self.args.config:
# try:
# logging.config.fileConfig(self.args.config)
# except (configparser.NoSectionError, KeyError):
# pass
# else:
# logging.basicConfig(level=self.args.logging_level)
#
# def _run(self):
# logging.debug('Run command with args: %s', self.args)
# try:
# return self.run()
# except KeyboardInterrupt:
# sys.exit(1)
#
# def _handle_response(self, response):
# if response is None:
# return "Success."
# elif isinstance(response, six.string_types):
# return response
# elif isinstance(response, list):
# if len(response) == 0:
# return 'No results.'
# if hasattr(self, 'formatter'):
# response = map(self.formatter, response)
# return tabulate(response, headers='keys', tablefmt="plain")
, which may contain function names, class names, or code. Output only the next line. | with mock_args([]): |
Using the snippet: <|code_start|>
class TestRegisterWorkflow(unittest.TestCase):
def setUp(self):
self.mock_swf = mock_swf()
self.mock_swf.start()
self.connection = get_connection()
self.connection.register_domain(
name='TEST',
workflowExecutionRetentionPeriodInDays='1')
def tearDown(self):
self.mock_swf.stop()
def _describe_workflow(self, name, version):
types = self.connection.describe_workflow_type(
domain='TEST',
workflowType={'name': name, 'version': version})
return types
def _list_workflows(self):
response = self.connection.list_workflow_types(
domain='TEST',
registrationStatus='REGISTERED')
return response['typeInfos']
def test_example_demo(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import mock
from moto import mock_swf
from caravan.swf import (get_workflow_registration_parameter,
register_workflow,
get_connection)
from caravan.examples.demo import Demo
and context (class names, function names, or code) available:
# Path: caravan/swf.py
# def get_workflow_registration_parameter(workflow):
# args = {}
#
# for parameter in REGISTER_WORKFLOW_PARAMETERS:
# attr_name = inflection.underscore(parameter)
# attr_value = getattr(workflow, attr_name, None)
#
# required = attr_name in REGISTER_WORKFLOW_REQUIRED_PARAMETERS
#
# if attr_value is None:
# if required:
# raise InvalidWorkflowError('missing attribute %s' % attr_name)
#
# else:
# is_string = isinstance(attr_value, string_types)
# is_dict = isinstance(attr_value, dict)
# is_int = isinstance(attr_value, int)
#
# if parameter == 'defaultTaskList' and is_string:
# attr_value = {'name': attr_value}
# if parameter == 'defaultTaskList' and is_dict:
# pass
# if parameter.endswith('Timeout') and is_int:
# attr_value = str(attr_value)
# elif not is_string:
# raise InvalidWorkflowError('invalid attribute %s' % attr_name)
#
# args[parameter] = attr_value
#
# return args
#
# def register_workflow(connection, domain, workflow):
# """Register a workflow type.
#
# Return False if this workflow already registered (and True otherwise).
# """
# args = get_workflow_registration_parameter(workflow)
#
# try:
# connection.register_workflow_type(domain=domain, **args)
# except ClientError as err:
# if err.response['Error']['Code'] == 'TypeAlreadyExistsFault':
# return False # Ignore this error
# raise
#
# return True
#
# def get_connection():
# # Must increase the http timeout since SWF has a timeout of 60 sec
# config = Config(connect_timeout=50, read_timeout=70)
# connection = boto3.client("swf", config=config)
# return connection
. Output only the next line. | result = register_workflow(self.connection, 'TEST', Demo) |
Predict the next line after this snippet: <|code_start|>
@mock.patch('caravan.commands.decider.Worker')
class Test(unittest.TestCase):
def test_nominal(self, m_worker_cls):
m_worker = m_worker_cls.return_value
m_worker.run.side_effect = [None, None, KeyboardInterrupt('KILLTEST')]
args = [
'-d', 'DOMAIN', '-m', 'caravan.tests.fixtures', '-t', 'TASKLIST',
]
with mock_args(args):
with self.assertRaises(SystemExit) as exc:
Command.main()
self.assertEqual(exc.exception.code, 1)
self.assertEqual(m_worker.run.call_count, 3)
args, kwargs = m_worker_cls.call_args
self.assertEqual(kwargs['domain'], 'DOMAIN')
self.assertEqual(kwargs['task_list'], 'TASKLIST')
self.assertEqual(kwargs['workflows'],
<|code_end|>
using the current file's imports:
import unittest
import mock
import caravan
from caravan.tests import fixtures
from caravan.tests.util import mock_args
from caravan.commands.decider import Command
from caravan.commands.decider import ClassesLoaderFromModule
and any relevant context from other files:
# Path: caravan/tests/fixtures.py
# class TestWorkflow1(Workflow):
# class TestWorkflow2(Workflow):
#
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/decider.py
# class Command(BaseCommand):
#
# description = 'Decider worker'
#
# def setup_arguments(self, parser):
# parser.add_argument('-m', '--modules',
# type=ClassesLoaderFromModule(Workflow),
# nargs='+',
# required=True)
# parser.add_argument('-d', '--domain',
# required=True)
# parser.add_argument('-t', '--task-list',
# required=True)
# parser.add_argument('--register-workflows', action='store_true')
#
# def run(self):
# connection = get_connection()
# workflows = [w for module in self.args.modules for w in module]
#
# if self.args.register_workflows:
# log.info("Registering workflow types")
# for workflow in workflows:
# created = register_workflow(connection=connection,
# domain=self.args.domain,
# workflow=workflow)
# if created:
# log.info("Workflow type %s(%s): registered.",
# workflow.name, workflow.version)
# else:
# log.info("Workflow type %s(%s): already registered.",
# workflow.name, workflow.version)
#
# log.info("Start decider worker...")
# worker = Worker(connection=connection,
# domain=self.args.domain,
# task_list=self.args.task_list,
# workflows=workflows)
#
# while True:
# try:
# worker.run()
# except Exception: # Doesn't catch KeyboardInterrupt
# log.exception("Decider crashed!")
#
# Path: caravan/commands/decider.py
# class Command(BaseCommand):
# def setup_arguments(self, parser):
# def run(self):
. Output only the next line. | [fixtures.TestWorkflow1, fixtures.TestWorkflow2]) |
Continue the code snippet: <|code_start|>
@mock.patch('caravan.commands.decider.Worker')
class Test(unittest.TestCase):
def test_nominal(self, m_worker_cls):
m_worker = m_worker_cls.return_value
m_worker.run.side_effect = [None, None, KeyboardInterrupt('KILLTEST')]
args = [
'-d', 'DOMAIN', '-m', 'caravan.tests.fixtures', '-t', 'TASKLIST',
]
<|code_end|>
. Use current file imports:
import unittest
import mock
import caravan
from caravan.tests import fixtures
from caravan.tests.util import mock_args
from caravan.commands.decider import Command
from caravan.commands.decider import ClassesLoaderFromModule
and context (classes, functions, or code) from other files:
# Path: caravan/tests/fixtures.py
# class TestWorkflow1(Workflow):
# class TestWorkflow2(Workflow):
#
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/decider.py
# class Command(BaseCommand):
#
# description = 'Decider worker'
#
# def setup_arguments(self, parser):
# parser.add_argument('-m', '--modules',
# type=ClassesLoaderFromModule(Workflow),
# nargs='+',
# required=True)
# parser.add_argument('-d', '--domain',
# required=True)
# parser.add_argument('-t', '--task-list',
# required=True)
# parser.add_argument('--register-workflows', action='store_true')
#
# def run(self):
# connection = get_connection()
# workflows = [w for module in self.args.modules for w in module]
#
# if self.args.register_workflows:
# log.info("Registering workflow types")
# for workflow in workflows:
# created = register_workflow(connection=connection,
# domain=self.args.domain,
# workflow=workflow)
# if created:
# log.info("Workflow type %s(%s): registered.",
# workflow.name, workflow.version)
# else:
# log.info("Workflow type %s(%s): already registered.",
# workflow.name, workflow.version)
#
# log.info("Start decider worker...")
# worker = Worker(connection=connection,
# domain=self.args.domain,
# task_list=self.args.task_list,
# workflows=workflows)
#
# while True:
# try:
# worker.run()
# except Exception: # Doesn't catch KeyboardInterrupt
# log.exception("Decider crashed!")
#
# Path: caravan/commands/decider.py
# class Command(BaseCommand):
# def setup_arguments(self, parser):
# def run(self):
. Output only the next line. | with mock_args(args): |
Continue the code snippet: <|code_start|>
@mock.patch('caravan.commands.decider.Worker')
class Test(unittest.TestCase):
def test_nominal(self, m_worker_cls):
m_worker = m_worker_cls.return_value
m_worker.run.side_effect = [None, None, KeyboardInterrupt('KILLTEST')]
args = [
'-d', 'DOMAIN', '-m', 'caravan.tests.fixtures', '-t', 'TASKLIST',
]
with mock_args(args):
with self.assertRaises(SystemExit) as exc:
<|code_end|>
. Use current file imports:
import unittest
import mock
import caravan
from caravan.tests import fixtures
from caravan.tests.util import mock_args
from caravan.commands.decider import Command
from caravan.commands.decider import ClassesLoaderFromModule
and context (classes, functions, or code) from other files:
# Path: caravan/tests/fixtures.py
# class TestWorkflow1(Workflow):
# class TestWorkflow2(Workflow):
#
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/decider.py
# class Command(BaseCommand):
#
# description = 'Decider worker'
#
# def setup_arguments(self, parser):
# parser.add_argument('-m', '--modules',
# type=ClassesLoaderFromModule(Workflow),
# nargs='+',
# required=True)
# parser.add_argument('-d', '--domain',
# required=True)
# parser.add_argument('-t', '--task-list',
# required=True)
# parser.add_argument('--register-workflows', action='store_true')
#
# def run(self):
# connection = get_connection()
# workflows = [w for module in self.args.modules for w in module]
#
# if self.args.register_workflows:
# log.info("Registering workflow types")
# for workflow in workflows:
# created = register_workflow(connection=connection,
# domain=self.args.domain,
# workflow=workflow)
# if created:
# log.info("Workflow type %s(%s): registered.",
# workflow.name, workflow.version)
# else:
# log.info("Workflow type %s(%s): already registered.",
# workflow.name, workflow.version)
#
# log.info("Start decider worker...")
# worker = Worker(connection=connection,
# domain=self.args.domain,
# task_list=self.args.task_list,
# workflows=workflows)
#
# while True:
# try:
# worker.run()
# except Exception: # Doesn't catch KeyboardInterrupt
# log.exception("Decider crashed!")
#
# Path: caravan/commands/decider.py
# class Command(BaseCommand):
# def setup_arguments(self, parser):
# def run(self):
. Output only the next line. | Command.main() |
Predict the next line after this snippet: <|code_start|> @mock.patch('caravan.commands.decider.get_connection', autospec=True)
def test_register_workflows(self, m_get_conn, m_register, m_worker_cls):
m_worker = m_worker_cls.return_value
m_worker.run.side_effect = KeyboardInterrupt('KILLTEST')
m_conn = m_get_conn.return_value
args = [
'-d', 'DOMAIN', '-m', 'caravan.tests.fixtures', '-t', 'TASKLIST',
'--register-workflows',
]
with mock_args(args):
with self.assertRaises(SystemExit):
Command.main()
expected = [
mock.call(connection=m_conn,
domain='DOMAIN',
workflow=fixtures.TestWorkflow1),
mock.call(connection=m_conn,
domain='DOMAIN',
workflow=fixtures.TestWorkflow2),
]
self.assertEqual(m_register.call_args_list, expected)
class TestClassLoader(unittest.TestCase):
def test_nominal(self):
<|code_end|>
using the current file's imports:
import unittest
import mock
import caravan
from caravan.tests import fixtures
from caravan.tests.util import mock_args
from caravan.commands.decider import Command
from caravan.commands.decider import ClassesLoaderFromModule
and any relevant context from other files:
# Path: caravan/tests/fixtures.py
# class TestWorkflow1(Workflow):
# class TestWorkflow2(Workflow):
#
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/decider.py
# class Command(BaseCommand):
#
# description = 'Decider worker'
#
# def setup_arguments(self, parser):
# parser.add_argument('-m', '--modules',
# type=ClassesLoaderFromModule(Workflow),
# nargs='+',
# required=True)
# parser.add_argument('-d', '--domain',
# required=True)
# parser.add_argument('-t', '--task-list',
# required=True)
# parser.add_argument('--register-workflows', action='store_true')
#
# def run(self):
# connection = get_connection()
# workflows = [w for module in self.args.modules for w in module]
#
# if self.args.register_workflows:
# log.info("Registering workflow types")
# for workflow in workflows:
# created = register_workflow(connection=connection,
# domain=self.args.domain,
# workflow=workflow)
# if created:
# log.info("Workflow type %s(%s): registered.",
# workflow.name, workflow.version)
# else:
# log.info("Workflow type %s(%s): already registered.",
# workflow.name, workflow.version)
#
# log.info("Start decider worker...")
# worker = Worker(connection=connection,
# domain=self.args.domain,
# task_list=self.args.task_list,
# workflows=workflows)
#
# while True:
# try:
# worker.run()
# except Exception: # Doesn't catch KeyboardInterrupt
# log.exception("Decider crashed!")
#
# Path: caravan/commands/decider.py
# class Command(BaseCommand):
# def setup_arguments(self, parser):
# def run(self):
. Output only the next line. | loader = ClassesLoaderFromModule(caravan.Workflow) |
Given the code snippet: <|code_start|>
def httpretty_register():
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
body = '{"runId": "1e536162-f1ea-48b0-85f3-aade88eef2f7"}'
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body=body)
def run_command(additional_args):
httpretty_register()
args = ['-d', 'DOMAIN', '-i', 'ID']
args += additional_args
with captured(out(), err()) as (stdout, stderr):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import json
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.terminate import Command
and context (functions, classes, or occasionally code) from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/terminate.py
# class Command(BaseCommand):
#
# description = 'Terminate a workflow execution'
#
# def setup_arguments(self, parser):
# parser.add_argument('-d', '--domain', required=True)
# parser.add_argument('-i', '--id', required=True)
# parser.add_argument('--run-id')
# parser.add_argument('--reason')
# parser.add_argument('--details')
# parser.add_argument('--child-policy', choices=self.CHILD_POLICIES)
#
# def run(self):
# run_swf_command(
# 'terminate_workflow_execution',
# domain=self.args.domain,
# workflowId=self.args.id,
# runId=self.args.run_id,
# reason=self.args.reason,
# details=self.args.details,
# childPolicy=self.args.child_policy,
# )
# return 'Execution terminated.'
. Output only the next line. | with mock_args(args): |
Based on the snippet: <|code_start|>
def httpretty_register():
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
body = '{"runId": "1e536162-f1ea-48b0-85f3-aade88eef2f7"}'
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body=body)
def run_command(additional_args):
httpretty_register()
args = ['-d', 'DOMAIN', '-i', 'ID']
args += additional_args
with captured(out(), err()) as (stdout, stderr):
with mock_args(args):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import json
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.terminate import Command
and context (classes, functions, sometimes code) from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/terminate.py
# class Command(BaseCommand):
#
# description = 'Terminate a workflow execution'
#
# def setup_arguments(self, parser):
# parser.add_argument('-d', '--domain', required=True)
# parser.add_argument('-i', '--id', required=True)
# parser.add_argument('--run-id')
# parser.add_argument('--reason')
# parser.add_argument('--details')
# parser.add_argument('--child-policy', choices=self.CHILD_POLICIES)
#
# def run(self):
# run_swf_command(
# 'terminate_workflow_execution',
# domain=self.args.domain,
# workflowId=self.args.id,
# runId=self.args.run_id,
# reason=self.args.reason,
# details=self.args.details,
# childPolicy=self.args.child_policy,
# )
# return 'Execution terminated.'
. Output only the next line. | Command.main() |
Next line prediction: <|code_start|>
def httpretty_register():
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
body = '{"runId": "1e536162-f1ea-48b0-85f3-aade88eef2f7"}'
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body=body)
def run_command(additional_args):
httpretty_register()
args = ['-d', 'DOMAIN', '-n', 'NAME', '-v', 'VERSION', '-i', 'ID']
args += additional_args
with captured(out(), err()) as (stdout, stderr):
<|code_end|>
. Use current file imports:
(import unittest
import json
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.start import Command)
and context including class names, function names, or small code snippets from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/start.py
# class Command(BaseCommand):
#
# description = 'Start a workflow execution'
#
# def setup_arguments(self, parser):
# parser.add_argument('-d', '--domain', required=True)
# parser.add_argument('-i', '--id', required=True)
# parser.add_argument('-n', '--name', required=True)
# parser.add_argument('-v', '--version', required=True)
# parser.add_argument('-t', '--task-list')
#
# parser.add_argument(
# '--input',
# help='Raw input data for this execution',
# metavar='"<Some data>"')
# parser.add_argument(
# '--tag-list',
# help='List of tags to associate with the workflow execution',
# metavar='"tag1 tag2 ..."')
# parser.add_argument(
# '--execution-timeout',
# help='The maximum total duration for this workflow execution '
# '(seconds)')
# parser.add_argument(
# '--task-timeout',
# help='The maximum duration of decision tasks (seconds)')
# parser.add_argument(
# '--child-policy',
# choices=self.CHILD_POLICIES,
# help='Policy to use for the child executions of this execution')
# parser.add_argument(
# '--lambda-role',
# help='ARN of an IAM role that authorizes SWF to invoke Lambda '
# 'functions')
#
# def run(self):
# workflow_type = {'name': self.args.name, 'version': self.args.version}
#
# if self.args.task_list is not None:
# task_list = {'name': self.args.task_list}
# else:
# task_list = None
#
# if self.args.tag_list:
# tag_list = self.args.tag_list.split()
# else:
# tag_list = None
#
# response = run_swf_command(
# 'start_workflow_execution',
# domain=self.args.domain,
# workflowId=self.args.id,
# workflowType=workflow_type,
# input=self.args.input,
# taskList=task_list,
# tagList=tag_list,
# executionStartToCloseTimeout=self.args.execution_timeout,
# taskStartToCloseTimeout=self.args.task_timeout,
# childPolicy=self.args.child_policy,
# lambdaRole=self.args.lambda_role,
# )
#
# return 'Execution started. RunId: %s' % response['runId']
. Output only the next line. | with mock_args(args): |
Given snippet: <|code_start|>
def httpretty_register():
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
body = '{"runId": "1e536162-f1ea-48b0-85f3-aade88eef2f7"}'
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body=body)
def run_command(additional_args):
httpretty_register()
args = ['-d', 'DOMAIN', '-n', 'NAME', '-v', 'VERSION', '-i', 'ID']
args += additional_args
with captured(out(), err()) as (stdout, stderr):
with mock_args(args):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import json
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.start import Command
and context:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/start.py
# class Command(BaseCommand):
#
# description = 'Start a workflow execution'
#
# def setup_arguments(self, parser):
# parser.add_argument('-d', '--domain', required=True)
# parser.add_argument('-i', '--id', required=True)
# parser.add_argument('-n', '--name', required=True)
# parser.add_argument('-v', '--version', required=True)
# parser.add_argument('-t', '--task-list')
#
# parser.add_argument(
# '--input',
# help='Raw input data for this execution',
# metavar='"<Some data>"')
# parser.add_argument(
# '--tag-list',
# help='List of tags to associate with the workflow execution',
# metavar='"tag1 tag2 ..."')
# parser.add_argument(
# '--execution-timeout',
# help='The maximum total duration for this workflow execution '
# '(seconds)')
# parser.add_argument(
# '--task-timeout',
# help='The maximum duration of decision tasks (seconds)')
# parser.add_argument(
# '--child-policy',
# choices=self.CHILD_POLICIES,
# help='Policy to use for the child executions of this execution')
# parser.add_argument(
# '--lambda-role',
# help='ARN of an IAM role that authorizes SWF to invoke Lambda '
# 'functions')
#
# def run(self):
# workflow_type = {'name': self.args.name, 'version': self.args.version}
#
# if self.args.task_list is not None:
# task_list = {'name': self.args.task_list}
# else:
# task_list = None
#
# if self.args.tag_list:
# tag_list = self.args.tag_list.split()
# else:
# tag_list = None
#
# response = run_swf_command(
# 'start_workflow_execution',
# domain=self.args.domain,
# workflowId=self.args.id,
# workflowType=workflow_type,
# input=self.args.input,
# taskList=task_list,
# tagList=tag_list,
# executionStartToCloseTimeout=self.args.execution_timeout,
# taskStartToCloseTimeout=self.args.task_timeout,
# childPolicy=self.args.child_policy,
# lambdaRole=self.args.lambda_role,
# )
#
# return 'Execution started. RunId: %s' % response['runId']
which might include code, classes, or functions. Output only the next line. | Command.main() |
Here is a snippet: <|code_start|>
class Test(unittest.TestCase):
@httpretty.activate
def test_nominal(self):
args = ['-d', 'DOMAIN', '-i', 'ID', '-s', 'SIG']
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body='')
with captured(out(), err()) as (stdout, stderr):
<|code_end|>
. Write the next line using the current file imports:
import json
import unittest
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.signal import Command
and context from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/signal.py
# class Command(BaseCommand):
#
# description = 'Signal a workflow execution'
#
# def setup_arguments(self, parser):
# parser.add_argument('-d', '--domain', required=True)
# parser.add_argument('-i', '--id', required=True)
# parser.add_argument('--run-id')
# parser.add_argument('-s', '--signal', required=True)
# parser.add_argument(
# '--input',
# help='Raw input data for this signal',
# metavar='"<Some data>"')
#
# def run(self):
# run_swf_command(
# 'signal_workflow_execution',
# domain=self.args.domain,
# workflowId=self.args.id,
# signalName=self.args.signal,
# runId=self.args.run_id,
# input=self.args.input,
# )
# return 'Signal sent.'
, which may include functions, classes, or code. Output only the next line. | with mock_args(args): |
Next line prediction: <|code_start|>
class Test(unittest.TestCase):
@httpretty.activate
def test_nominal(self):
args = ['-d', 'DOMAIN', '-i', 'ID', '-s', 'SIG']
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body='')
with captured(out(), err()) as (stdout, stderr):
with mock_args(args):
<|code_end|>
. Use current file imports:
(import json
import unittest
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.signal import Command)
and context including class names, function names, or small code snippets from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/signal.py
# class Command(BaseCommand):
#
# description = 'Signal a workflow execution'
#
# def setup_arguments(self, parser):
# parser.add_argument('-d', '--domain', required=True)
# parser.add_argument('-i', '--id', required=True)
# parser.add_argument('--run-id')
# parser.add_argument('-s', '--signal', required=True)
# parser.add_argument(
# '--input',
# help='Raw input data for this signal',
# metavar='"<Some data>"')
#
# def run(self):
# run_swf_command(
# 'signal_workflow_execution',
# domain=self.args.domain,
# workflowId=self.args.id,
# signalName=self.args.signal,
# runId=self.args.run_id,
# input=self.args.input,
# )
# return 'Signal sent.'
. Output only the next line. | Command.main() |
Using the snippet: <|code_start|>
class Test(unittest.TestCase):
@httpretty.activate
def test_nominal(self):
args = ['--name', 'DOMAIN', '--retention-days', '10']
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body='')
with captured(out(), err()) as (stdout, stderr):
<|code_end|>
, determine the next line of code. You have imports:
import json
import unittest
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.domain_register import Command
and context (class names, function names, or code) available:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/domain_register.py
# class Command(BaseCommand):
#
# description = 'Register a domain'
# default_config_section = 'caravan:domain'
#
# def setup_arguments(self, parser):
# parser.add_argument('-n', '--name', required=True)
# parser.add_argument(
# '--retention-days',
# dest='retention_days',
# required=True,
# help='Retention period for workflow execution')
# parser.add_argument('--description')
#
# def run(self):
# run_swf_command(
# 'register_domain',
# name=self.args.name,
# workflowExecutionRetentionPeriodInDays=self.args.retention_days,
# description=self.args.description,
# )
. Output only the next line. | with mock_args(args): |
Continue the code snippet: <|code_start|>
class Test(unittest.TestCase):
@httpretty.activate
def test_nominal(self):
args = ['--name', 'DOMAIN', '--retention-days', '10']
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body='')
with captured(out(), err()) as (stdout, stderr):
with mock_args(args):
<|code_end|>
. Use current file imports:
import json
import unittest
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.domain_register import Command
and context (classes, functions, or code) from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/domain_register.py
# class Command(BaseCommand):
#
# description = 'Register a domain'
# default_config_section = 'caravan:domain'
#
# def setup_arguments(self, parser):
# parser.add_argument('-n', '--name', required=True)
# parser.add_argument(
# '--retention-days',
# dest='retention_days',
# required=True,
# help='Retention period for workflow execution')
# parser.add_argument('--description')
#
# def run(self):
# run_swf_command(
# 'register_domain',
# name=self.args.name,
# workflowExecutionRetentionPeriodInDays=self.args.retention_days,
# description=self.args.description,
# )
. Output only the next line. | Command.main() |
Predict the next line after this snippet: <|code_start|>
def httpretty_register():
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
body = """
{"domainInfos":
[
{"description": "music", "name": "867530901",
"status": "REGISTERED"},
{"description": "music", "name": "867530902",
"status": "REGISTERED"},
{"description": "", "name": "Demo", "status": "REGISTERED"}
]
} """
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body=body)
def run_command(additional_args):
httpretty_register()
args = []
args += additional_args
with captured(out(), err()) as (stdout, stderr):
<|code_end|>
using the current file's imports:
import unittest
import json
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.domain_list import Command
and any relevant context from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/domain_list.py
# class Command(BaseCommand):
#
# description = 'List domains'
#
# def setup_arguments(self, parser):
# parser.add_argument('--deprecated',
# dest='registration_status',
# action='store_const',
# const='DEPRECATED',
# default='REGISTERED')
#
# def run(self):
# response = run_swf_command(
# 'list_domains',
# registrationStatus=self.args.registration_status
# )
#
# return response['domainInfos']
. Output only the next line. | with mock_args(args): |
Here is a snippet: <|code_start|>
def httpretty_register():
headers = {
'x-amzn-RequestId': 'd68969c7-3f0d-11e1-9b11-7182192d0b57',
}
body = """
{"domainInfos":
[
{"description": "music", "name": "867530901",
"status": "REGISTERED"},
{"description": "music", "name": "867530902",
"status": "REGISTERED"},
{"description": "", "name": "Demo", "status": "REGISTERED"}
]
} """
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body=body)
def run_command(additional_args):
httpretty_register()
args = []
args += additional_args
with captured(out(), err()) as (stdout, stderr):
with mock_args(args):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import json
import httpretty
from abduct import captured, out, err
from caravan.tests.util import mock_args
from caravan.commands.domain_list import Command
and context from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/domain_list.py
# class Command(BaseCommand):
#
# description = 'List domains'
#
# def setup_arguments(self, parser):
# parser.add_argument('--deprecated',
# dest='registration_status',
# action='store_const',
# const='DEPRECATED',
# default='REGISTERED')
#
# def run(self):
# response = run_swf_command(
# 'list_domains',
# registrationStatus=self.args.registration_status
# )
#
# return response['domainInfos']
, which may include functions, classes, or code. Output only the next line. | Command.main() |
Given the following code snippet before the placeholder: <|code_start|> { "executionInfos": [
{ "cancelRequested": false,
"execution": {
"runId": "f5ebbac6-941c-4342-ad69-dfd2f8be6689",
"workflowId": "20110927-T-1"
},
"executionStatus": "OPEN",
"startTimestamp": 1326585031.619,
"tagList": [
"music purchase", "digital", "ricoh-the-dog"
],
"workflowType": {
"name": "customerOrderWorkflow",
"version": "1.0"
}
} ]
}"""
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body=body)
def run_command(additional_args):
httpretty_register()
args = ['-d', 'DOMAIN']
args += additional_args
with captured(out(), err()) as (stdout, stderr):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import json
import httpretty
from abduct import captured, out, err
from freezegun import freeze_time
from caravan.tests.util import mock_args
from caravan.commands.list import Command
and context including class names, function names, and sometimes code from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/list.py
# class Command(BaseCommand):
#
# description = 'List workflow executions'
#
# def setup_arguments(self, parser):
# present = arrow.utcnow()
# default_oldest = present.replace(days=-1)
# default_latest = present.clone()
#
# parser.add_argument('-d', '--domain', required=True)
# parser.add_argument('--oldest', default=default_oldest, type=arrow.get)
# parser.add_argument('--latest', default=default_latest, type=arrow.get)
#
# filter_group = parser.add_mutually_exclusive_group()
# type_group = filter_group.add_argument_group()
# type_group.add_argument('-n', '--name')
# type_group.add_argument('-v', '--version')
# filter_group.add_argument('--tag')
# filter_group.add_argument('--id')
#
# def run(self):
# time_filter = {
# 'oldestDate': self.args.oldest.naive,
# 'latestDate': self.args.latest.naive,
# }
#
# if self.args.name is not None:
# type_filter = {
# 'name': self.args.name,
# }
# if self.args.version is not None:
# type_filter['version'] = self.args.version
# else:
# type_filter = None
#
# if self.args.tag is not None:
# tag_filter = {
# 'tag': self.args.tag,
# }
# else:
# tag_filter = None
#
# if self.args.id is not None:
# execution_filter = {
# 'workflowId': self.args.id,
# }
# else:
# execution_filter = None
#
# response = run_swf_command(
# 'list_open_workflow_executions',
# domain=self.args.domain,
# startTimeFilter=time_filter,
# typeFilter=type_filter,
# tagFilter=tag_filter,
# executionFilter=execution_filter,
# )
#
# return response['executionInfos']
#
# def formatter(self, e):
# w = e['workflowType']
# return {
# 'Start': arrow.get(e['startTimestamp']).humanize(),
# 'Workflow Type': '%s(%s)' % (w['name'], w['version']),
# 'Workflow Id': e['execution']['workflowId'],
# 'Run Id': e['execution']['runId'],
# 'Status': e['executionStatus'],
# }
. Output only the next line. | with mock_args(args): |
Predict the next line for this snippet: <|code_start|> { "cancelRequested": false,
"execution": {
"runId": "f5ebbac6-941c-4342-ad69-dfd2f8be6689",
"workflowId": "20110927-T-1"
},
"executionStatus": "OPEN",
"startTimestamp": 1326585031.619,
"tagList": [
"music purchase", "digital", "ricoh-the-dog"
],
"workflowType": {
"name": "customerOrderWorkflow",
"version": "1.0"
}
} ]
}"""
httpretty.register_uri(httpretty.POST,
"https://swf.us-east-1.amazonaws.com/",
content_type='application/json',
adding_headers=headers,
body=body)
def run_command(additional_args):
httpretty_register()
args = ['-d', 'DOMAIN']
args += additional_args
with captured(out(), err()) as (stdout, stderr):
with mock_args(args):
<|code_end|>
with the help of current file imports:
import unittest
import json
import httpretty
from abduct import captured, out, err
from freezegun import freeze_time
from caravan.tests.util import mock_args
from caravan.commands.list import Command
and context from other files:
# Path: caravan/tests/util.py
# def mock_args(args):
# return mock.patch('sys.argv', ['PROG'] + args)
#
# Path: caravan/commands/list.py
# class Command(BaseCommand):
#
# description = 'List workflow executions'
#
# def setup_arguments(self, parser):
# present = arrow.utcnow()
# default_oldest = present.replace(days=-1)
# default_latest = present.clone()
#
# parser.add_argument('-d', '--domain', required=True)
# parser.add_argument('--oldest', default=default_oldest, type=arrow.get)
# parser.add_argument('--latest', default=default_latest, type=arrow.get)
#
# filter_group = parser.add_mutually_exclusive_group()
# type_group = filter_group.add_argument_group()
# type_group.add_argument('-n', '--name')
# type_group.add_argument('-v', '--version')
# filter_group.add_argument('--tag')
# filter_group.add_argument('--id')
#
# def run(self):
# time_filter = {
# 'oldestDate': self.args.oldest.naive,
# 'latestDate': self.args.latest.naive,
# }
#
# if self.args.name is not None:
# type_filter = {
# 'name': self.args.name,
# }
# if self.args.version is not None:
# type_filter['version'] = self.args.version
# else:
# type_filter = None
#
# if self.args.tag is not None:
# tag_filter = {
# 'tag': self.args.tag,
# }
# else:
# tag_filter = None
#
# if self.args.id is not None:
# execution_filter = {
# 'workflowId': self.args.id,
# }
# else:
# execution_filter = None
#
# response = run_swf_command(
# 'list_open_workflow_executions',
# domain=self.args.domain,
# startTimeFilter=time_filter,
# typeFilter=type_filter,
# tagFilter=tag_filter,
# executionFilter=execution_filter,
# )
#
# return response['executionInfos']
#
# def formatter(self, e):
# w = e['workflowType']
# return {
# 'Start': arrow.get(e['startTimestamp']).humanize(),
# 'Workflow Type': '%s(%s)' % (w['name'], w['version']),
# 'Workflow Id': e['execution']['workflowId'],
# 'Run Id': e['execution']['runId'],
# 'Status': e['executionStatus'],
# }
, which may contain function names, class names, or code. Output only the next line. | Command.main() |
Given the following code snippet before the placeholder: <|code_start|>
views = Blueprint('views', __name__)
@views.route('/')
def index():
<|code_end|>
, predict the next line using imports from the current file:
from flask import Blueprint, render_template
from gepify.influxdb import influxdb
and context including class names, function names, and sometimes code from other files:
# Path: gepify/influxdb.py
# class Client:
# def __init__(self):
# def count(self, metric):
. Output only the next line. | influxdb.count('index_page_visits') |
Given the following code snippet before the placeholder: <|code_start|>
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
access_token = session.get('spotify_access_token', None)
refresh_token = session.get('spotify_refresh_token', None)
expires_at = session.get('spotify_expires_at', None)
if access_token is None or refresh_token is None or expires_at is None:
return redirect(url_for('spotify.login'))
now = int(time.time())
if now >= expires_at:
try:
<|code_end|>
, predict the next line using imports from the current file:
from flask import session, redirect, url_for, g, render_template, current_app
from .models import (
get_access_token_from_refresh_token, save_token_data_in_session
)
from functools import wraps
import time
import spotipy
and context including class names, function names, and sometimes code from other files:
# Path: gepify/services/spotify/models.py
# def get_access_token_from_refresh_token(refresh_token):
# """Request access and refresh tokens from refresh token
#
# Parameters
# ----------
# refresh_token : str
# The refresh token from previous authentication.
#
# Raises
# ------
# RuntimeError
# If spotify API gives an error.
# """
# payload = {
# 'refresh_token': refresh_token,
# 'grant_type': 'refresh_token'
# }
#
# return _get_token(payload)
#
# def save_token_data_in_session(access_token_data):
# """Saves token data in session
#
# Parameters
# ----------
# access_token_data : dict
# The token data from get_access_token_from_code
# or get_access_token_from_refresh_token
# """
# access_token = access_token_data['access_token']
# refresh_token = access_token_data['refresh_token']
# expires_at = int(time.time()) + int(access_token_data['expires_in'])
#
# session['spotify_access_token'] = access_token
# if refresh_token:
# session['spotify_refresh_token'] = refresh_token
# session['spotify_expires_at'] = expires_at
. Output only the next line. | token_data = get_access_token_from_refresh_token( |
Using the snippet: <|code_start|>
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
access_token = session.get('spotify_access_token', None)
refresh_token = session.get('spotify_refresh_token', None)
expires_at = session.get('spotify_expires_at', None)
if access_token is None or refresh_token is None or expires_at is None:
return redirect(url_for('spotify.login'))
now = int(time.time())
if now >= expires_at:
try:
token_data = get_access_token_from_refresh_token(
refresh_token)
<|code_end|>
, determine the next line of code. You have imports:
from flask import session, redirect, url_for, g, render_template, current_app
from .models import (
get_access_token_from_refresh_token, save_token_data_in_session
)
from functools import wraps
import time
import spotipy
and context (class names, function names, or code) available:
# Path: gepify/services/spotify/models.py
# def get_access_token_from_refresh_token(refresh_token):
# """Request access and refresh tokens from refresh token
#
# Parameters
# ----------
# refresh_token : str
# The refresh token from previous authentication.
#
# Raises
# ------
# RuntimeError
# If spotify API gives an error.
# """
# payload = {
# 'refresh_token': refresh_token,
# 'grant_type': 'refresh_token'
# }
#
# return _get_token(payload)
#
# def save_token_data_in_session(access_token_data):
# """Saves token data in session
#
# Parameters
# ----------
# access_token_data : dict
# The token data from get_access_token_from_code
# or get_access_token_from_refresh_token
# """
# access_token = access_token_data['access_token']
# refresh_token = access_token_data['refresh_token']
# expires_at = int(time.time()) + int(access_token_data['expires_in'])
#
# session['spotify_access_token'] = access_token
# if refresh_token:
# session['spotify_refresh_token'] = refresh_token
# session['spotify_expires_at'] = expires_at
. Output only the next line. | save_token_data_in_session(token_data) |
Continue the code snippet: <|code_start|> # 'Song is aleady downloading. Will retry in 5 seconds.')
# self.assertTrue(retry.called)
def test_download_song_with_unsupported_provider(self):
with self.assertRaisesRegex(ValueError, 'Provider not found: zamunda'):
songs.download_song({'name': 'song'}, provider='zamunda')
song = songs.get_song('song')
self.assertNotIn('mp3', song['files'])
@mock.patch('gepify.providers.youtube.get_song_id',
side_effect=lambda name: 'dQw4w9WgXcQ')
@mock.patch('gepify.providers.youtube.download_song')
def test_download_song_with_youtube(self, download_song, *args):
songs.download_song({'name': 'song'})
download_song.assert_called_with('dQw4w9WgXcQ', 'mp3')
song = songs.get_song('song')
self.assertEqual(song['files']['mp3'], './songs/dQw4w9WgXcQ.mp3')
@mock.patch('gepify.providers.soundcloud.get_song_id',
side_effect=lambda name: (1234, 'song id'))
@mock.patch('gepify.providers.soundcloud.download_song')
def test_download_song_with_soundcloud(self, download_song, *args):
songs.download_song({'name': 'song'}, provider='soundcloud')
download_song.assert_called_with('song id', 'mp3')
song = songs.get_song('song')
self.assertEqual(song['files']['mp3'], './songs/1234.mp3')
class PlaylistsTestCase(TestCase):
def setUp(self):
<|code_end|>
. Use current file imports:
from unittest import mock, TestCase
from gepify.providers import songs, playlists, youtube, soundcloud
from werkzeug.contrib.cache import SimpleCache
import json
import time
import os
and context (classes, functions, or code) from other files:
# Path: gepify/providers/songs.py
# def get_song(song_name):
# def add_song_file(song_name, file, format):
# def has_song_format(song_name, format):
# def download_song(self, song_info, provider='youtube', format='mp3'):
#
# Path: gepify/providers/playlists.py
# def get_playlist(service, playlist, format):
# def has_playlist(service, playlist, format):
# def checksum(tracks):
# def handle_error(playlist_cache_key):
# def create_zip_playlist(playlist, service, checksum, format='mp3'):
# def download_playlist(playlist, service, provider='youtube', format='mp3'):
# def clean_playlists():
#
# Path: gepify/providers/youtube.py
# DEVELOPER_KEY = os.environ.get('YOUTUBE_DEVELOPER_KEY')
# YOUTUBE_API_SERVICE_NAME = 'youtube'
# YOUTUBE_API_VERSION = 'v3'
# def get_song_id(song_name):
# def download_song(id, format):
#
# Path: gepify/providers/soundcloud.py
# SOUNDCLOUD_CLIENT_ID = os.environ.get('SOUNDCLOUD_CLIENT_ID')
# def get_song_id(song_name):
# def download_song(id, format):
. Output only the next line. | playlists.cache = SimpleCache() |
Next line prediction: <|code_start|>
playlist = playlists.cache.get('spotify_1234_mp3')
self.assertEqual(playlist['path'], './playlists/spotify_1234_mp3.zip')
self.assertEqual(playlist['checksum'], checksum)
class mocked_Resource():
def __init__(self, *args, **kwargs):
self.result = []
def search(self):
return self
def list(self, *args, **kwargs):
if kwargs['q'] == 'existing song':
with open('tests/youtube_dump.json') as f:
self.result = json.loads(f.read())
return self
def execute(self):
return self
def get(self, *args, **kwargs):
return self.result
class YoutubeTestCase(TestCase):
@mock.patch('googleapiclient.discovery.Resource',
side_effect=mocked_Resource)
def test_get_song_id(self, Resource):
<|code_end|>
. Use current file imports:
(from unittest import mock, TestCase
from gepify.providers import songs, playlists, youtube, soundcloud
from werkzeug.contrib.cache import SimpleCache
import json
import time
import os)
and context including class names, function names, or small code snippets from other files:
# Path: gepify/providers/songs.py
# def get_song(song_name):
# def add_song_file(song_name, file, format):
# def has_song_format(song_name, format):
# def download_song(self, song_info, provider='youtube', format='mp3'):
#
# Path: gepify/providers/playlists.py
# def get_playlist(service, playlist, format):
# def has_playlist(service, playlist, format):
# def checksum(tracks):
# def handle_error(playlist_cache_key):
# def create_zip_playlist(playlist, service, checksum, format='mp3'):
# def download_playlist(playlist, service, provider='youtube', format='mp3'):
# def clean_playlists():
#
# Path: gepify/providers/youtube.py
# DEVELOPER_KEY = os.environ.get('YOUTUBE_DEVELOPER_KEY')
# YOUTUBE_API_SERVICE_NAME = 'youtube'
# YOUTUBE_API_VERSION = 'v3'
# def get_song_id(song_name):
# def download_song(id, format):
#
# Path: gepify/providers/soundcloud.py
# SOUNDCLOUD_CLIENT_ID = os.environ.get('SOUNDCLOUD_CLIENT_ID')
# def get_song_id(song_name):
# def download_song(id, format):
. Output only the next line. | song_id = youtube.get_song_id('existing song') |
Given the code snippet: <|code_start|> youtube.download_song('song id', 'mp3')
self.assertEqual(download.call_count, 1)
download.assert_called_with(['http://www.youtube.com/watch?v=song id'])
class mocked_Response():
def __init__(self, obj):
self.obj = obj
class mocked_Client():
def __init__(self, *args, **kwargs):
pass
def get(self, resource, q):
if q == 'existing song':
return [mocked_Response({
'id': '1234',
'permalink': 'song_permalink',
'user': {
'permalink': 'user_permalink'
}
})]
return []
class SoundcloudTestCase(TestCase):
@mock.patch('soundcloud.Client', side_effect=mocked_Client)
def test_get_song_id(self, Client):
<|code_end|>
, generate the next line using the imports in this file:
from unittest import mock, TestCase
from gepify.providers import songs, playlists, youtube, soundcloud
from werkzeug.contrib.cache import SimpleCache
import json
import time
import os
and context (functions, classes, or occasionally code) from other files:
# Path: gepify/providers/songs.py
# def get_song(song_name):
# def add_song_file(song_name, file, format):
# def has_song_format(song_name, format):
# def download_song(self, song_info, provider='youtube', format='mp3'):
#
# Path: gepify/providers/playlists.py
# def get_playlist(service, playlist, format):
# def has_playlist(service, playlist, format):
# def checksum(tracks):
# def handle_error(playlist_cache_key):
# def create_zip_playlist(playlist, service, checksum, format='mp3'):
# def download_playlist(playlist, service, provider='youtube', format='mp3'):
# def clean_playlists():
#
# Path: gepify/providers/youtube.py
# DEVELOPER_KEY = os.environ.get('YOUTUBE_DEVELOPER_KEY')
# YOUTUBE_API_SERVICE_NAME = 'youtube'
# YOUTUBE_API_VERSION = 'v3'
# def get_song_id(song_name):
# def download_song(id, format):
#
# Path: gepify/providers/soundcloud.py
# SOUNDCLOUD_CLIENT_ID = os.environ.get('SOUNDCLOUD_CLIENT_ID')
# def get_song_id(song_name):
# def download_song(id, format):
. Output only the next line. | song_id, download_id = soundcloud.get_song_id('existing song') |
Given the following code snippet before the placeholder: <|code_start|>"""
Minimum Description Length Principle (MDLP) binning
- Original paper: http://sci2s.ugr.es/keel/pdf/algorithm/congreso/fayyad1993.pdf
- Implementation inspiration: https://www.ibm.com/support/knowledgecenter/it/SSLVMB_21.0.0/com.ibm.spss.statistics.help/alg_optimal-binning.htm
"""
<|code_end|>
, predict the next line using imports from the current file:
import collections
import math
import numpy as np
from scipy import stats
from sklearn.utils import check_X_y
from .base import BaseSupervisedBinner
and context including class names, function names, and sometimes code from other files:
# Path: xam/preprocessing/binning/base.py
# class BaseSupervisedBinner(BaseBinner):
#
# def fit(X, y, **fit_params):
# raise NotImplementedError
. Output only the next line. | class MDLPBinner(BaseSupervisedBinner): |
Continue the code snippet: <|code_start|>"""
Bayesian blocks binning. Good for visualization.
References:
- http://adsabs.harvard.edu/abs/2012arXiv1207.5578S
- https://jakevdp.github.io/blog/2012/09/12/dynamic-programming-in-python/
"""
<|code_end|>
. Use current file imports:
import numpy as np
from sklearn.utils import check_array
from .base import BaseUnsupervisedBinner
and context (classes, functions, or code) from other files:
# Path: xam/preprocessing/binning/base.py
# class BaseUnsupervisedBinner(BaseBinner):
#
# def fit(X, y=None, **fit_params):
# raise NotImplementedError
. Output only the next line. | class BayesianBlocksBinner(BaseUnsupervisedBinner): |
Given the code snippet: <|code_start|>
class DistributionResampler():
def __init__(self, column=0, sample_frac=0.5, n_bins=100, seed=None):
super().__init__()
self.column = column
self.sample_frac = sample_frac
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import pandas as pd
from .binning.equal_frequency import EqualFrequencyBinner
and context (functions, classes, or occasionally code) from other files:
# Path: xam/preprocessing/binning/equal_frequency.py
# class EqualFrequencyBinner(BaseUnsupervisedBinner):
#
# def __init__(self, n_bins=5):
#
# super().__init__()
#
# # Properties
# self.n_bins = n_bins
#
# def fit(self, X, y=None, **fit_params):
# """Choose equally spaces cut points."""
#
# # scikit-learn checks
# X = check_array(X)
#
# step = 100 / self.n_bins
#
# self.cut_points_ = np.stack([
# np.percentile(X, q, axis=0)
# for q in np.arange(start=step, stop=100, step=step)
# ], axis=-1).tolist()
#
# return self
#
# @property
# def cut_points(self):
# return self.cut_points_
. Output only the next line. | self.binner = EqualFrequencyBinner(n_bins=n_bins) |
Given snippet: <|code_start|>class TutorialDoc(Document):
doc_type = 'tutorial'
author = DictField(Mapping.build(
name = TextField(),
email = TextField(),
jabber = TextField(),
website = TextField()
))
clientversion = TextField()
links = ListField(
DictField(Mapping.build(
linktext = TextField(),
url = TextField()
))
)
tutorial = ListField(
DictField(Mapping.build(
image = TextField(),
text = TextField()
))
)
all_tutorials = ViewField('tutorial', '''\
function (doc) {
if (doc.doc_type == 'tutorial') {
emit(doc._id, doc);
};
}''')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flaskext.couchdb import BooleanField, DateTimeField, Document, \
DictField, ListField, Mapping, TextField, ViewField
from einfachjabber.extensions import db
and context:
# Path: einfachjabber/extensions.py
which might include code, classes, or functions. Output only the next line. | db.add_document(TutorialDoc) |
Predict the next line for this snippet: <|code_start|> :param data: data for mail-forming, depends on mailtype
'''
if data:
if mailtype is 'mailreminder':
msg = Message('[einfachJabber.de] Jabber-Konto Registrierung')
msg.body = u'''
einfachJabber.de
Du hast eben über http://einfachjabber.de einen neuen
Jabber-Account registriert.
Die Benutzerdaten dazu lauten:
Benutzername: %s
Passwort: %s
Auf http://einfachjabber.de findest du Anleitungen für
verschiedene Client-Programme.
''' % (data[1], data[2])
msg.recipients = [data[0]]
if mailtype is 'rating':
msg = Message('[einfachJabber.de] Tutorialbewertung')
msg.body = u'''
einfachJabber.de Tutorialbewertung
Bewertung: %s
Vorschlag: %s
Tutorial: %s
''' % (data[0], data[1], data[2])
msg.recipients = ['bz@einfachjabber.de']
<|code_end|>
with the help of current file imports:
from os import path, chdir
from glob import glob
from datetime import datetime
from creoleparser.dialects import create_dialect, creole10_base, creole11_base
from creoleparser.core import Parser
from flaskext.mail import Message
from einfachjabber.extensions import mail
from flask import abort, current_app
import json
and context from other files:
# Path: einfachjabber/extensions.py
, which may contain function names, class names, or code. Output only the next line. | mail.send(msg) |
Based on the snippet: <|code_start|> chunk_offset = struct.unpack(fmt, self.fh.read(fmt_size))
chunk_address = struct.unpack('<Q', self.fh.read(8))[0]
keys.append(OrderedDict((
('chunk_size', chunk_size),
('filter_mask', filter_mask),
('chunk_offset', chunk_offset),
)))
addresses.append(chunk_address)
node['keys'] = keys
node['addresses'] = addresses
return node
def construct_data_from_chunks(
self, chunk_shape, data_shape, dtype, filter_pipeline):
""" Build a complete data array from chunks. """
if isinstance(dtype, tuple):
true_dtype = tuple(dtype)
dtype_class = dtype[0]
if dtype_class == 'REFERENCE':
size = dtype[1]
if size != 8:
raise NotImplementedError('Unsupported Reference type')
dtype = '<u8'
else:
raise NotImplementedError('datatype not implemented')
else:
true_dtype = None
# create array to store data
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import OrderedDict
from .core import _padded_size
from .core import _unpack_struct_from_file
from .core import Reference
import struct
import zlib
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# Path: pyfive/core.py
# def _unpack_struct_from_file(structure, fh):
# """ Unpack a structure into an OrderedDict from an open file. """
# size = _structure_size(structure)
# buf = fh.read(size)
# return _unpack_struct_from(structure, buf)
#
# Path: pyfive/core.py
# class Reference(object):
# """
# HDF5 Reference.
# """
#
# def __init__(self, address_of_reference):
# self.address_of_reference = address_of_reference
#
# def __bool__(self):
# # False for null references (address of 0) True otherwise
# return bool(self.address_of_reference)
#
# __nonzero__ = __bool__ # Python 2.x requires __nonzero__ for truth value
. Output only the next line. | shape = [_padded_size(i, j) for i, j in zip(data_shape, chunk_shape)] |
Based on the snippet: <|code_start|>class BTree(object):
"""
HDF5 version 1 B-Tree.
"""
def __init__(self, fh, offset):
""" initalize. """
self.fh = fh
# read in the root node
root_node = self._read_node(offset)
self.root_node = root_node
# read in all nodes
all_nodes = {}
node_level = root_node['node_level']
all_nodes[node_level] = [root_node]
while node_level != 0:
new_nodes = []
for parent_node in all_nodes[node_level]:
for addr in parent_node['addresses']:
new_nodes.append(self._read_node(addr))
new_node_level = new_nodes[0]['node_level']
all_nodes[new_node_level] = new_nodes
node_level = new_node_level
self.all_nodes = all_nodes
def _read_node(self, offset):
""" Return a single node in the B-Tree located at a given offset. """
self.fh.seek(offset)
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import OrderedDict
from .core import _padded_size
from .core import _unpack_struct_from_file
from .core import Reference
import struct
import zlib
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# Path: pyfive/core.py
# def _unpack_struct_from_file(structure, fh):
# """ Unpack a structure into an OrderedDict from an open file. """
# size = _structure_size(structure)
# buf = fh.read(size)
# return _unpack_struct_from(structure, buf)
#
# Path: pyfive/core.py
# class Reference(object):
# """
# HDF5 Reference.
# """
#
# def __init__(self, address_of_reference):
# self.address_of_reference = address_of_reference
#
# def __bool__(self):
# # False for null references (address of 0) True otherwise
# return bool(self.address_of_reference)
#
# __nonzero__ = __bool__ # Python 2.x requires __nonzero__ for truth value
. Output only the next line. | node = _unpack_struct_from_file(B_LINK_NODE_V1, self.fh) |
Continue the code snippet: <|code_start|> raise NotImplementedError('datatype not implemented')
else:
true_dtype = None
# create array to store data
shape = [_padded_size(i, j) for i, j in zip(data_shape, chunk_shape)]
data = np.zeros(shape, dtype=dtype)
# loop over chunks reading each into the full data array
count = np.prod(chunk_shape)
itemsize = np.dtype(dtype).itemsize
chunk_buffer_size = count * itemsize
for node in self.all_nodes[0]:
for node_key, addr in zip(node['keys'], node['addresses']):
self.fh.seek(addr)
if filter_pipeline is None:
chunk_buffer = self.fh.read(chunk_buffer_size)
else:
chunk_buffer = self.fh.read(node_key['chunk_size'])
filter_mask = node_key['filter_mask']
chunk_buffer = self._filter_chunk(
chunk_buffer, filter_mask, filter_pipeline, itemsize)
chunk_data = np.frombuffer(chunk_buffer, dtype=dtype)
start = node_key['chunk_offset'][:-1]
region = [slice(i, i+j) for i, j in zip(start, chunk_shape)]
data[tuple(region)] = chunk_data.reshape(chunk_shape)
if isinstance(true_dtype, tuple):
if dtype_class == 'REFERENCE':
<|code_end|>
. Use current file imports:
from collections import OrderedDict
from .core import _padded_size
from .core import _unpack_struct_from_file
from .core import Reference
import struct
import zlib
import numpy as np
and context (classes, functions, or code) from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# Path: pyfive/core.py
# def _unpack_struct_from_file(structure, fh):
# """ Unpack a structure into an OrderedDict from an open file. """
# size = _structure_size(structure)
# buf = fh.read(size)
# return _unpack_struct_from(structure, buf)
#
# Path: pyfive/core.py
# class Reference(object):
# """
# HDF5 Reference.
# """
#
# def __init__(self, address_of_reference):
# self.address_of_reference = address_of_reference
#
# def __bool__(self):
# # False for null references (address of 0) True otherwise
# return bool(self.address_of_reference)
#
# __nonzero__ = __bool__ # Python 2.x requires __nonzero__ for truth value
. Output only the next line. | to_reference = np.vectorize(Reference) |
Here is a snippet: <|code_start|>
DIRNAME = os.path.dirname(__file__)
DATASET_FLETCHER_HDF5_FILE = os.path.join(DIRNAME, 'fletcher32.hdf5')
def test_fletcher32_datasets():
with pyfive.File(DATASET_FLETCHER_HDF5_FILE) as hfile:
# check data
dset1 = hfile['dataset1']
assert_array_equal(dset1[:], np.arange(4*4).reshape((4, 4)))
assert dset1.chunks == (2, 2)
# check data
dset2 = hfile['dataset2']
assert_array_equal(dset2[:], np.arange(3))
assert dset2.chunks == (3, )
# check attribute
assert dset1.fletcher32
class TestChunkFletcher32(unittest.TestCase):
def test_fletcher32_invalid(self):
bad_chunk = b'\x00\x00\x00\x01'
with self.assertRaises(ValueError) as context:
<|code_end|>
. Write the next line using the current file imports:
import os
import unittest
import numpy as np
import pyfive
from numpy.testing import assert_array_equal
from pyfive.btree import _verify_fletcher32
and context from other files:
# Path: pyfive/btree.py
# def _verify_fletcher32(chunk_buffer):
# """ Verify a chunk with a fletcher32 checksum. """
# # calculate checksums
# if len(chunk_buffer) % 2:
# arr = np.frombuffer(chunk_buffer[:-4]+b'\x00', '<u2')
# else:
# arr = np.frombuffer(chunk_buffer[:-4], '<u2')
# sum1 = sum2 = 0
# for i in arr:
# sum1 = (sum1 + i) % 65535
# sum2 = (sum2 + sum1) % 65535
#
# # extract stored checksums
# ref_sum1, ref_sum2 = np.frombuffer(chunk_buffer[-4:], '>u2')
# ref_sum1 = ref_sum1 % 65535
# ref_sum2 = ref_sum2 % 65535
#
# # compare
# if sum1 != ref_sum1 or sum2 != ref_sum2:
# raise ValueError("fletcher32 checksum invalid")
# return True
, which may include functions, classes, or code. Output only the next line. | _verify_fletcher32(bad_chunk) |
Predict the next line for this snippet: <|code_start|>
def __init__(self, fh, offset):
fh.seek(offset)
header = _unpack_struct_from_file(GLOBAL_HEAP_HEADER, fh)
assert header['signature'] == b'GCOL'
assert header['version'] == 1
heap_data_size = header['collection_size'] - GLOBAL_HEAP_HEADER_SIZE
heap_data = fh.read(heap_data_size)
assert len(heap_data) == heap_data_size # check for early end of file
self.heap_data = heap_data
self._header = header
self._objects = None
@property
def objects(self):
""" Dictionary of objects in the heap. """
if self._objects is None:
self._objects = OrderedDict()
offset = 0
while offset < len(self.heap_data):
info = _unpack_struct_from(
GLOBAL_HEAP_OBJECT, self.heap_data, offset)
if info['object_index'] == 0:
break
offset += GLOBAL_HEAP_OBJECT_SIZE
fmt = '<' + str(info['object_size']) + 's'
obj_data = struct.unpack_from(fmt, self.heap_data, offset)[0]
self._objects[info['object_index']] = obj_data
<|code_end|>
with the help of current file imports:
import struct
from collections import OrderedDict
from .core import _padded_size, _structure_size
from .core import _unpack_struct_from, _unpack_struct_from_file
from .core import InvalidHDF5File
and context from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# Path: pyfive/core.py
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# def _unpack_struct_from_file(structure, fh):
# """ Unpack a structure into an OrderedDict from an open file. """
# size = _structure_size(structure)
# buf = fh.read(size)
# return _unpack_struct_from(structure, buf)
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
, which may contain function names, class names, or code. Output only the next line. | offset += _padded_size(info['object_size']) |
Using the snippet: <|code_start|> return self._objects
FORMAT_SIGNATURE = b'\211HDF\r\n\032\n'
# Version 0 SUPERBLOCK
SUPERBLOCK_V0 = OrderedDict((
('format_signature', '8s'),
('superblock_version', 'B'),
('free_storage_version', 'B'),
('root_group_version', 'B'),
('reserved_0', 'B'),
('shared_header_version', 'B'),
('offset_size', 'B'), # assume 8
('length_size', 'B'), # assume 8
('reserved_1', 'B'),
('group_leaf_node_k', 'H'),
('group_internal_node_k', 'H'),
('file_consistency_flags', 'L'),
('base_address', 'Q'), # assume 8 byte addressing
('free_space_address', 'Q'), # assume 8 byte addressing
('end_of_file_address', 'Q'), # assume 8 byte addressing
('driver_information_address', 'Q'), # assume 8 byte addressing
))
<|code_end|>
, determine the next line of code. You have imports:
import struct
from collections import OrderedDict
from .core import _padded_size, _structure_size
from .core import _unpack_struct_from, _unpack_struct_from_file
from .core import InvalidHDF5File
and context (class names, function names, or code) available:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# Path: pyfive/core.py
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# def _unpack_struct_from_file(structure, fh):
# """ Unpack a structure into an OrderedDict from an open file. """
# size = _structure_size(structure)
# buf = fh.read(size)
# return _unpack_struct_from(structure, buf)
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
. Output only the next line. | SUPERBLOCK_V0_SIZE = _structure_size(SUPERBLOCK_V0) |
Given the code snippet: <|code_start|> links[e['link_name']] = heap.get_object_name(offset).decode('utf-8')
return links
class GlobalHeap(object):
"""
HDF5 Global Heap collection.
"""
def __init__(self, fh, offset):
fh.seek(offset)
header = _unpack_struct_from_file(GLOBAL_HEAP_HEADER, fh)
assert header['signature'] == b'GCOL'
assert header['version'] == 1
heap_data_size = header['collection_size'] - GLOBAL_HEAP_HEADER_SIZE
heap_data = fh.read(heap_data_size)
assert len(heap_data) == heap_data_size # check for early end of file
self.heap_data = heap_data
self._header = header
self._objects = None
@property
def objects(self):
""" Dictionary of objects in the heap. """
if self._objects is None:
self._objects = OrderedDict()
offset = 0
while offset < len(self.heap_data):
<|code_end|>
, generate the next line using the imports in this file:
import struct
from collections import OrderedDict
from .core import _padded_size, _structure_size
from .core import _unpack_struct_from, _unpack_struct_from_file
from .core import InvalidHDF5File
and context (functions, classes, or occasionally code) from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# Path: pyfive/core.py
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# def _unpack_struct_from_file(structure, fh):
# """ Unpack a structure into an OrderedDict from an open file. """
# size = _structure_size(structure)
# buf = fh.read(size)
# return _unpack_struct_from(structure, buf)
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
. Output only the next line. | info = _unpack_struct_from( |
Predict the next line after this snippet: <|code_start|>""" Misc low-level representation of HDF5 objects. """
class SuperBlock(object):
"""
HDF5 Superblock.
"""
def __init__(self, fh, offset):
""" initalize. """
fh.seek(offset)
version_hint = struct.unpack_from('<B', fh.read(9), 8)[0]
fh.seek(offset)
if version_hint == 0:
<|code_end|>
using the current file's imports:
import struct
from collections import OrderedDict
from .core import _padded_size, _structure_size
from .core import _unpack_struct_from, _unpack_struct_from_file
from .core import InvalidHDF5File
and any relevant context from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# Path: pyfive/core.py
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# def _unpack_struct_from_file(structure, fh):
# """ Unpack a structure into an OrderedDict from an open file. """
# size = _structure_size(structure)
# buf = fh.read(size)
# return _unpack_struct_from(structure, buf)
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
. Output only the next line. | contents = _unpack_struct_from_file(SUPERBLOCK_V0, fh) |
Next line prediction: <|code_start|>""" Misc low-level representation of HDF5 objects. """
class SuperBlock(object):
"""
HDF5 Superblock.
"""
def __init__(self, fh, offset):
""" initalize. """
fh.seek(offset)
version_hint = struct.unpack_from('<B', fh.read(9), 8)[0]
fh.seek(offset)
if version_hint == 0:
contents = _unpack_struct_from_file(SUPERBLOCK_V0, fh)
self._end_of_sblock = offset + SUPERBLOCK_V0_SIZE
elif version_hint == 2 or version_hint == 3:
contents = _unpack_struct_from_file(SUPERBLOCK_V2_V3, fh)
self._end_of_sblock = offset + SUPERBLOCK_V2_V3_SIZE
else:
raise NotImplementedError(
"unsupported superblock version: %i" % (version_hint))
# verify contents
if contents['format_signature'] != FORMAT_SIGNATURE:
<|code_end|>
. Use current file imports:
(import struct
from collections import OrderedDict
from .core import _padded_size, _structure_size
from .core import _unpack_struct_from, _unpack_struct_from_file
from .core import InvalidHDF5File)
and context including class names, function names, or small code snippets from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# Path: pyfive/core.py
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# def _unpack_struct_from_file(structure, fh):
# """ Unpack a structure into an OrderedDict from an open file. """
# size = _structure_size(structure)
# buf = fh.read(size)
# return _unpack_struct_from(structure, buf)
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
. Output only the next line. | raise InvalidHDF5File('Incorrect file signature') |
Using the snippet: <|code_start|>
dtype_char = 'f'
byte_order = datatype_msg['class_bit_field_0'] & 0x01
if byte_order == 0:
byte_order_char = '<' # little-endian
else:
byte_order_char = '>' # big-endian
# 12-bytes floating-point property description
# not read, assumed to be IEEE standard format
self.offset += 12
return byte_order_char + dtype_char + str(length_in_bytes)
@staticmethod
def _determine_dtype_string(datatype_msg):
""" Return the NumPy dtype for a string class. """
return 'S' + str(datatype_msg['size'])
def _determine_dtype_compound(self, datatype_msg):
""" Return the dtype of a compound class if supported. """
bit_field_0 = datatype_msg['class_bit_field_0']
bit_field_1 = datatype_msg['class_bit_field_1']
n_comp = bit_field_0 + (bit_field_1 << 4)
# read in the members of the compound datatype
members = []
for _ in range(n_comp):
null_location = self.buf.index(b'\x00', self.offset)
<|code_end|>
, determine the next line of code. You have imports:
from collections import OrderedDict
from .core import _padded_size, _structure_size, _unpack_struct_from
from .core import InvalidHDF5File
and context (class names, function names, or code) available:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
. Output only the next line. | name_size = _padded_size(null_location - self.offset, 8) |
Given the following code snippet before the placeholder: <|code_start|> prop2['dim_size_1'] == 0 and
prop2['dim_size_2'] == 0 and
prop2['dim_size_3'] == 0 and
prop2['dim_size_4'] == 0
)
if names_valid and dtypes_valid and offsets_valid and props_valid:
return complex_dtype_map[dtype1]
raise NotImplementedError("Compond dtype not supported.")
@staticmethod
def _determine_dtype_vlen(datatype_msg):
""" Return the dtype information for a variable length class. """
vlen_type = datatype_msg['class_bit_field_0'] & 0x01
if vlen_type != 1:
return ('VLEN_SEQUENCE', 0, 0)
padding_type = datatype_msg['class_bit_field_0'] >> 4 # bits 4-7
character_set = datatype_msg['class_bit_field_1'] & 0x01
return ('VLEN_STRING', padding_type, character_set)
# IV.A.2.d The Datatype Message
DATATYPE_MSG = OrderedDict((
('class_and_version', 'B'),
('class_bit_field_0', 'B'),
('class_bit_field_1', 'B'),
('class_bit_field_2', 'B'),
('size', 'I'),
))
<|code_end|>
, predict the next line using imports from the current file:
from collections import OrderedDict
from .core import _padded_size, _structure_size, _unpack_struct_from
from .core import InvalidHDF5File
and context including class names, function names, and sometimes code from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
. Output only the next line. | DATATYPE_MSG_SIZE = _structure_size(DATATYPE_MSG) |
Continue the code snippet: <|code_start|>""" Representation and reading of HDF5 datatype messages. """
class DatatypeMessage(object):
""" Representation of a HDF5 Datatype Message. """
# Contents and layout defined in IV.A.2.d.
def __init__(self, buf, offset):
self.buf = buf
self.offset = offset
self.dtype = self.determine_dtype()
def determine_dtype(self):
""" Return the dtype (often numpy-like) for the datatype message. """
<|code_end|>
. Use current file imports:
from collections import OrderedDict
from .core import _padded_size, _structure_size, _unpack_struct_from
from .core import InvalidHDF5File
and context (classes, functions, or code) from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
. Output only the next line. | datatype_msg = _unpack_struct_from(DATATYPE_MSG, self.buf, self.offset) |
Predict the next line after this snippet: <|code_start|> # last 4 bits
datatype_class = datatype_msg['class_and_version'] & 0x0F
if datatype_class == DATATYPE_FIXED_POINT:
return self._determine_dtype_fixed_point(datatype_msg)
elif datatype_class == DATATYPE_FLOATING_POINT:
return self._determine_dtype_floating_point(datatype_msg)
elif datatype_class == DATATYPE_TIME:
raise NotImplementedError("Time datatype class not supported.")
elif datatype_class == DATATYPE_STRING:
return self._determine_dtype_string(datatype_msg)
elif datatype_class == DATATYPE_BITFIELD:
raise NotImplementedError("Bitfield datatype class not supported.")
elif datatype_class == DATATYPE_OPAQUE:
raise NotImplementedError("Opaque datatype class not supported.")
elif datatype_class == DATATYPE_COMPOUND:
return self._determine_dtype_compound(datatype_msg)
elif datatype_class == DATATYPE_REFERENCE:
return ('REFERENCE', datatype_msg['size'])
elif datatype_class == DATATYPE_ENUMERATED:
raise NotImplementedError(
"Enumerated datatype class not supported.")
elif datatype_class == DATATYPE_ARRAY:
raise NotImplementedError("Array datatype class not supported.")
elif datatype_class == DATATYPE_VARIABLE_LENGTH:
vlen_type = self._determine_dtype_vlen(datatype_msg)
if vlen_type[0] == 'VLEN_SEQUENCE':
base_type = self.determine_dtype()
vlen_type = ('VLEN_SEQUENCE', base_type)
return vlen_type
<|code_end|>
using the current file's imports:
from collections import OrderedDict
from .core import _padded_size, _structure_size, _unpack_struct_from
from .core import InvalidHDF5File
and any relevant context from other files:
# Path: pyfive/core.py
# def _padded_size(size, padding_multipe=8):
# """ Return the size of a field padded to be a multiple a give value. """
# return int(ceil(size / padding_multipe) * padding_multipe)
#
# def _structure_size(structure):
# """ Return the size of a structure in bytes. """
# fmt = '<' + ''.join(structure.values())
# return struct.calcsize(fmt)
#
# def _unpack_struct_from(structure, buf, offset=0):
# """ Unpack a structure into an OrderedDict from a buffer of bytes. """
# fmt = '<' + ''.join(structure.values())
# values = struct.unpack_from(fmt, buf, offset=offset)
# return OrderedDict(zip(structure.keys(), values))
#
# Path: pyfive/core.py
# class InvalidHDF5File(Exception):
# """ Exception raised when an invalid HDF5 file is detected. """
# pass
. Output only the next line. | raise InvalidHDF5File('Invalid datatype class %i' % (datatype_class)) |
Predict the next line after this snippet: <|code_start|># assign the RHS definitions for the ODE, the vardict dictionary,
# to the varspecs attribute of DSargs
DSargs.varspecs = vardict
# Create an object representing the implementation of the model.
# In PyDSTool, this is known as a Generator object, because
# it can numerically compute ("generate") trajectories using the VODE
# integration scheme.
DS = Generator.Vode_ODEsystem(DSargs)
# This shows how to change just these entries once the Generator has been created
DS.set(ics={'v': -75})
# A function that tests the outcome of a given value of parameter tau
def test_tau(tau):
DS.set(pars={'tau': tau},
algparams={'init_step': min(tau/2,0.5)})
traj = DS.compute('test')
pts = traj.sample()
return pts
# A loop to test a distribution of values of tau
for tau in 40*exp(-linspace(1, 6, 6)):
pts = test_tau(tau)
plt.plot(pts['t'], pts['v'], '.-', label='tau=%.3f (VODE)' %tau)
# Find solutions using Euler integration
def test_tau_euler(tau, step, symb):
DS.set(pars={'tau': tau})
print "Testing Euler method with tau =", tau
<|code_end|>
using the current file's imports:
from PyDSTool import *
from euler import euler_integrate
and any relevant context from other files:
# Path: euler.py
# def euler_integrate(DS, t0, t1, dt, x0):
# ts = linspace(t0, t1, (t1-t0)/dt)
# xs = zeros(len(ts), float)
# x = x0
# for i, t in enumerate(ts):
# xs[i] = x
# x = euler_step(DS, t, x, dt)
# return ts, xs
. Output only the next line. | ts, vs = euler_integrate(DS, 0, 20, step, DS.initialconditions['v']) |
Next line prediction: <|code_start|> except OSError:
# directory was created and populated with images in a
# previous run => keep it
pass
# cannot set albums => empty subdirs so that no albums are
# generated
album.subdirs = []
album.medias = []
else:
with open(nomediapath) as nomediaFile:
logger.info("Found a .nomedia file in %s, ignoring its entries", album.name)
ignored = nomediaFile.read().split("\n")
album.medias = [
media for media in album.medias if media.src_filename not in ignored
]
album.subdirs = [
dirname for dirname in album.subdirs if dirname not in ignored
]
# subdirs have been added to the gallery already, remove
# them there, too
_remove_albums_with_subdirs(
album.gallery.albums, ignored, album.path + os.path.sep
)
def register(settings):
<|code_end|>
. Use current file imports:
(import logging
import os
from sigal import signals)
and context including class names, function names, or small code snippets from other files:
# Path: sigal/signals.py
. Output only the next line. | signals.album_initialized.connect(filter_nomedia) |
Given snippet: <|code_start|>
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
def test_read_settings(settings):
"""Test that the settings are correctly read."""
assert settings['img_size'] == (640, 480)
assert settings['thumb_size'] == (200, 150)
assert settings['thumb_suffix'] == '.tn'
assert settings['source'] == os.path.join(CURRENT_DIR, 'sample', 'pictures')
def test_get_thumb(settings):
"""Test the get_thumb function."""
tests = [
('example.jpg', 'thumbnails/example.tn.jpg'),
('test/example.jpg', 'test/thumbnails/example.tn.jpg'),
('test/t/example.jpg', 'test/t/thumbnails/example.tn.jpg'),
]
for src, ref in tests:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from sigal.settings import get_thumb, read_settings
and context:
# Path: sigal/settings.py
# def get_thumb(settings, filename):
# """Return the path to the thumb.
#
# examples:
# >>> default_settings = create_settings()
# >>> get_thumb(default_settings, "bar/foo.jpg")
# "bar/thumbnails/foo.jpg"
# >>> get_thumb(default_settings, "bar/foo.png")
# "bar/thumbnails/foo.png"
#
# for videos, it returns a jpg file:
# >>> get_thumb(default_settings, "bar/foo.webm")
# "bar/thumbnails/foo.jpg"
# """
#
# path, filen = os.path.split(filename)
# name, ext = os.path.splitext(filen)
#
# if ext.lower() in settings['video_extensions']:
# ext = '.jpg'
# return join(
# path,
# settings['thumb_dir'],
# settings['thumb_prefix'] + name + settings['thumb_suffix'] + ext,
# )
#
# def read_settings(filename=None):
# """Read settings from a config file in the source_dir root."""
#
# logger = logging.getLogger(__name__)
# logger.info("Reading settings ...")
# settings = _DEFAULT_CONFIG.copy()
#
# if filename:
# logger.debug("Settings file: %s", filename)
# settings_path = os.path.dirname(filename)
# tempdict = {}
#
# with open(filename) as f:
# code = compile(f.read(), filename, 'exec')
# exec(code, tempdict)
#
# settings.update(
# (k, v) for k, v in tempdict.items() if k not in ['__builtins__']
# )
#
# # Make the paths relative to the settings file
# paths = ['source', 'destination', 'watermark']
#
# if os.path.isdir(join(settings_path, settings['theme'])) and os.path.isdir(
# join(settings_path, settings['theme'], 'templates')
# ):
# paths.append('theme')
#
# for p in paths:
# path = settings[p]
# if path and not isabs(path):
# settings[p] = abspath(normpath(join(settings_path, path)))
# logger.debug("Rewrite %s : %s -> %s", p, path, settings[p])
#
# for key in ('img_size', 'thumb_size', 'video_size'):
# if settings[key]:
# w, h = settings[key]
# if h > w:
# settings[key] = (h, w)
# logger.warning(
# "The %s setting should be specified with the largest value first.",
# key,
# )
#
# if not settings['img_processor']:
# logger.info('No Processor, images will not be resized')
#
# logger.debug('Settings:\n%s', pformat(settings, width=120))
# return settings
which might include code, classes, or functions. Output only the next line. | assert get_thumb(settings, src) == ref |
Using the snippet: <|code_start|> assert settings['thumb_size'] == (200, 150)
assert settings['thumb_suffix'] == '.tn'
assert settings['source'] == os.path.join(CURRENT_DIR, 'sample', 'pictures')
def test_get_thumb(settings):
"""Test the get_thumb function."""
tests = [
('example.jpg', 'thumbnails/example.tn.jpg'),
('test/example.jpg', 'test/thumbnails/example.tn.jpg'),
('test/t/example.jpg', 'test/t/thumbnails/example.tn.jpg'),
]
for src, ref in tests:
assert get_thumb(settings, src) == ref
tests = [
('example.webm', 'thumbnails/example.tn.jpg'),
('test/example.mp4', 'test/thumbnails/example.tn.jpg'),
('test/t/example.avi', 'test/t/thumbnails/example.tn.jpg'),
]
for src, ref in tests:
assert get_thumb(settings, src) == ref
def test_img_sizes(tmpdir):
"""Test that image size is swaped if needed."""
conf = tmpdir.join('sigal.conf.py')
conf.write("thumb_size = (150, 200)")
<|code_end|>
, determine the next line of code. You have imports:
import os
from sigal.settings import get_thumb, read_settings
and context (class names, function names, or code) available:
# Path: sigal/settings.py
# def get_thumb(settings, filename):
# """Return the path to the thumb.
#
# examples:
# >>> default_settings = create_settings()
# >>> get_thumb(default_settings, "bar/foo.jpg")
# "bar/thumbnails/foo.jpg"
# >>> get_thumb(default_settings, "bar/foo.png")
# "bar/thumbnails/foo.png"
#
# for videos, it returns a jpg file:
# >>> get_thumb(default_settings, "bar/foo.webm")
# "bar/thumbnails/foo.jpg"
# """
#
# path, filen = os.path.split(filename)
# name, ext = os.path.splitext(filen)
#
# if ext.lower() in settings['video_extensions']:
# ext = '.jpg'
# return join(
# path,
# settings['thumb_dir'],
# settings['thumb_prefix'] + name + settings['thumb_suffix'] + ext,
# )
#
# def read_settings(filename=None):
# """Read settings from a config file in the source_dir root."""
#
# logger = logging.getLogger(__name__)
# logger.info("Reading settings ...")
# settings = _DEFAULT_CONFIG.copy()
#
# if filename:
# logger.debug("Settings file: %s", filename)
# settings_path = os.path.dirname(filename)
# tempdict = {}
#
# with open(filename) as f:
# code = compile(f.read(), filename, 'exec')
# exec(code, tempdict)
#
# settings.update(
# (k, v) for k, v in tempdict.items() if k not in ['__builtins__']
# )
#
# # Make the paths relative to the settings file
# paths = ['source', 'destination', 'watermark']
#
# if os.path.isdir(join(settings_path, settings['theme'])) and os.path.isdir(
# join(settings_path, settings['theme'], 'templates')
# ):
# paths.append('theme')
#
# for p in paths:
# path = settings[p]
# if path and not isabs(path):
# settings[p] = abspath(normpath(join(settings_path, path)))
# logger.debug("Rewrite %s : %s -> %s", p, path, settings[p])
#
# for key in ('img_size', 'thumb_size', 'video_size'):
# if settings[key]:
# w, h = settings[key]
# if h > w:
# settings[key] = (h, w)
# logger.warning(
# "The %s setting should be specified with the largest value first.",
# key,
# )
#
# if not settings['img_processor']:
# logger.info('No Processor, images will not be resized')
#
# logger.debug('Settings:\n%s', pformat(settings, width=120))
# return settings
. Output only the next line. | settings = read_settings(str(conf)) |
Using the snippet: <|code_start|> filename, ext = os.path.splitext(f)
options = gallery.settings["upload_s3_options"]
proposed_cache_control = None
if "media_max_age" in options and ext in [".jpg", ".png", ".webm", ".mp4"]:
proposed_cache_control = "max-age=%s" % options["media_max_age"]
elif "max_age" in options:
proposed_cache_control = "max-age=%s" % options["max_age"]
return proposed_cache_control
def upload_file(gallery, bucket, f):
logger.debug("Uploading file %s", f)
key = Key(bucket)
key.key = f
cache_metadata = generate_cache_metadata(gallery, f)
if cache_metadata:
key.set_metadata("Cache-Control", cache_metadata)
key.set_contents_from_filename(
os.path.join(gallery.settings["destination"], f),
policy=gallery.settings["upload_s3_options"]["policy"],
)
def register(settings):
if settings.get("upload_s3_options"):
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
import boto
from click import progressbar
from sigal import signals
from boto.s3.key import Key
and context (class names, function names, or code) available:
# Path: sigal/signals.py
. Output only the next line. | signals.gallery_build.connect(upload_s3) |
Predict the next line after this snippet: <|code_start|>
Based on pilkit's Adjust_ processor.
.. _Adjust: \
https://github.com/matthewwithanm/pilkit/blob/master/pilkit/processors/base.py#L19
Settings::
adjust_options = {
'color': 1.0,
'brightness': 1.0,
'contrast': 1.0,
'sharpness': 1.0
}
"""
logger = logging.getLogger(__name__)
def adjust(img, settings=None):
logger.debug('Adjust image %r', img)
return Adjust(**settings['adjust_options']).process(img)
def register(settings):
if settings.get('adjust_options'):
<|code_end|>
using the current file's imports:
import logging
from pilkit.processors import Adjust
from sigal import signals
and any relevant context from other files:
# Path: sigal/signals.py
. Output only the next line. | signals.img_resized.connect(adjust) |
Predict the next line for this snippet: <|code_start|>
def copy_assets(settings):
theme_path = os.path.join(settings["destination"], 'static')
copy(
os.path.join(ASSETS_PATH, "decrypt.js"),
theme_path,
symlink=False,
rellink=False,
)
copy(
os.path.join(ASSETS_PATH, "keycheck.txt"),
theme_path,
symlink=False,
rellink=False,
)
copy(
os.path.join(ASSETS_PATH, "sw.js"),
settings["destination"],
symlink=False,
rellink=False,
)
def inject_scripts(context):
cache = load_cache(context['settings'])
context["encrypt_options"] = get_options(context['settings'], cache)
def register(settings):
<|code_end|>
with the help of current file imports:
import logging
import os
import pickle
import random
import string
from io import BytesIO
from itertools import chain
from click import progressbar
from sigal import signals
from sigal.settings import get_thumb
from sigal.utils import copy
from .endec import encrypt, kdf_gen_key
and context from other files:
# Path: sigal/signals.py
#
# Path: sigal/settings.py
# def get_thumb(settings, filename):
# """Return the path to the thumb.
#
# examples:
# >>> default_settings = create_settings()
# >>> get_thumb(default_settings, "bar/foo.jpg")
# "bar/thumbnails/foo.jpg"
# >>> get_thumb(default_settings, "bar/foo.png")
# "bar/thumbnails/foo.png"
#
# for videos, it returns a jpg file:
# >>> get_thumb(default_settings, "bar/foo.webm")
# "bar/thumbnails/foo.jpg"
# """
#
# path, filen = os.path.split(filename)
# name, ext = os.path.splitext(filen)
#
# if ext.lower() in settings['video_extensions']:
# ext = '.jpg'
# return join(
# path,
# settings['thumb_dir'],
# settings['thumb_prefix'] + name + settings['thumb_suffix'] + ext,
# )
#
# Path: sigal/utils.py
# def copy(src, dst, symlink=False, rellink=False):
# """Copy or symlink the file."""
# func = os.symlink if symlink else shutil.copy2
# if symlink and os.path.lexists(dst):
# os.remove(dst)
# if rellink: # relative symlink from dst
# func(os.path.relpath(src, os.path.dirname(dst)), dst)
# else:
# try:
# func(src, dst)
# except PermissionError:
# # this can happen if the file is not writable, so we try to remove
# # it first
# os.remove(dst)
# func(src, dst)
, which may contain function names, class names, or code. Output only the next line. | signals.gallery_build.connect(encrypt_gallery) |
Given the code snippet: <|code_start|> # in case any of the credentials are newly generated, write them back
# to cache
cache["credentials"] = {
"gcm_tag": options["gcm_tag"],
"kdf_salt": options["kdf_salt"],
"kdf_iters": options["kdf_iters"],
"galleryId": options["galleryId"],
}
return options
def cache_key(media):
return os.path.join(media.path, media.dst_filename)
def save_property(cache, media):
key = cache_key(media)
if key not in cache:
cache[key] = {}
cache[key]["size"] = media.size
cache[key]["thumb_size"] = media.thumb_size
cache[key]["encrypted"] = set()
def get_encrypt_list(settings, media):
to_encrypt = []
# resized image or in case of "use_orig", the original
to_encrypt.append(media.dst_filename)
if settings["make_thumbs"]:
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import pickle
import random
import string
from io import BytesIO
from itertools import chain
from click import progressbar
from sigal import signals
from sigal.settings import get_thumb
from sigal.utils import copy
from .endec import encrypt, kdf_gen_key
and context (functions, classes, or occasionally code) from other files:
# Path: sigal/signals.py
#
# Path: sigal/settings.py
# def get_thumb(settings, filename):
# """Return the path to the thumb.
#
# examples:
# >>> default_settings = create_settings()
# >>> get_thumb(default_settings, "bar/foo.jpg")
# "bar/thumbnails/foo.jpg"
# >>> get_thumb(default_settings, "bar/foo.png")
# "bar/thumbnails/foo.png"
#
# for videos, it returns a jpg file:
# >>> get_thumb(default_settings, "bar/foo.webm")
# "bar/thumbnails/foo.jpg"
# """
#
# path, filen = os.path.split(filename)
# name, ext = os.path.splitext(filen)
#
# if ext.lower() in settings['video_extensions']:
# ext = '.jpg'
# return join(
# path,
# settings['thumb_dir'],
# settings['thumb_prefix'] + name + settings['thumb_suffix'] + ext,
# )
#
# Path: sigal/utils.py
# def copy(src, dst, symlink=False, rellink=False):
# """Copy or symlink the file."""
# func = os.symlink if symlink else shutil.copy2
# if symlink and os.path.lexists(dst):
# os.remove(dst)
# if rellink: # relative symlink from dst
# func(os.path.relpath(src, os.path.dirname(dst)), dst)
# else:
# try:
# func(src, dst)
# except PermissionError:
# # this can happen if the file is not writable, so we try to remove
# # it first
# os.remove(dst)
# func(src, dst)
. Output only the next line. | to_encrypt.append(get_thumb(settings, media.dst_filename)) # thumbnail |
Given the code snippet: <|code_start|> # save the progress and abort the build if any image
# fails to be encrypted
save_cache(settings, cache)
raise Abort
key_check_path = os.path.join(settings["destination"], 'static', 'keycheck.txt')
encrypt_file("keycheck.txt", key_check_path, key, gcm_tag)
def encrypt_file(filename, full_path, key, gcm_tag):
with BytesIO() as outBuffer:
try:
with open(full_path, "rb") as infile:
encrypt(key, infile, outBuffer, gcm_tag)
except Exception as e:
logger.error("Encryption failed for %s: %s", filename, e)
return False
else:
logger.info("Encrypting %s...", filename)
try:
with open(full_path, "wb") as outfile:
outfile.write(outBuffer.getbuffer())
except Exception as e:
logger.error("Could not write to file %s: %s", filename, e)
return False
return True
def copy_assets(settings):
theme_path = os.path.join(settings["destination"], 'static')
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import pickle
import random
import string
from io import BytesIO
from itertools import chain
from click import progressbar
from sigal import signals
from sigal.settings import get_thumb
from sigal.utils import copy
from .endec import encrypt, kdf_gen_key
and context (functions, classes, or occasionally code) from other files:
# Path: sigal/signals.py
#
# Path: sigal/settings.py
# def get_thumb(settings, filename):
# """Return the path to the thumb.
#
# examples:
# >>> default_settings = create_settings()
# >>> get_thumb(default_settings, "bar/foo.jpg")
# "bar/thumbnails/foo.jpg"
# >>> get_thumb(default_settings, "bar/foo.png")
# "bar/thumbnails/foo.png"
#
# for videos, it returns a jpg file:
# >>> get_thumb(default_settings, "bar/foo.webm")
# "bar/thumbnails/foo.jpg"
# """
#
# path, filen = os.path.split(filename)
# name, ext = os.path.splitext(filen)
#
# if ext.lower() in settings['video_extensions']:
# ext = '.jpg'
# return join(
# path,
# settings['thumb_dir'],
# settings['thumb_prefix'] + name + settings['thumb_suffix'] + ext,
# )
#
# Path: sigal/utils.py
# def copy(src, dst, symlink=False, rellink=False):
# """Copy or symlink the file."""
# func = os.symlink if symlink else shutil.copy2
# if symlink and os.path.lexists(dst):
# os.remove(dst)
# if rellink: # relative symlink from dst
# func(os.path.relpath(src, os.path.dirname(dst)), dst)
# else:
# try:
# func(src, dst)
# except PermissionError:
# # this can happen if the file is not writable, so we try to remove
# # it first
# os.remove(dst)
# func(src, dst)
. Output only the next line. | copy( |
Given the following code snippet before the placeholder: <|code_start|> nb_items = min(nb_items, nb_medias) if nb_items > 0 else nb_medias
base_url = feed_url.rsplit('/', maxsplit=1)[0]
for item in medias[:nb_items]:
if theme == 'galleria':
link = f'{base_url}/{item.path}/#{item.url}'
else:
link = f'{base_url}/{item.path}/'
feed.add_item(
title=Markup.escape(item.title or item.url),
link=link,
# unique_id='tag:%s,%s:%s' % (urlparse(link).netloc,
# item.date.date(),
# urlparse(link).path.lstrip('/')),
description='<img src="{}/{}/{}" />'.format(
base_url, item.path, item.thumbnail
),
# categories=item.tags if hasattr(item, 'tags') else None,
author_name=getattr(item, 'author', ''),
pubdate=item.date or datetime.now(),
)
output_file = os.path.join(root_album.dst_path, feed_url.split('/')[-1])
logger.info('Generate %s feeds: %s', feed_type.upper(), output_file)
with open(output_file, 'w', encoding='utf8') as f:
feed.write(f, 'utf-8')
def register(settings):
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
from datetime import datetime
from markupsafe import Markup
from sigal import signals
from feedgenerator import Atom1Feed, Rss201rev2Feed
and context including class names, function names, and sometimes code from other files:
# Path: sigal/signals.py
. Output only the next line. | signals.gallery_build.connect(generate_feeds) |
Here is a snippet: <|code_start|> compress_settings = gallery.settings.get(
'compress_assets_options', DEFAULT_SETTINGS
)
compressor = get_compressor(compress_settings)
if compressor is None:
return
# Collecting theme assets
theme_assets = []
for current_directory, _, filenames in os.walk(
os.path.join(gallery.settings['destination'], 'static')
):
for filename in filenames:
theme_assets.append(os.path.join(current_directory, filename))
with progressbar(
length=len(gallery.albums) + len(theme_assets), label='Compressing static files'
) as bar:
for album in gallery.albums.values():
compressor.compress(os.path.join(album.dst_path, album.output_file))
bar.update(1)
for theme_asset in theme_assets:
compressor.compress(theme_asset)
bar.update(1)
def register(settings):
if settings['write_html']:
<|code_end|>
. Write the next line using the current file imports:
import gzip
import logging
import os
import shutil
import zopfli.gzip
import brotli
import zopfli.gzip # noqa
import brotli # noqa
from click import progressbar
from sigal import signals
and context from other files:
# Path: sigal/signals.py
, which may include functions, classes, or code. Output only the next line. | signals.gallery_build.connect(compress_gallery) |
Based on the snippet: <|code_start|>
CURRENT_DIR = os.path.dirname(__file__)
SAMPLE_DIR = os.path.join(CURRENT_DIR, 'sample')
def test_copy(tmpdir):
filename = 'KeckObservatory20071020.jpg'
src = os.path.join(SAMPLE_DIR, 'pictures', 'dir2', filename)
dst = str(tmpdir.join(filename))
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from pathlib import Path
from sigal import utils
and context (classes, functions, sometimes code) from other files:
# Path: sigal/utils.py
# VIDEO_MIMES = {'.mp4': 'video/mp4', '.webm': 'video/webm', '.ogv': 'video/ogg'}
# MD = None
# MD = Markdown(
# extensions=[
# 'markdown.extensions.extra',
# 'markdown.extensions.meta',
# 'markdown.extensions.tables',
# ],
# output_format='html5',
# )
# class Devnull:
# def write(self, *_):
# def flush(self, *_):
# def copy(src, dst, symlink=False, rellink=False):
# def check_or_create_dir(path):
# def get_mod_date(path):
# def url_from_path(path):
# def read_markdown(filename):
# def is_valid_html5_video(ext):
# def get_mime(ext):
. Output only the next line. | utils.copy(src, dst) |
Predict the next line for this snippet: <|code_start|>
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
BUILD_DIR = os.path.join(CURRENT_DIR, 'sample', '_build')
@pytest.fixture(scope='session', autouse=True)
def remove_build():
"""Ensure that build directory does not exists before each test."""
if os.path.exists(BUILD_DIR):
shutil.rmtree(BUILD_DIR)
@pytest.fixture
def settings():
"""Read the sample config file."""
return read_settings(os.path.join(CURRENT_DIR, 'sample', 'sigal.conf.py'))
@pytest.fixture()
def disconnect_signals():
# Reset plugins
yield None
<|code_end|>
with the help of current file imports:
import os
import shutil
import blinker
import PIL
import pytest
from sigal import signals
from sigal.settings import read_settings
and context from other files:
# Path: sigal/signals.py
#
# Path: sigal/settings.py
# def read_settings(filename=None):
# """Read settings from a config file in the source_dir root."""
#
# logger = logging.getLogger(__name__)
# logger.info("Reading settings ...")
# settings = _DEFAULT_CONFIG.copy()
#
# if filename:
# logger.debug("Settings file: %s", filename)
# settings_path = os.path.dirname(filename)
# tempdict = {}
#
# with open(filename) as f:
# code = compile(f.read(), filename, 'exec')
# exec(code, tempdict)
#
# settings.update(
# (k, v) for k, v in tempdict.items() if k not in ['__builtins__']
# )
#
# # Make the paths relative to the settings file
# paths = ['source', 'destination', 'watermark']
#
# if os.path.isdir(join(settings_path, settings['theme'])) and os.path.isdir(
# join(settings_path, settings['theme'], 'templates')
# ):
# paths.append('theme')
#
# for p in paths:
# path = settings[p]
# if path and not isabs(path):
# settings[p] = abspath(normpath(join(settings_path, path)))
# logger.debug("Rewrite %s : %s -> %s", p, path, settings[p])
#
# for key in ('img_size', 'thumb_size', 'video_size'):
# if settings[key]:
# w, h = settings[key]
# if h > w:
# settings[key] = (h, w)
# logger.warning(
# "The %s setting should be specified with the largest value first.",
# key,
# )
#
# if not settings['img_processor']:
# logger.info('No Processor, images will not be resized')
#
# logger.debug('Settings:\n%s', pformat(settings, width=120))
# return settings
, which may contain function names, class names, or code. Output only the next line. | for name in dir(signals): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.