Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> class PlaybookRunHistorySerializer(serializers.HyperlinkedModelSerializer): playbook = serializers.SlugRelatedField( read_only=True, slug_field='name' ) launched_by = serializers.SlugRelatedField( read_only=True, slug_field='username' ) class Meta: <|code_end|> , predict the next line using imports from the current file: from .models import Playbook, PlaybookRunHistory from django.contrib.auth.models import Group from rest_framework import serializers from ..Cyclosible.serializers import GroupSerializerNoValidator from django.core.exceptions import ObjectDoesNotExist and context including class names, function names, and sometimes code from other files: # Path: cyclosible/playbook/models.py # class Playbook(models.Model): # class Meta: # app_label = 'playbook' # permissions = ( # ("view_playbook", "Can view the playbook"), # ("can_override_skip_tags", 'Can override skip_tags'), # ("can_override_only_tags", 'Can override only_tags'), # ("can_override_extra_vars", 'Can override extra_vars'), # ("can_override_subset", 'Can override subset'), # ("can_run_playbook", 'Can run the playbook') # ) # # name = models.CharField(max_length=100, unique=True, db_index=True) # only_tags = models.CharField(max_length=1024, default='', blank=True) # skip_tags = models.CharField(max_length=1024, default='', blank=True) # extra_vars = models.CharField(max_length=1024, default='', blank=True) # subset = models.CharField(max_length=1024, default='', blank=True) # group = models.ForeignKey(Group, null=True) # # def __unicode__(self): # return self.name # # class PlaybookRunHistory(models.Model): # class Meta: # app_label = 'playbook' # # STATUS = ( # ('SUCCESS', 'Success'), # ('RUNNING', 'Running'), # ('FAILURE', 'Failure'), # ) # # playbook = models.ForeignKey(Playbook, db_index=True, related_name='history') # date_launched = models.DateTimeField(blank=True) # date_finished = models.DateTimeField(blank=True, null=True) # status = models.CharField(max_length=1024, default='RUNNING') # task_id = models.CharField(max_length=1024, default='', blank=True) # log_url = models.CharField(max_length=1024, default='', blank=True) # launched_by = models.ForeignKey(User) # # Path: cyclosible/Cyclosible/serializers.py # class GroupSerializerNoValidator(serializers.HyperlinkedModelSerializer): # name = serializers.SlugField(validators=[]) # # class Meta: # model = Group # lookup_field = 'name' # fields = ('url', 'name') # extra_kwargs = { # 'url': {'lookup_field': 'name'} # } . Output only the next line.
model = PlaybookRunHistory
Using the snippet: <|code_start|>class PlaybookRunHistorySerializer(serializers.HyperlinkedModelSerializer): playbook = serializers.SlugRelatedField( read_only=True, slug_field='name' ) launched_by = serializers.SlugRelatedField( read_only=True, slug_field='username' ) class Meta: model = PlaybookRunHistory fields = ('url', 'playbook', 'date_launched', 'date_finished', 'status', 'task_id', 'launched_by', 'log_url') class FilteredHistorySerializer(serializers.ListSerializer): def to_representation(self, data): data = data.order_by('-date_launched')[:10] return super(FilteredHistorySerializer, self).to_representation(data) class PlaybookRunHistoryLastSerializer(PlaybookRunHistorySerializer): class Meta: model = PlaybookRunHistory list_serializer_class = FilteredHistorySerializer class PlaybookSerializer(serializers.HyperlinkedModelSerializer): <|code_end|> , determine the next line of code. You have imports: from .models import Playbook, PlaybookRunHistory from django.contrib.auth.models import Group from rest_framework import serializers from ..Cyclosible.serializers import GroupSerializerNoValidator from django.core.exceptions import ObjectDoesNotExist and context (class names, function names, or code) available: # Path: cyclosible/playbook/models.py # class Playbook(models.Model): # class Meta: # app_label = 'playbook' # permissions = ( # ("view_playbook", "Can view the playbook"), # ("can_override_skip_tags", 'Can override skip_tags'), # ("can_override_only_tags", 'Can override only_tags'), # ("can_override_extra_vars", 'Can override extra_vars'), # ("can_override_subset", 'Can override subset'), # ("can_run_playbook", 'Can run the playbook') # ) # # name = models.CharField(max_length=100, unique=True, db_index=True) # only_tags = models.CharField(max_length=1024, default='', blank=True) # skip_tags = models.CharField(max_length=1024, default='', blank=True) # extra_vars = models.CharField(max_length=1024, default='', blank=True) # subset = models.CharField(max_length=1024, default='', blank=True) # group = models.ForeignKey(Group, null=True) # # def __unicode__(self): # return self.name # # class PlaybookRunHistory(models.Model): # class Meta: # app_label = 'playbook' # # STATUS = ( # ('SUCCESS', 'Success'), # ('RUNNING', 'Running'), # ('FAILURE', 'Failure'), # ) # # playbook = models.ForeignKey(Playbook, db_index=True, related_name='history') # date_launched = models.DateTimeField(blank=True) # date_finished = models.DateTimeField(blank=True, null=True) # status = models.CharField(max_length=1024, default='RUNNING') # task_id = models.CharField(max_length=1024, default='', blank=True) # log_url = models.CharField(max_length=1024, default='', blank=True) # launched_by = models.ForeignKey(User) # # Path: cyclosible/Cyclosible/serializers.py # class GroupSerializerNoValidator(serializers.HyperlinkedModelSerializer): # name = serializers.SlugField(validators=[]) # # class Meta: # model = Group # lookup_field = 'name' # fields = ('url', 'name') # extra_kwargs = { # 'url': {'lookup_field': 'name'} # } . Output only the next line.
group = GroupSerializerNoValidator(many=False, required=True)
Given snippet: <|code_start|> class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import (UserSerializer, GroupSerializer) from django.http import HttpResponseForbidden and context: # Path: cyclosible/Cyclosible/serializers.py # class UserSerializer(serializers.HyperlinkedModelSerializer): # groups = GroupSerializerNoValidator(many=True, required=False) # # class Meta: # model = User # lookup_field = 'username' # fields = ('url', 'first_name', 'last_name', 'username', 'email', 'groups') # extra_kwargs = { # 'url': {'lookup_field': 'username'} # } # # def create(self, validated_data): # groups_data = validated_data.pop('groups') # user = User.objects.create(**validated_data) # for group_data in groups_data: # try: # group = Group.objects.get(name=group_data.get('name')) # group.user_set.add(user) # except Group.DoesNotExist: # group = Group.objects.create(**group_data) # group.user_set.add(user) # return user # # def update(self, instance, validated_data): # instance.first_name = validated_data.get('first_name', instance.first_name) # instance.last_name = validated_data.get('last_name', instance.last_name) # instance.username = validated_data.get('username', instance.username) # instance.email = validated_data.get('email', instance.email) # instance.groups.clear() # groups_data = validated_data.get('groups') # for group_data in groups_data: # try: # group = Group.objects.get(name=group_data.get('name')) # group.user_set.add(instance) # except Group.DoesNotExist: # group = Group.objects.create(**group_data) # group.user_set.add(instance) # return instance # # class GroupSerializer(serializers.HyperlinkedModelSerializer): # # class Meta: # model = Group # lookup_field = 'name' # fields = ('url', 'name') # extra_kwargs = { # 'url': {'lookup_field': 'name'} # } which might include code, classes, or functions. Output only the next line.
serializer_class = UserSerializer
Predict the next line after this snippet: <|code_start|> class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'username' class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() <|code_end|> using the current file's imports: from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import (UserSerializer, GroupSerializer) from django.http import HttpResponseForbidden and any relevant context from other files: # Path: cyclosible/Cyclosible/serializers.py # class UserSerializer(serializers.HyperlinkedModelSerializer): # groups = GroupSerializerNoValidator(many=True, required=False) # # class Meta: # model = User # lookup_field = 'username' # fields = ('url', 'first_name', 'last_name', 'username', 'email', 'groups') # extra_kwargs = { # 'url': {'lookup_field': 'username'} # } # # def create(self, validated_data): # groups_data = validated_data.pop('groups') # user = User.objects.create(**validated_data) # for group_data in groups_data: # try: # group = Group.objects.get(name=group_data.get('name')) # group.user_set.add(user) # except Group.DoesNotExist: # group = Group.objects.create(**group_data) # group.user_set.add(user) # return user # # def update(self, instance, validated_data): # instance.first_name = validated_data.get('first_name', instance.first_name) # instance.last_name = validated_data.get('last_name', instance.last_name) # instance.username = validated_data.get('username', instance.username) # instance.email = validated_data.get('email', instance.email) # instance.groups.clear() # groups_data = validated_data.get('groups') # for group_data in groups_data: # try: # group = Group.objects.get(name=group_data.get('name')) # group.user_set.add(instance) # except Group.DoesNotExist: # group = Group.objects.create(**group_data) # group.user_set.add(instance) # return instance # # class GroupSerializer(serializers.HyperlinkedModelSerializer): # # class Meta: # model = Group # lookup_field = 'name' # fields = ('url', 'name') # extra_kwargs = { # 'url': {'lookup_field': 'name'} # } . Output only the next line.
serializer_class = GroupSerializer
Given the following code snippet before the placeholder: <|code_start|> @admin.register(Playbook) class PlaybookAdmin(GuardedModelAdmin): queryset = Playbook.objects.all() list_display = ('name', 'group', 'only_tags', 'skip_tags') <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from .models import Playbook, PlaybookRunHistory from guardian.admin import GuardedModelAdmin and context including class names, function names, and sometimes code from other files: # Path: cyclosible/playbook/models.py # class Playbook(models.Model): # class Meta: # app_label = 'playbook' # permissions = ( # ("view_playbook", "Can view the playbook"), # ("can_override_skip_tags", 'Can override skip_tags'), # ("can_override_only_tags", 'Can override only_tags'), # ("can_override_extra_vars", 'Can override extra_vars'), # ("can_override_subset", 'Can override subset'), # ("can_run_playbook", 'Can run the playbook') # ) # # name = models.CharField(max_length=100, unique=True, db_index=True) # only_tags = models.CharField(max_length=1024, default='', blank=True) # skip_tags = models.CharField(max_length=1024, default='', blank=True) # extra_vars = models.CharField(max_length=1024, default='', blank=True) # subset = models.CharField(max_length=1024, default='', blank=True) # group = models.ForeignKey(Group, null=True) # # def __unicode__(self): # return self.name # # class PlaybookRunHistory(models.Model): # class Meta: # app_label = 'playbook' # # STATUS = ( # ('SUCCESS', 'Success'), # ('RUNNING', 'Running'), # ('FAILURE', 'Failure'), # ) # # playbook = models.ForeignKey(Playbook, db_index=True, related_name='history') # date_launched = models.DateTimeField(blank=True) # date_finished = models.DateTimeField(blank=True, null=True) # status = models.CharField(max_length=1024, default='RUNNING') # task_id = models.CharField(max_length=1024, default='', blank=True) # log_url = models.CharField(max_length=1024, default='', blank=True) # launched_by = models.ForeignKey(User) . Output only the next line.
@admin.register(PlaybookRunHistory)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- ''' Copyright 2012-2018 HWM This file is part of PorDB3. PorDB3 is free software: you can redistribute it and or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PorDB3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http: www.gnu.org licenses >. ''' <|code_end|> , determine the next line of code. You have imports: from PyQt5 import QtGui, QtCore, QtWidgets from pordb_update_version import Ui_Dialog as pordb_update_version import os import urllib.request, urllib.error, urllib.parse import tempfile import zipfile and context (class names, function names, or code) available: # Path: pordb_update_version.py # class Ui_Dialog(object): # def setupUi(self, Dialog): # Dialog.setObjectName("Dialog") # Dialog.resize(638, 407) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap("pypordb/8027068_splash.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Dialog.setWindowIcon(icon) # self.gridLayout_2 = QtWidgets.QGridLayout(Dialog) # self.gridLayout_2.setObjectName("gridLayout_2") # self.verticalLayout_2 = QtWidgets.QVBoxLayout() # self.verticalLayout_2.setObjectName("verticalLayout_2") # self.scrollArea = QtWidgets.QScrollArea(Dialog) # self.scrollArea.setWidgetResizable(True) # self.scrollArea.setObjectName("scrollArea") # self.scrollAreaWidgetContents = QtWidgets.QWidget() # self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 622, 337)) # self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") # self.gridLayout = QtWidgets.QGridLayout(self.scrollAreaWidgetContents) # self.gridLayout.setContentsMargins(0, 0, 0, 0) # self.gridLayout.setObjectName("gridLayout") # self.label_2 = QtWidgets.QLabel(self.scrollAreaWidgetContents) # self.label_2.setObjectName("label_2") # self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1) # self.plainTextEditWhatsnew = QtWidgets.QPlainTextEdit(self.scrollAreaWidgetContents) # self.plainTextEditWhatsnew.setReadOnly(True) # self.plainTextEditWhatsnew.setObjectName("plainTextEditWhatsnew") # self.gridLayout.addWidget(self.plainTextEditWhatsnew, 2, 0, 1, 1) # self.label_3 = QtWidgets.QLabel(self.scrollAreaWidgetContents) # self.label_3.setObjectName("label_3") # self.gridLayout.addWidget(self.label_3, 0, 0, 1, 1) # self.scrollArea.setWidget(self.scrollAreaWidgetContents) # self.verticalLayout_2.addWidget(self.scrollArea) # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.label = QtWidgets.QLabel(Dialog) # self.label.setObjectName("label") # self.verticalLayout.addWidget(self.label) # self.horizontalLayout = QtWidgets.QHBoxLayout() # self.horizontalLayout.setObjectName("horizontalLayout") # self.pushButtonYes = QtWidgets.QPushButton(Dialog) # self.pushButtonYes.setAutoDefault(False) # self.pushButtonYes.setDefault(True) # self.pushButtonYes.setObjectName("pushButtonYes") # self.horizontalLayout.addWidget(self.pushButtonYes) # self.pushButtonNo = QtWidgets.QPushButton(Dialog) # self.pushButtonNo.setObjectName("pushButtonNo") # self.horizontalLayout.addWidget(self.pushButtonNo) # self.verticalLayout.addLayout(self.horizontalLayout) # self.verticalLayout_2.addLayout(self.verticalLayout) # self.gridLayout_2.addLayout(self.verticalLayout_2, 0, 0, 1, 1) # # self.retranslateUi(Dialog) # QtCore.QMetaObject.connectSlotsByName(Dialog) # # def retranslateUi(self, Dialog): # _translate = QtCore.QCoreApplication.translate # Dialog.setWindowTitle(_translate("Dialog", "PorDB3 Update")) # self.label_2.setText(_translate("Dialog", "<html><head/><body><p><span style=\" font-size:12pt;\">What\'s new:</span></p></body></html>")) # self.label_3.setText(_translate("Dialog", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600;\">New version of PorDB3 available</span></p></body></html>")) # self.label.setText(_translate("Dialog", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600;\">Do you want to perform the update?</span></p></body></html>")) # self.pushButtonYes.setText(_translate("Dialog", "Yes")) # self.pushButtonNo.setText(_translate("Dialog", "No")) . Output only the next line.
from pordb_update_version import Ui_Dialog as pordb_update_version
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- ''' Copyright 2012-2018 HWM This file is part of PorDB3. PorDB3 is free software: you can redistribute it and or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PorDB3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http: www.gnu.org licenses >. ''' <|code_end|> . Use current file imports: from PyQt5 import QtGui, QtCore, QtWidgets from pordb_bildgross import Ui_Dialog as pordb_bildgross and context (classes, functions, or code) from other files: # Path: pordb_bildgross.py # class Ui_Dialog(object): # def setupUi(self, Dialog): # Dialog.setObjectName("Dialog") # Dialog.resize(1271, 961) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap("pypordb/8027068_splash.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Dialog.setWindowIcon(icon) # self.hboxlayout = QtWidgets.QHBoxLayout(Dialog) # self.hboxlayout.setObjectName("hboxlayout") # self.horizontalLayout = QtWidgets.QHBoxLayout() # self.horizontalLayout.setObjectName("horizontalLayout") # self.labelBildgross = QtWidgets.QLabel(Dialog) # self.labelBildgross.setObjectName("labelBildgross") # self.horizontalLayout.addWidget(self.labelBildgross) # self.hboxlayout.addLayout(self.horizontalLayout) # # self.retranslateUi(Dialog) # QtCore.QMetaObject.connectSlotsByName(Dialog) # # def retranslateUi(self, Dialog): # _translate = QtCore.QCoreApplication.translate # Dialog.setWindowTitle(_translate("Dialog", "PorDB3")) # self.labelBildgross.setText(_translate("Dialog", "TextLabel")) . Output only the next line.
from pordb_bildgross import Ui_Dialog as pordb_bildgross
Given snippet: <|code_start|># -*- coding: utf-8 -*- ''' Copyright 2012-2018 HWM This file is part of PorDB3. PorDB3 is free software: you can redistribute it and or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PorDB3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http: www.gnu.org licenses >. ''' <|code_end|> , continue by predicting the next line. Consider current file imports: from PyQt5 import QtGui, QtCore, QtWidgets from pordb_bildschneiden import Ui_Dialog as pordb_bildschneiden and context: # Path: pordb_bildschneiden.py # class Ui_Dialog(object): # def setupUi(self, Dialog): # Dialog.setObjectName("Dialog") # Dialog.resize(1244, 924) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap("pypordb/8027068_splash.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Dialog.setWindowIcon(icon) # self.gridLayout = QtWidgets.QGridLayout(Dialog) # self.gridLayout.setObjectName("gridLayout") # self.vboxlayout = QtWidgets.QVBoxLayout() # self.vboxlayout.setObjectName("vboxlayout") # self.labelBild = QtWidgets.QLabel(Dialog) # self.labelBild.setMinimumSize(QtCore.QSize(260, 260)) # self.labelBild.setWhatsThis("") # self.labelBild.setObjectName("labelBild") # self.vboxlayout.addWidget(self.labelBild) # self.hboxlayout = QtWidgets.QHBoxLayout() # self.hboxlayout.setObjectName("hboxlayout") # self.pushButtonNeuSpeichern = QtWidgets.QPushButton(Dialog) # self.pushButtonNeuSpeichern.setText("") # icon1 = QtGui.QIcon() # icon1.addPixmap(QtGui.QPixmap("pypordb/media-floppy.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # self.pushButtonNeuSpeichern.setIcon(icon1) # self.pushButtonNeuSpeichern.setObjectName("pushButtonNeuSpeichern") # self.hboxlayout.addWidget(self.pushButtonNeuSpeichern) # self.pushButtonNeuSpeichernAls = QtWidgets.QPushButton(Dialog) # self.pushButtonNeuSpeichernAls.setText("") # icon2 = QtGui.QIcon() # icon2.addPixmap(QtGui.QPixmap("pypordb/document-save-as.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # self.pushButtonNeuSpeichernAls.setIcon(icon2) # self.pushButtonNeuSpeichernAls.setObjectName("pushButtonNeuSpeichernAls") # self.hboxlayout.addWidget(self.pushButtonNeuSpeichernAls) # self.pushButtonNeuCancel = QtWidgets.QPushButton(Dialog) # self.pushButtonNeuCancel.setText("") # icon3 = QtGui.QIcon() # icon3.addPixmap(QtGui.QPixmap("pypordb/dialog-cancel.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # self.pushButtonNeuCancel.setIcon(icon3) # self.pushButtonNeuCancel.setObjectName("pushButtonNeuCancel") # self.hboxlayout.addWidget(self.pushButtonNeuCancel) # self.vboxlayout.addLayout(self.hboxlayout) # self.gridLayout.addLayout(self.vboxlayout, 0, 0, 1, 1) # # self.retranslateUi(Dialog) # QtCore.QMetaObject.connectSlotsByName(Dialog) # # def retranslateUi(self, Dialog): # _translate = QtCore.QCoreApplication.translate # Dialog.setWindowTitle(_translate("Dialog", "Crop image")) # self.labelBild.setText(_translate("Dialog", "Image")) # self.pushButtonNeuSpeichern.setToolTip(_translate("Dialog", "<html><head/><body><p>Save</p></body></html>")) # self.pushButtonNeuSpeichernAls.setToolTip(_translate("Dialog", "<html><head/><body><p>Save as ...</p></body></html>")) # self.pushButtonNeuCancel.setToolTip(_translate("Dialog", "<html><head/><body><p>Cancel</p></body></html>")) which might include code, classes, or functions. Output only the next line.
from pordb_bildschneiden import Ui_Dialog as pordb_bildschneiden
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- ''' Copyright 2012-2018 HWM This file is part of PorDB3. PorDB3 is free software: you can redistribute it and or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PorDB3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http: www.gnu.org licenses >. ''' <|code_end|> , predict the next line using imports from the current file: from PyQt5 import QtGui, QtCore, QtWidgets from pordb_bilddatei_umbenennen import Ui_Dialog as pordb_bilddatei_umbenennen import os and context including class names, function names, and sometimes code from other files: # Path: pordb_bilddatei_umbenennen.py # class Ui_Dialog(object): # def setupUi(self, Dialog): # Dialog.setObjectName("Dialog") # Dialog.resize(1035, 307) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap("pypordb/8027068_splash.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Dialog.setWindowIcon(icon) # self.verticalLayout_3 = QtWidgets.QVBoxLayout(Dialog) # self.verticalLayout_3.setObjectName("verticalLayout_3") # self.label = QtWidgets.QLabel(Dialog) # font = QtGui.QFont() # font.setPointSize(16) # font.setBold(True) # font.setWeight(75) # self.label.setFont(font) # self.label.setObjectName("label") # self.verticalLayout_3.addWidget(self.label) # self.verticalLayout_2 = QtWidgets.QVBoxLayout() # self.verticalLayout_2.setObjectName("verticalLayout_2") # self.horizontalLayout = QtWidgets.QHBoxLayout() # self.horizontalLayout.setObjectName("horizontalLayout") # self.groupBox = QtWidgets.QGroupBox(Dialog) # self.groupBox.setObjectName("groupBox") # self.gridLayout = QtWidgets.QGridLayout(self.groupBox) # self.gridLayout.setObjectName("gridLayout") # self.listWidgetDateinamen = QtWidgets.QListWidget(self.groupBox) # self.listWidgetDateinamen.setObjectName("listWidgetDateinamen") # self.gridLayout.addWidget(self.listWidgetDateinamen, 0, 0, 1, 1) # self.horizontalLayout.addWidget(self.groupBox) # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.groupBox_2 = QtWidgets.QGroupBox(Dialog) # self.groupBox_2.setObjectName("groupBox_2") # self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox_2) # self.gridLayout_2.setObjectName("gridLayout_2") # self.lineEditDateiname = QtWidgets.QLineEdit(self.groupBox_2) # self.lineEditDateiname.setObjectName("lineEditDateiname") # self.gridLayout_2.addWidget(self.lineEditDateiname, 0, 0, 1, 1) # self.verticalLayout.addWidget(self.groupBox_2) # self.labelDateiname = QtWidgets.QLabel(Dialog) # self.labelDateiname.setText("") # self.labelDateiname.setObjectName("labelDateiname") # self.verticalLayout.addWidget(self.labelDateiname) # spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) # self.verticalLayout.addItem(spacerItem) # self.horizontalLayout.addLayout(self.verticalLayout) # self.verticalLayout_2.addLayout(self.horizontalLayout) # self.horizontalLayout_2 = QtWidgets.QHBoxLayout() # self.horizontalLayout_2.setObjectName("horizontalLayout_2") # self.pushButtonUmbenennen = QtWidgets.QPushButton(Dialog) # self.pushButtonUmbenennen.setDefault(True) # self.pushButtonUmbenennen.setFlat(False) # self.pushButtonUmbenennen.setObjectName("pushButtonUmbenennen") # self.horizontalLayout_2.addWidget(self.pushButtonUmbenennen) # self.pushButtonCancel = QtWidgets.QPushButton(Dialog) # self.pushButtonCancel.setObjectName("pushButtonCancel") # self.horizontalLayout_2.addWidget(self.pushButtonCancel) # self.verticalLayout_2.addLayout(self.horizontalLayout_2) # self.verticalLayout_3.addLayout(self.verticalLayout_2) # # self.retranslateUi(Dialog) # QtCore.QMetaObject.connectSlotsByName(Dialog) # # def retranslateUi(self, Dialog): # _translate = QtCore.QCoreApplication.translate # Dialog.setWindowTitle(_translate("Dialog", "Edit filename")) # self.label.setText(_translate("Dialog", "Filename already exists or has more than 256 characters")) # self.groupBox.setTitle(_translate("Dialog", "Similar files in directory")) # self.groupBox_2.setTitle(_translate("Dialog", "New filename")) # self.pushButtonUmbenennen.setText(_translate("Dialog", "Rename file")) # self.pushButtonUmbenennen.setShortcut(_translate("Dialog", "Return")) # self.pushButtonCancel.setText(_translate("Dialog", "Cancel")) . Output only the next line.
from pordb_bilddatei_umbenennen import Ui_Dialog as pordb_bilddatei_umbenennen
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- ''' Copyright 2012-2022 HWM This file is part of PorDB3. PorDB3 is free software: you can redistribute it and or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PorDB3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http: www.gnu.org licenses >. ''' <|code_end|> using the current file's imports: from PyQt5 import QtWidgets from pordb_original import Ui_Dialog as pordb_original and any relevant context from other files: # Path: pordb_original.py # class Ui_Dialog(object): # def setupUi(self, Dialog): # Dialog.setObjectName("Dialog") # Dialog.resize(956, 667) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap("pypordb/8027068_splash.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Dialog.setWindowIcon(icon) # self.gridLayout = QtWidgets.QGridLayout(Dialog) # self.gridLayout.setObjectName("gridLayout") # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.tableWidget = QtWidgets.QTableWidget(Dialog) # self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) # self.tableWidget.setRowCount(20) # self.tableWidget.setObjectName("tableWidget") # self.tableWidget.setColumnCount(1) # item = QtWidgets.QTableWidgetItem() # self.tableWidget.setHorizontalHeaderItem(0, item) # self.tableWidget.horizontalHeader().setVisible(False) # self.tableWidget.horizontalHeader().setDefaultSectionSize(900) # self.tableWidget.horizontalHeader().setMinimumSectionSize(26) # self.verticalLayout.addWidget(self.tableWidget) # self.horizontalLayout = QtWidgets.QHBoxLayout() # self.horizontalLayout.setObjectName("horizontalLayout") # spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) # self.horizontalLayout.addItem(spacerItem) # self.pushButtonSpeichern = QtWidgets.QPushButton(Dialog) # self.pushButtonSpeichern.setObjectName("pushButtonSpeichern") # self.horizontalLayout.addWidget(self.pushButtonSpeichern) # self.pushButtonAbbrechen = QtWidgets.QPushButton(Dialog) # self.pushButtonAbbrechen.setObjectName("pushButtonAbbrechen") # self.horizontalLayout.addWidget(self.pushButtonAbbrechen) # self.verticalLayout.addLayout(self.horizontalLayout) # self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1) # # self.retranslateUi(Dialog) # QtCore.QMetaObject.connectSlotsByName(Dialog) # # def retranslateUi(self, Dialog): # _translate = QtCore.QCoreApplication.translate # Dialog.setWindowTitle(_translate("Dialog", "Enter more movie titles")) # item = self.tableWidget.horizontalHeaderItem(0) # item.setText(_translate("Dialog", "More movie titles")) # self.pushButtonSpeichern.setText(_translate("Dialog", "Save")) # self.pushButtonAbbrechen.setText(_translate("Dialog", "Cancel")) . Output only the next line.
from pordb_original import Ui_Dialog as pordb_original
Using the snippet: <|code_start|># -*- coding: utf-8 -*- ''' Copyright 2012-2018 HWM This file is part of PorDB3. PorDB3 is free software: you can redistribute it and or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PorDB3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http: www.gnu.org licenses >. ''' <|code_end|> , determine the next line of code. You have imports: from PyQt5 import QtGui, QtCore, QtWidgets from pordb_darsteller_umbenennen import Ui_Dialog as pordb_darsteller_umbenennen and context (class names, function names, or code) available: # Path: pordb_darsteller_umbenennen.py # class Ui_Dialog(object): # def setupUi(self, Dialog): # Dialog.setObjectName("Dialog") # Dialog.resize(483, 121) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap("pypordb/8027068_splash.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Dialog.setWindowIcon(icon) # self.gridLayout = QtWidgets.QGridLayout(Dialog) # self.gridLayout.setObjectName("gridLayout") # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.groupBox = QtWidgets.QGroupBox(Dialog) # self.groupBox.setObjectName("groupBox") # self.horizontalLayout = QtWidgets.QHBoxLayout(self.groupBox) # self.horizontalLayout.setObjectName("horizontalLayout") # self.lineEditNeuerName = QtWidgets.QLineEdit(self.groupBox) # self.lineEditNeuerName.setObjectName("lineEditNeuerName") # self.horizontalLayout.addWidget(self.lineEditNeuerName) # self.verticalLayout.addWidget(self.groupBox) # self.hboxlayout = QtWidgets.QHBoxLayout() # self.hboxlayout.setObjectName("hboxlayout") # self.pushButtonUmbenennen = QtWidgets.QPushButton(Dialog) # icon1 = QtGui.QIcon() # icon1.addPixmap(QtGui.QPixmap("pypordb/umbenennen.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # self.pushButtonUmbenennen.setIcon(icon1) # self.pushButtonUmbenennen.setObjectName("pushButtonUmbenennen") # self.hboxlayout.addWidget(self.pushButtonUmbenennen) # self.pushButtonCancel = QtWidgets.QPushButton(Dialog) # icon2 = QtGui.QIcon() # icon2.addPixmap(QtGui.QPixmap("pypordb/dialog-cancel.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # self.pushButtonCancel.setIcon(icon2) # self.pushButtonCancel.setObjectName("pushButtonCancel") # self.hboxlayout.addWidget(self.pushButtonCancel) # self.verticalLayout.addLayout(self.hboxlayout) # self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1) # # self.retranslateUi(Dialog) # QtCore.QMetaObject.connectSlotsByName(Dialog) # # def retranslateUi(self, Dialog): # _translate = QtCore.QCoreApplication.translate # Dialog.setWindowTitle(_translate("Dialog", "Enter new name")) # self.groupBox.setTitle(_translate("Dialog", "New name:")) # self.pushButtonUmbenennen.setText(_translate("Dialog", "Rename")) # self.pushButtonCancel.setText(_translate("Dialog", "Cancel")) . Output only the next line.
from pordb_darsteller_umbenennen import Ui_Dialog as pordb_darsteller_umbenennen
Using the snippet: <|code_start|> async def task1(): await asyncio.sleep(1) return 1 async def task2(): await asyncio.sleep(0) return 2 async def task3(): await asyncio.sleep(0) raise ValueError(3) async def task4(): await asyncio.sleep(1) raise ValueError(4) async def task5(): try: await asyncio.sleep(1) finally: raise ValueError(5) @pytest.mark.asyncio async def test_task_group_cleanup(event_loop): <|code_end|> , determine the next line of code. You have imports: import asyncio import pytest from aiostream.manager import TaskGroup and context (class names, function names, or code) available: # Path: aiostream/manager.py # class TaskGroup: # def __init__(self): # self._pending = set() # # async def __aenter__(self): # return self # # async def __aexit__(self, *args): # while self._pending: # task = self._pending.pop() # await self.cancel_task(task) # # def create_task(self, coro): # task = asyncio.ensure_future(coro) # self._pending.add(task) # return task # # async def wait_any(self, tasks): # done, _ = await asyncio.wait(tasks, return_when="FIRST_COMPLETED") # self._pending -= done # return done # # async def wait_all(self, tasks): # if not tasks: # return set() # done, _ = await asyncio.wait(tasks) # self._pending -= done # return done # # async def cancel_task(self, task): # try: # # The task is already cancelled # if task.cancelled(): # pass # # The task is already finished # elif task.done(): # # Discard the pending exception (if any). # # This makes sense since we don't know in which context the exception # # was meant to be processed. For instance, a `StopAsyncIteration` # # might be raised to notify that the end of a streamer has been reached. # task.exception() # # The task needs to be cancelled and awaited # else: # task.cancel() # try: # await task # except asyncio.CancelledError: # pass # # Silence any exception raised while cancelling the task. # # This might happen if the `CancelledError` is silenced, and the # # corresponding async generator returns, causing the `anext` call # # to raise a `StopAsyncIteration`. # except Exception: # pass # finally: # self._pending.discard(task) . Output only the next line.
async with TaskGroup() as group:
Based on the snippet: <|code_start|> pass # The task is already finished elif task.done(): # Discard the pending exception (if any). # This makes sense since we don't know in which context the exception # was meant to be processed. For instance, a `StopAsyncIteration` # might be raised to notify that the end of a streamer has been reached. task.exception() # The task needs to be cancelled and awaited else: task.cancel() try: await task except asyncio.CancelledError: pass # Silence any exception raised while cancelling the task. # This might happen if the `CancelledError` is silenced, and the # corresponding async generator returns, causing the `anext` call # to raise a `StopAsyncIteration`. except Exception: pass finally: self._pending.discard(task) class StreamerManager: def __init__(self): self.tasks = {} self.streamers = [] self.group = TaskGroup() <|code_end|> , predict the immediate next line with the help of imports: import asyncio from .aiter_utils import AsyncExitStack from .aiter_utils import anext from .core import streamcontext and context (classes, functions, sometimes code) from other files: # Path: aiostream/aiter_utils.py # def aiter(obj): # def anext(obj): # async def await_(obj): # def async_(fn): # async def wrapper(*args, **kwargs): # def is_async_iterable(obj): # def assert_async_iterable(obj): # def is_async_iterator(obj): # def assert_async_iterator(obj): # def __init__(self, aiterator): # def __aiter__(self): # def __anext__(self): # async def __aenter__(self): # async def __aexit__(self, typ, value, traceback): # async def aclose(self): # async def athrow(self, exc): # def aitercontext(aiterable, *, cls=AsyncIteratorContext): # class AsyncIteratorContext(AsyncIterator): # _STANDBY = "STANDBY" # _RUNNING = "RUNNING" # _FINISHED = "FINISHED" # # Path: aiostream/aiter_utils.py # def anext(obj): # """Access anext magic method.""" # assert_async_iterator(obj) # return obj.__anext__() # # Path: aiostream/core.py # def streamcontext(aiterable): # """Return a stream context manager from an asynchronous iterable. # # The context management makes sure the aclose asynchronous method # of the corresponding iterator has run before it exits. It also issues # warnings and RuntimeError if it is used incorrectly. # # It is safe to use with any asynchronous iterable and prevent # asynchronous iterator context to be wrapped twice. # # Correct usage:: # # ait = some_asynchronous_iterable() # async with streamcontext(ait) as streamer: # async for item in streamer: # <block> # # For streams objects, it is possible to use the stream method instead:: # # xs = stream.count() # async with xs.stream() as streamer: # async for item in streamer: # <block> # """ # return aitercontext(aiterable, cls=Streamer) . Output only the next line.
self.stack = AsyncExitStack()
Predict the next line after this snippet: <|code_start|> self.tasks = {} self.streamers = [] self.group = TaskGroup() self.stack = AsyncExitStack() async def __aenter__(self): await self.stack.__aenter__() await self.stack.enter_async_context(self.group) return self async def __aexit__(self, *args): for streamer in self.streamers: task = self.tasks.pop(streamer, None) if task is not None: self.stack.push_async_callback(self.group.cancel_task, task) self.stack.push_async_exit(streamer) self.tasks.clear() self.streamers.clear() return await self.stack.__aexit__(*args) async def enter_and_create_task(self, aiter): streamer = streamcontext(aiter) await streamer.__aenter__() self.streamers.append(streamer) self.create_task(streamer) return streamer def create_task(self, streamer): assert streamer in self.streamers assert streamer not in self.tasks <|code_end|> using the current file's imports: import asyncio from .aiter_utils import AsyncExitStack from .aiter_utils import anext from .core import streamcontext and any relevant context from other files: # Path: aiostream/aiter_utils.py # def aiter(obj): # def anext(obj): # async def await_(obj): # def async_(fn): # async def wrapper(*args, **kwargs): # def is_async_iterable(obj): # def assert_async_iterable(obj): # def is_async_iterator(obj): # def assert_async_iterator(obj): # def __init__(self, aiterator): # def __aiter__(self): # def __anext__(self): # async def __aenter__(self): # async def __aexit__(self, typ, value, traceback): # async def aclose(self): # async def athrow(self, exc): # def aitercontext(aiterable, *, cls=AsyncIteratorContext): # class AsyncIteratorContext(AsyncIterator): # _STANDBY = "STANDBY" # _RUNNING = "RUNNING" # _FINISHED = "FINISHED" # # Path: aiostream/aiter_utils.py # def anext(obj): # """Access anext magic method.""" # assert_async_iterator(obj) # return obj.__anext__() # # Path: aiostream/core.py # def streamcontext(aiterable): # """Return a stream context manager from an asynchronous iterable. # # The context management makes sure the aclose asynchronous method # of the corresponding iterator has run before it exits. It also issues # warnings and RuntimeError if it is used incorrectly. # # It is safe to use with any asynchronous iterable and prevent # asynchronous iterator context to be wrapped twice. # # Correct usage:: # # ait = some_asynchronous_iterable() # async with streamcontext(ait) as streamer: # async for item in streamer: # <block> # # For streams objects, it is possible to use the stream method instead:: # # xs = stream.count() # async with xs.stream() as streamer: # async for item in streamer: # <block> # """ # return aitercontext(aiterable, cls=Streamer) . Output only the next line.
self.tasks[streamer] = self.group.create_task(anext(streamer))
Next line prediction: <|code_start|> # to raise a `StopAsyncIteration`. except Exception: pass finally: self._pending.discard(task) class StreamerManager: def __init__(self): self.tasks = {} self.streamers = [] self.group = TaskGroup() self.stack = AsyncExitStack() async def __aenter__(self): await self.stack.__aenter__() await self.stack.enter_async_context(self.group) return self async def __aexit__(self, *args): for streamer in self.streamers: task = self.tasks.pop(streamer, None) if task is not None: self.stack.push_async_callback(self.group.cancel_task, task) self.stack.push_async_exit(streamer) self.tasks.clear() self.streamers.clear() return await self.stack.__aexit__(*args) async def enter_and_create_task(self, aiter): <|code_end|> . Use current file imports: (import asyncio from .aiter_utils import AsyncExitStack from .aiter_utils import anext from .core import streamcontext) and context including class names, function names, or small code snippets from other files: # Path: aiostream/aiter_utils.py # def aiter(obj): # def anext(obj): # async def await_(obj): # def async_(fn): # async def wrapper(*args, **kwargs): # def is_async_iterable(obj): # def assert_async_iterable(obj): # def is_async_iterator(obj): # def assert_async_iterator(obj): # def __init__(self, aiterator): # def __aiter__(self): # def __anext__(self): # async def __aenter__(self): # async def __aexit__(self, typ, value, traceback): # async def aclose(self): # async def athrow(self, exc): # def aitercontext(aiterable, *, cls=AsyncIteratorContext): # class AsyncIteratorContext(AsyncIterator): # _STANDBY = "STANDBY" # _RUNNING = "RUNNING" # _FINISHED = "FINISHED" # # Path: aiostream/aiter_utils.py # def anext(obj): # """Access anext magic method.""" # assert_async_iterator(obj) # return obj.__anext__() # # Path: aiostream/core.py # def streamcontext(aiterable): # """Return a stream context manager from an asynchronous iterable. # # The context management makes sure the aclose asynchronous method # of the corresponding iterator has run before it exits. It also issues # warnings and RuntimeError if it is used incorrectly. # # It is safe to use with any asynchronous iterable and prevent # asynchronous iterator context to be wrapped twice. # # Correct usage:: # # ait = some_asynchronous_iterable() # async with streamcontext(ait) as streamer: # async for item in streamer: # <block> # # For streams objects, it is possible to use the stream method instead:: # # xs = stream.count() # async with xs.stream() as streamer: # async for item in streamer: # <block> # """ # return aitercontext(aiterable, cls=Streamer) . Output only the next line.
streamer = streamcontext(aiter)
Given snippet: <|code_start|> # Disable sync iteration # This is necessary because __getitem__ is defined # which is a valid fallback for for-loops in python __iter__ = None def stream(self): """Return a streamer context for safe iteration. Example:: xs = stream.count() async with xs.stream() as streamer: async for item in streamer: <block> """ return self.__aiter__() # Advertise the proper synthax for entering a stream context __aexit__ = None async def __aenter__(self): raise TypeError( "A stream object cannot be used as a context manager. " "Use the `stream` method instead: " "`async with xs.stream() as streamer`" ) <|code_end|> , continue by predicting the next line. Consider current file imports: import inspect import functools from collections.abc import AsyncIterable, Awaitable from .aiter_utils import AsyncIteratorContext from .aiter_utils import aitercontext, assert_async_iterable from .stream import chain from .stream import getitem and context: # Path: aiostream/aiter_utils.py # class AsyncIteratorContext(AsyncIterator): # """Asynchronous iterator with context management. # # The context management makes sure the aclose asynchronous method # of the corresponding iterator has run before it exits. It also issues # warnings and RuntimeError if it is used incorrectly. # # Correct usage:: # # ait = some_asynchronous_iterable() # async with AsyncIteratorContext(ait) as safe_ait: # async for item in safe_ait: # <block> # # It is nonetheless not meant to use directly. # Prefer aitercontext helper instead. # """ # # _STANDBY = "STANDBY" # _RUNNING = "RUNNING" # _FINISHED = "FINISHED" # # def __init__(self, aiterator): # """Initialize with an asynchrnous iterator.""" # assert_async_iterator(aiterator) # if isinstance(aiterator, AsyncIteratorContext): # raise TypeError(f"{aiterator!r} is already an AsyncIteratorContext") # self._state = self._STANDBY # self._aiterator = aiterator # # def __aiter__(self): # return self # # def __anext__(self): # if self._state == self._FINISHED: # raise RuntimeError( # f"{type(self).__name__} is closed and cannot be iterated" # ) # if self._state == self._STANDBY: # warnings.warn( # f"{type(self).__name__} is iterated outside of its context", # stacklevel=2, # ) # return anext(self._aiterator) # # async def __aenter__(self): # if self._state == self._RUNNING: # raise RuntimeError(f"{type(self).__name__} has already been entered") # if self._state == self._FINISHED: # raise RuntimeError( # f"{type(self).__name__} is closed and cannot be iterated" # ) # self._state = self._RUNNING # return self # # async def __aexit__(self, typ, value, traceback): # try: # if self._state == self._FINISHED: # return False # try: # # # No exception to throw # if typ is None: # return False # # # Prevent GeneratorExit from being silenced # if typ is GeneratorExit: # return False # # # No method to throw # if not hasattr(self._aiterator, "athrow"): # return False # # # No frame to throw # if not getattr(self._aiterator, "ag_frame", True): # return False # # # Cannot throw at the moment # if getattr(self._aiterator, "ag_running", False): # return False # # # Throw # try: # await self._aiterator.athrow(typ, value, traceback) # raise RuntimeError("Async iterator didn't stop after athrow()") # # # Exception has been (most probably) silenced # except StopAsyncIteration as exc: # return exc is not value # # # A (possibly new) exception has been raised # except BaseException as exc: # if exc is value: # return False # raise # finally: # # Look for an aclose method # aclose = getattr(self._aiterator, "aclose", None) # # # The ag_running attribute has been introduced with python 3.8 # running = getattr(self._aiterator, "ag_running", False) # closed = not getattr(self._aiterator, "ag_frame", True) # # # A RuntimeError is raised if aiterator is running or closed # if aclose and not running and not closed: # try: # await aclose() # # # Work around bpo-35409 # except GeneratorExit: # pass # pragma: no cover # finally: # self._state = self._FINISHED # # async def aclose(self): # await self.__aexit__(None, None, None) # # async def athrow(self, exc): # if self._state == self._FINISHED: # raise RuntimeError(f"{type(self).__name__} is closed and cannot be used") # return await self._aiterator.athrow(exc) # # Path: aiostream/aiter_utils.py # def aitercontext(aiterable, *, cls=AsyncIteratorContext): # """Return an asynchronous context manager from an asynchronous iterable. # # The context management makes sure the aclose asynchronous method # has run before it exits. It also issues warnings and RuntimeError # if it is used incorrectly. # # It is safe to use with any asynchronous iterable and prevent # asynchronous iterator context to be wrapped twice. # # Correct usage:: # # ait = some_asynchronous_iterable() # async with aitercontext(ait) as safe_ait: # async for item in safe_ait: # <block> # # An optional subclass of AsyncIteratorContext can be provided. # This class will be used to wrap the given iterable. # """ # assert issubclass(cls, AsyncIteratorContext) # aiterator = aiter(aiterable) # if isinstance(aiterator, cls): # return aiterator # return cls(aiterator) # # def assert_async_iterable(obj): # """Raise a TypeError if the given object is not an # asynchronous iterable. # """ # if not is_async_iterable(obj): # raise TypeError(f"{type(obj).__name__!r} object is not async iterable") which might include code, classes, or functions. Output only the next line.
class Streamer(AsyncIteratorContext, Stream):
Here is a snippet: <|code_start|> await streamer[5] """ pass def streamcontext(aiterable): """Return a stream context manager from an asynchronous iterable. The context management makes sure the aclose asynchronous method of the corresponding iterator has run before it exits. It also issues warnings and RuntimeError if it is used incorrectly. It is safe to use with any asynchronous iterable and prevent asynchronous iterator context to be wrapped twice. Correct usage:: ait = some_asynchronous_iterable() async with streamcontext(ait) as streamer: async for item in streamer: <block> For streams objects, it is possible to use the stream method instead:: xs = stream.count() async with xs.stream() as streamer: async for item in streamer: <block> """ <|code_end|> . Write the next line using the current file imports: import inspect import functools from collections.abc import AsyncIterable, Awaitable from .aiter_utils import AsyncIteratorContext from .aiter_utils import aitercontext, assert_async_iterable from .stream import chain from .stream import getitem and context from other files: # Path: aiostream/aiter_utils.py # class AsyncIteratorContext(AsyncIterator): # """Asynchronous iterator with context management. # # The context management makes sure the aclose asynchronous method # of the corresponding iterator has run before it exits. It also issues # warnings and RuntimeError if it is used incorrectly. # # Correct usage:: # # ait = some_asynchronous_iterable() # async with AsyncIteratorContext(ait) as safe_ait: # async for item in safe_ait: # <block> # # It is nonetheless not meant to use directly. # Prefer aitercontext helper instead. # """ # # _STANDBY = "STANDBY" # _RUNNING = "RUNNING" # _FINISHED = "FINISHED" # # def __init__(self, aiterator): # """Initialize with an asynchrnous iterator.""" # assert_async_iterator(aiterator) # if isinstance(aiterator, AsyncIteratorContext): # raise TypeError(f"{aiterator!r} is already an AsyncIteratorContext") # self._state = self._STANDBY # self._aiterator = aiterator # # def __aiter__(self): # return self # # def __anext__(self): # if self._state == self._FINISHED: # raise RuntimeError( # f"{type(self).__name__} is closed and cannot be iterated" # ) # if self._state == self._STANDBY: # warnings.warn( # f"{type(self).__name__} is iterated outside of its context", # stacklevel=2, # ) # return anext(self._aiterator) # # async def __aenter__(self): # if self._state == self._RUNNING: # raise RuntimeError(f"{type(self).__name__} has already been entered") # if self._state == self._FINISHED: # raise RuntimeError( # f"{type(self).__name__} is closed and cannot be iterated" # ) # self._state = self._RUNNING # return self # # async def __aexit__(self, typ, value, traceback): # try: # if self._state == self._FINISHED: # return False # try: # # # No exception to throw # if typ is None: # return False # # # Prevent GeneratorExit from being silenced # if typ is GeneratorExit: # return False # # # No method to throw # if not hasattr(self._aiterator, "athrow"): # return False # # # No frame to throw # if not getattr(self._aiterator, "ag_frame", True): # return False # # # Cannot throw at the moment # if getattr(self._aiterator, "ag_running", False): # return False # # # Throw # try: # await self._aiterator.athrow(typ, value, traceback) # raise RuntimeError("Async iterator didn't stop after athrow()") # # # Exception has been (most probably) silenced # except StopAsyncIteration as exc: # return exc is not value # # # A (possibly new) exception has been raised # except BaseException as exc: # if exc is value: # return False # raise # finally: # # Look for an aclose method # aclose = getattr(self._aiterator, "aclose", None) # # # The ag_running attribute has been introduced with python 3.8 # running = getattr(self._aiterator, "ag_running", False) # closed = not getattr(self._aiterator, "ag_frame", True) # # # A RuntimeError is raised if aiterator is running or closed # if aclose and not running and not closed: # try: # await aclose() # # # Work around bpo-35409 # except GeneratorExit: # pass # pragma: no cover # finally: # self._state = self._FINISHED # # async def aclose(self): # await self.__aexit__(None, None, None) # # async def athrow(self, exc): # if self._state == self._FINISHED: # raise RuntimeError(f"{type(self).__name__} is closed and cannot be used") # return await self._aiterator.athrow(exc) # # Path: aiostream/aiter_utils.py # def aitercontext(aiterable, *, cls=AsyncIteratorContext): # """Return an asynchronous context manager from an asynchronous iterable. # # The context management makes sure the aclose asynchronous method # has run before it exits. It also issues warnings and RuntimeError # if it is used incorrectly. # # It is safe to use with any asynchronous iterable and prevent # asynchronous iterator context to be wrapped twice. # # Correct usage:: # # ait = some_asynchronous_iterable() # async with aitercontext(ait) as safe_ait: # async for item in safe_ait: # <block> # # An optional subclass of AsyncIteratorContext can be provided. # This class will be used to wrap the given iterable. # """ # assert issubclass(cls, AsyncIteratorContext) # aiterator = aiter(aiterable) # if isinstance(aiterator, cls): # return aiterator # return cls(aiterator) # # def assert_async_iterable(obj): # """Raise a TypeError if the given object is not an # asynchronous iterable. # """ # if not is_async_iterable(obj): # raise TypeError(f"{type(obj).__name__!r} object is not async iterable") , which may include functions, classes, or code. Output only the next line.
return aitercontext(aiterable, cls=Streamer)
Predict the next line after this snippet: <|code_start|> 'description_en': u'List of CPM films for all times', 'description_be': u'Список фильмов CPM на все времена', 'description_ru': u'Спіс фільмаў CPM на ўсе часы', } def get_film_frame(apps, item): Image = get_image_model(apps) Collection = apps.get_model('wagtailcore.Collection') collection_id = Collection.objects.filter(depth=1)[0] title = slugify(item['film_title_en']) frame = Image(title=title, collection=collection_id) photo_file = os.path.join(DIR_0017, item['frame']) frame.file.save( name=title + os.extsep + '.jpg', content=File(open(photo_file, 'rb')) ) return frame def create_film_index_page(apps): index_page_ct = get_content_type(apps, 'cpm_generic', 'indexpage') IndexPage = apps.get_model('cpm_generic.IndexPage') HomePage = apps.get_model('home.HomePage') homepage = HomePage.objects.get(slug='home') <|code_end|> using the current file's imports: import os import json from itertools import chain from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, get_content_type, get_image_model, remove_subpage) and any relevant context from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
filmsindex_page = add_subpage(
Given the following code snippet before the placeholder: <|code_start|> 'title': u'Films', 'slug': 'films', 'caption_en': u'Films', 'caption_be': u'Фільмы', 'caption_ru': u'Фильмы', 'description_en': u'List of CPM films for all times', 'description_be': u'Список фильмов CPM на все времена', 'description_ru': u'Спіс фільмаў CPM на ўсе часы', } def get_film_frame(apps, item): Image = get_image_model(apps) Collection = apps.get_model('wagtailcore.Collection') collection_id = Collection.objects.filter(depth=1)[0] title = slugify(item['film_title_en']) frame = Image(title=title, collection=collection_id) photo_file = os.path.join(DIR_0017, item['frame']) frame.file.save( name=title + os.extsep + '.jpg', content=File(open(photo_file, 'rb')) ) return frame def create_film_index_page(apps): <|code_end|> , predict the next line using imports from the current file: import os import json from itertools import chain from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, get_content_type, get_image_model, remove_subpage) and context including class names, function names, and sometimes code from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
index_page_ct = get_content_type(apps, 'cpm_generic', 'indexpage')
Given the following code snippet before the placeholder: <|code_start|>def get_films_2012_data(): films_json = os.path.join( MIGRATION_DIR, '0017_add_films_2012_data/films2012.json' ) return json.load(open(films_json, 'rb'), 'utf8') def get_nominations(): nomination_json = os.path.join( MIGRATION_DIR, '0017_add_films_2012_data/nominations2012.json' ) return json.load(open(nomination_json, 'rb'), 'utf8') def _get_filmsindex_kw(): return { 'title': u'Films', 'slug': 'films', 'caption_en': u'Films', 'caption_be': u'Фільмы', 'caption_ru': u'Фильмы', 'description_en': u'List of CPM films for all times', 'description_be': u'Список фильмов CPM на все времена', 'description_ru': u'Спіс фільмаў CPM на ўсе часы', } def get_film_frame(apps, item): <|code_end|> , predict the next line using imports from the current file: import os import json from itertools import chain from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, get_content_type, get_image_model, remove_subpage) and context including class names, function names, and sometimes code from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
Image = get_image_model(apps)
Given the code snippet: <|code_start|> FilmPage = apps.get_model("results.FilmPage") ResultsRelatedWinner = apps.get_model('results.ResultsRelatedWinner') film_page_ct = get_content_type(apps, 'results', 'filmpage') collection_id = Collection.objects.filter(depth=1)[0] HomePage = apps.get_model('home.HomePage') homepage = HomePage.objects.get(slug='home') IndexPage = apps.get_model('cpm_generic.IndexPage') filmsindex_page = IndexPage.objects.get(slug='films') films2012_data = get_films_2012_data() results2012_page = get_results_page(apps) related_film_ids = chain.from_iterable( ResultsRelatedWinner.objects.filter( film=FilmPage.objects.filter(title=item['film_title_en']), page=results2012_page, ).values_list('id', flat=True) for item in films2012_data ) ResultsRelatedWinner.objects.filter(id__in=related_film_ids).delete() for item in films2012_data: title = slugify(item['film_title_en']) photo = Image.objects.get(title=title, collection=collection_id) photo.delete() <|code_end|> , generate the next line using the imports in this file: import os import json from itertools import chain from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, get_content_type, get_image_model, remove_subpage) and context (functions, classes, or occasionally code) from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
remove_subpage(
Here is a snippet: <|code_start|> class TestAdminModelChooserPanel(object): @pytest.fixture def model(self): """A model with a foreign key to Page which we want to render as a page chooser """ return PageChooserModel @pytest.fixture def edit_handler_class(self, model): """A AdminModelChooserPanel class that works on PageChooserModel's 'page' field """ <|code_end|> . Write the next line using the current file imports: import pytest from wagtail.tests.testapp.models import PageChooserModel from wagtail.wagtailadmin.edit_handlers import ObjectList from wagtail.wagtailcore.models import Page from modeladminutils.edit_handlers import AdminModelChooserPanel and context from other files: # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) , which may include functions, classes, or code. Output only the next line.
object_list = ObjectList([AdminModelChooserPanel('page')])
Next line prediction: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals def clear_jury_data(apps, schema_editor): HomePage = apps.get_model('home.HomePage') IndexPage = apps.get_model('cpm_generic.IndexPage') JuryMemberPage = apps.get_model('results.JuryMemberPage') RelatedJuryMember = apps.get_model('results.ResultsRelatedJuryMember') homepage = HomePage.objects.get(slug='home') juryindex = IndexPage.objects.get(slug='jury') for obj in RelatedJuryMember.objects.all(): obj.delete() for obj in JuryMemberPage.objects.all(): obj.photo.delete() <|code_end|> . Use current file imports: (from django.db import migrations from cpm_generic.migration_utils import remove_subpage) and context including class names, function names, or small code snippets from other files: # Path: cpm_generic/migration_utils.py # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
remove_subpage(
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals DATA_DIR = os.path.join(os.path.dirname(__file__), '0004') TIMETABLE_TITLE = 'Timetable' def _get_data(filename): with open(os.path.join(DATA_DIR, filename)) as data_file: return json.load(data_file) def add_filmprograms_2017(apps, schema_editor): FilmProgram = apps.get_model('events.FilmProgram') filmprogram_ct = get_content_type(apps, 'events', 'filmprogram') HomePage = apps.get_model('home.HomePage') homepage = HomePage.objects.get(slug='home') for item in _get_data('filmprograms.json'): if not FilmProgram.objects.filter(title=item['title']).exists(): <|code_end|> , predict the next line using imports from the current file: import json import os from dateutil.parser import parse as parse_datetime from django.conf import settings from django.db import migrations from cpm_generic.migration_utils import (add_subpage, get_content_type, remove_subpage) and context including class names, function names, and sometimes code from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
add_subpage(
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals DATA_DIR = os.path.join(os.path.dirname(__file__), '0004') TIMETABLE_TITLE = 'Timetable' def _get_data(filename): with open(os.path.join(DATA_DIR, filename)) as data_file: return json.load(data_file) def add_filmprograms_2017(apps, schema_editor): FilmProgram = apps.get_model('events.FilmProgram') <|code_end|> . Write the next line using the current file imports: import json import os from dateutil.parser import parse as parse_datetime from django.conf import settings from django.db import migrations from cpm_generic.migration_utils import (add_subpage, get_content_type, remove_subpage) and context from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() , which may include functions, classes, or code. Output only the next line.
filmprogram_ct = get_content_type(apps, 'events', 'filmprogram')
Predict the next line after this snippet: <|code_start|> with open(os.path.join(DATA_DIR, filename)) as data_file: return json.load(data_file) def add_filmprograms_2017(apps, schema_editor): FilmProgram = apps.get_model('events.FilmProgram') filmprogram_ct = get_content_type(apps, 'events', 'filmprogram') HomePage = apps.get_model('home.HomePage') homepage = HomePage.objects.get(slug='home') for item in _get_data('filmprograms.json'): if not FilmProgram.objects.filter(title=item['title']).exists(): add_subpage( parent=homepage, model=FilmProgram, content_type=filmprogram_ct, live=True, **item ) def remove_filmprograms_2017(apps, schema_editor): FilmProgram = apps.get_model('events.FilmProgram') HomePage = apps.get_model('home.HomePage') homepage = HomePage.objects.get(slug='home') for item in _get_data('filmprograms.json'): if FilmProgram.objects.filter(title=item['title']).exists(): <|code_end|> using the current file's imports: import json import os from dateutil.parser import parse as parse_datetime from django.conf import settings from django.db import migrations from cpm_generic.migration_utils import (add_subpage, get_content_type, remove_subpage) and any relevant context from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
remove_subpage(
Given the following code snippet before the placeholder: <|code_start|># Generated by Django 1.9.8 on 2016-12-10 22:48 from __future__ import unicode_literals DIR_0011 = os.path.join(os.path.dirname(__file__), '0011') def _get_photo_path(filename): return os.path.join(DIR_0011, filename) def _get_season(apps, season_name): Season = apps.get_model('cpm_data.Season') return Season.objects.get(name_en=season_name) def _get_data(season_year): with open(os.path.join( DIR_0011, 'jury_' + season_year + '.json' )) as data_file: return json.load(data_file) def add_jurymembers(apps, schema_editor, season_name): season = _get_season(apps, season_name=season_name) JuryMember = apps.get_model('cpm_data.JuryMember') <|code_end|> , predict the next line using imports from the current file: from functools import partial from django.core.files import File from django.db import migrations from cpm_generic.migration_utils import get_image_model import json import os and context including class names, function names, and sometimes code from other files: # Path: cpm_generic/migration_utils.py # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image . Output only the next line.
Image = get_image_model(apps)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals def update_pavel_ivanov(apps, schema_editor): JuryMember = apps.get_model('cpm_data.JuryMember') try: pavel_ivanov = JuryMember.objects.get(name_en='Pavel Ivanov') except JuryMember.DoesNotExist: pass else: this_dir = os.path.dirname(__file__) filepath = os.path.join(this_dir, '0013', 'Pavel Ivanov.jpg') <|code_end|> . Write the next line using the current file imports: import os from django.db import migrations from cpm_generic.migration_utils import get_image and context from other files: # Path: cpm_generic/migration_utils.py # def get_image(apps, title, filepath): # """Get image object from a local file.""" # # Image = get_image_model(apps) # Collection = apps.get_model('wagtailcore.Collection') # collection_id = Collection.objects.filter(depth=1)[0] # # image = Image(title=title, collection=collection_id) # with open(filepath, 'rb') as image_file: # image.file.save(name=os.path.basename(filepath), # content=File(image_file)) # image.save() # # return image , which may include functions, classes, or code. Output only the next line.
new_photo = get_image(apps, 'Pavel Ivanov', filepath)
Predict the next line for this snippet: <|code_start|> 'description_en': u'List of CPM partners for all times', 'description_be': u'Список партнеров CPM на все времена', 'description_ru': u'Спіс партнёраў CPM на ўсе часы', } def get_parner_image(apps, item): Image = get_image_model(apps) Collection = apps.get_model('wagtailcore.Collection') collection_id = Collection.objects.filter(depth=1)[0] title = slugify(item['name_en']) frame = Image(title=title, collection=collection_id) photo_file = os.path.join(DIR_0017, item['image']) frame.file.save( name=title + os.extsep + '.jpg', content=File(open(photo_file, 'rb')) ) return frame def create_partner_index_page(apps): index_page_ct = get_content_type(apps, 'cpm_generic', 'indexpage') IndexPage = apps.get_model('cpm_generic.IndexPage') HomePage = apps.get_model('home.HomePage') homepage = HomePage.objects.get(slug='home') <|code_end|> with the help of current file imports: import os import json from itertools import chain from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, get_content_type, get_image_model, remove_subpage) and context from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() , which may contain function names, class names, or code. Output only the next line.
partnerindex_page = add_subpage(
Here is a snippet: <|code_start|> 'title': u'Partners', 'slug': 'Partners', 'caption_en': u'Partners', 'caption_be': u'Партнёры', 'caption_ru': u'Партнеры', 'description_en': u'List of CPM partners for all times', 'description_be': u'Список партнеров CPM на все времена', 'description_ru': u'Спіс партнёраў CPM на ўсе часы', } def get_parner_image(apps, item): Image = get_image_model(apps) Collection = apps.get_model('wagtailcore.Collection') collection_id = Collection.objects.filter(depth=1)[0] title = slugify(item['name_en']) frame = Image(title=title, collection=collection_id) photo_file = os.path.join(DIR_0017, item['image']) frame.file.save( name=title + os.extsep + '.jpg', content=File(open(photo_file, 'rb')) ) return frame def create_partner_index_page(apps): <|code_end|> . Write the next line using the current file imports: import os import json from itertools import chain from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, get_content_type, get_image_model, remove_subpage) and context from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() , which may include functions, classes, or code. Output only the next line.
index_page_ct = get_content_type(apps, 'cpm_generic', 'indexpage')
Given the code snippet: <|code_start|> MIGRATION_DIR = os.path.dirname(__file__) DIR_0017 = os.path.join(MIGRATION_DIR, '0018_add_partners_2012_data') # TODO: coulds be abstracted def get_partners_2012_data(): partners_json = os.path.join( MIGRATION_DIR, '0018_add_partners_2012_data/partners.json' ) return json.load(open(partners_json, 'rb'), 'utf8') def _get_partnerindex_kw(): return { 'title': u'Partners', 'slug': 'Partners', 'caption_en': u'Partners', 'caption_be': u'Партнёры', 'caption_ru': u'Партнеры', 'description_en': u'List of CPM partners for all times', 'description_be': u'Список партнеров CPM на все времена', 'description_ru': u'Спіс партнёраў CPM на ўсе часы', } def get_parner_image(apps, item): <|code_end|> , generate the next line using the imports in this file: import os import json from itertools import chain from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, get_content_type, get_image_model, remove_subpage) and context (functions, classes, or occasionally code) from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
Image = get_image_model(apps)
Predict the next line for this snippet: <|code_start|> PartnerPage = apps.get_model("results.PartnerPage") ResultsRelatedPartner = apps.get_model('results.ResultsRelatedPartner') partner_page_ct = get_content_type(apps, 'results', 'partnerpage') collection_id = Collection.objects.filter(depth=1)[0] HomePage = apps.get_model('home.HomePage') homepage = HomePage.objects.get(slug='home') IndexPage = apps.get_model('cpm_generic.IndexPage') partnersindex_page = IndexPage.objects.get(slug='Partners') partners_data = get_partners_2012_data() results2012_page = get_results_page(apps) related_film_ids = chain.from_iterable( ResultsRelatedPartner.objects.filter( partner=PartnerPage.objects.filter(title=item['name_en']), page=results2012_page, ).values_list('id', flat=True) for item in partners_data ) ResultsRelatedPartner.objects.filter(id__in=related_film_ids).delete() for item in partners_data: title = slugify(item['name_en']) photo = Image.objects.get(title=title, collection=collection_id) photo.delete() <|code_end|> with the help of current file imports: import os import json from itertools import chain from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, get_content_type, get_image_model, remove_subpage) and context from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() , which may contain function names, class names, or code. Output only the next line.
remove_subpage(
Predict the next line for this snippet: <|code_start|> __all__ = ['SearchableManager'] class BaseSearchableManager(models.Manager): def get_queryset(self): <|code_end|> with the help of current file imports: from django.db import models from modeladminutils.queryset import SearchableQuerySet and context from other files: # Path: modeladminutils/queryset.py # class SearchableQuerySet(SearchableQuerySetMixin, models.query.QuerySet): # pass , which may contain function names, class names, or code. Output only the next line.
return SearchableQuerySet(self.model)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-03-13 21:41 def add_partners_page(apps, schema_editor): HomePage = apps.get_model('home.HomePage') PartnersPage = apps.get_model('partners.PartnersPage') Season = apps.get_model('cpm_data.Season') <|code_end|> , generate the next line using the imports in this file: from django.db import migrations from cpm_generic.migration_utils import (get_content_type, add_subpage, remove_subpage) and context (functions, classes, or occasionally code) from other files: # Path: cpm_generic/migration_utils.py # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
partners_page_ct = get_content_type(apps, 'partners', 'partnerspage')
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-03-13 21:41 def add_partners_page(apps, schema_editor): HomePage = apps.get_model('home.HomePage') PartnersPage = apps.get_model('partners.PartnersPage') Season = apps.get_model('cpm_data.Season') partners_page_ct = get_content_type(apps, 'partners', 'partnerspage') homepage = HomePage.objects.get(slug='home') season = Season.objects.get(name_en='2017') <|code_end|> , determine the next line of code. You have imports: from django.db import migrations from cpm_generic.migration_utils import (get_content_type, add_subpage, remove_subpage) and context (class names, function names, or code) available: # Path: cpm_generic/migration_utils.py # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
add_subpage(
Predict the next line after this snippet: <|code_start|> Season = apps.get_model('cpm_data.Season') partners_page_ct = get_content_type(apps, 'partners', 'partnerspage') homepage = HomePage.objects.get(slug='home') season = Season.objects.get(name_en='2017') add_subpage( homepage, PartnersPage, content_type=partners_page_ct, title=u'CPM Partners', slug='partners', name_en=u'Partners', name_be=u'Партнёры', name_ru=u'Партнеры', entry_en=u'<i>Cinema Perpetuum Mobile</i> is a non-profit, independent project which keeps on expenses and aspirations of the organizers. At the same time international nature of the event, cultural resonance provides fertile ground for collaboration with business and public organizations.', # noqa:E501 entry_be=u'<i>Cinema Perpetuum Mobile</i> - некамерцыйны, незалежны праект, які трымаецца на імкненнях і сродках арганізатараў. У той жа час чакаемы культурны рэзананс падзеі, яе міжнародны характар, актыўныя зацікаўленнасці, ствараюць выдатную глебу для супрацоўніцтва з камерцыйнымі і грамадскімі ўстановамі.', # noqa:E501 entry_ru=u'<i>Cinema Perpetuum Mobile</i> - некоммерческий, независимый проект, который держится на устремлениях и расходах организаторов. В то же время международный характер события, его культурный резонанс, заинтересованности, создают благоприятную почву для сотрудничества с коммерческими и общественными организациями.', # noqa:E501 season=season ) def remove_partners_page(apps, schema_editor): HomePage = apps.get_model('home.HomePage') PartnersPage = apps.get_model('partners.PartnersPage') partners_page_ct = get_content_type(apps, 'partners', 'partnerspage') homepage = HomePage.objects.get(slug='home') <|code_end|> using the current file's imports: from django.db import migrations from cpm_generic.migration_utils import (get_content_type, add_subpage, remove_subpage) and any relevant context from other files: # Path: cpm_generic/migration_utils.py # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() . Output only the next line.
remove_subpage(
Here is a snippet: <|code_start|>from __future__ import unicode_literals class ResultsRelatedWinner(Orderable): page = ParentalKey('ResultsPage', related_name='related_winners') film = models.ForeignKey( 'cpm_data.Film', null=False, blank=False, related_name='+' ) nomination_en = models.CharField(max_length=250, blank=True, default='') nomination_be = models.CharField(max_length=250, blank=True, default='') nomination_ru = models.CharField(max_length=250, blank=True, default='') <|code_end|> . Write the next line using the current file imports: from django.db import models from django.utils.translation import ugettext_lazy as _ from modelcluster.fields import ParentalKey from wagtail.wagtailcore.models import Orderable, Page from wagtail.wagtailadmin.edit_handlers import (FieldPanel, InlinePanel, PageChooserPanel) from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from cpm_generic.models import TranslatedField from modeladminutils.edit_handlers import AdminModelChooserPanel and context from other files: # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) # # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) , which may include functions, classes, or code. Output only the next line.
nomination = TranslatedField('nomination_en',
Given the following code snippet before the placeholder: <|code_start|> class ResultsRelatedWinner(Orderable): page = ParentalKey('ResultsPage', related_name='related_winners') film = models.ForeignKey( 'cpm_data.Film', null=False, blank=False, related_name='+' ) nomination_en = models.CharField(max_length=250, blank=True, default='') nomination_be = models.CharField(max_length=250, blank=True, default='') nomination_ru = models.CharField(max_length=250, blank=True, default='') nomination = TranslatedField('nomination_en', 'nomination_be', 'nomination_ru') film_title = property(lambda self: self.film.title) director = property(lambda self: self.film.director) country = property(lambda self: self.film.country) city = property(lambda self: self.film.city) year = property(lambda self: self.film.year) duration = property(lambda self: self.film.duration) genre = property(lambda self: self.film.genre) synopsis_short = property(lambda self: self.film.synopsis_short) synopsis = property(lambda self: self.film.synopsis) frame = property(lambda self: self.film.frame) panels = [ <|code_end|> , predict the next line using imports from the current file: from django.db import models from django.utils.translation import ugettext_lazy as _ from modelcluster.fields import ParentalKey from wagtail.wagtailcore.models import Orderable, Page from wagtail.wagtailadmin.edit_handlers import (FieldPanel, InlinePanel, PageChooserPanel) from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from cpm_generic.models import TranslatedField from modeladminutils.edit_handlers import AdminModelChooserPanel and context including class names, function names, and sometimes code from other files: # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) # # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) . Output only the next line.
AdminModelChooserPanel('film'),
Given the code snippet: <|code_start|> @hooks.register('register_admin_urls') def register_admin_urls(): return [ <|code_end|> , generate the next line using the imports in this file: from django.conf.urls import include, url from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem from submissions import admin_urls and context (functions, classes, or occasionally code) from other files: # Path: submissions/admin_urls.py . Output only the next line.
url(r'^submissions/', include(admin_urls, namespace='submissions')),
Predict the next line for this snippet: <|code_start|> class Submission(models.Model): title = models.CharField(verbose_name=_('Original title'), max_length=1000) title_en = models.CharField(verbose_name=_('English title'), max_length=1000) country = models.CharField(verbose_name=_('Country of production'), max_length=2, choices=COUNTRIES) language = models.CharField(verbose_name=_('Language of original version'), max_length=10, choices=LANGUAGES) genre = models.CharField(verbose_name=_('Genre'), max_length=1000, blank=True, null=True) section = models.IntegerField(verbose_name=_('Section'), choices=SECTIONS) synopsis = models.TextField(verbose_name=_('Synopsis')) length = models.IntegerField(verbose_name=_('Runtime (in minutes)')) aspect_ratio = models.CharField(verbose_name=_('Aspect ratio'), max_length=1000) year = models.IntegerField(verbose_name=_('Year of production')) <|code_end|> with the help of current file imports: from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cpm_generic.constants import COUNTRIES from submissions.constants import (YESNO, YESNOMAYBE, LANGUAGES, SECTIONS, BACKLINKS) and context from other files: # Path: submissions/constants.py # YESNO = ( # (1, _('Yes')), # (2, _('No')), # ) # # YESNOMAYBE = ( # (0, _('Maybe')), # (1, _('Yes')), # (2, _('No')), # ) # # LANGUAGES = sorted( # ( # (lang.alpha2, _(lang.name)) # for lang in pycountry.languages # if hasattr(lang, 'alpha2') # ), # key=lambda x: x[1] # ) # # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) # # BACKLINKS = ( # (1, _('festival website')), # (2, _('Facebook')), # (3, _('Twitter')), # (4, _('vk.com')), # (5, _('email')), # (6, _('internet search')), # (7, _('friends')), # (8, _('festivals database')), # (9, _('I participated in CPM\'2012')), # (10, _('place of study')), # (11, _('work')), # (12, _('other')), # ) , which may contain function names, class names, or code. Output only the next line.
premiere = models.IntegerField(verbose_name=_('Premiere'), choices=YESNO)
Given the following code snippet before the placeholder: <|code_start|> country = models.CharField(verbose_name=_('Country of production'), max_length=2, choices=COUNTRIES) language = models.CharField(verbose_name=_('Language of original version'), max_length=10, choices=LANGUAGES) genre = models.CharField(verbose_name=_('Genre'), max_length=1000, blank=True, null=True) section = models.IntegerField(verbose_name=_('Section'), choices=SECTIONS) synopsis = models.TextField(verbose_name=_('Synopsis')) length = models.IntegerField(verbose_name=_('Runtime (in minutes)')) aspect_ratio = models.CharField(verbose_name=_('Aspect ratio'), max_length=1000) year = models.IntegerField(verbose_name=_('Year of production')) premiere = models.IntegerField(verbose_name=_('Premiere'), choices=YESNO) film_awards = models.TextField(verbose_name=_('Film awards'), blank=True) director_awards = models.TextField( verbose_name=_('Director awards'), blank=True) budget = models.CharField(verbose_name=_('Film budget'), max_length=1000) film_link = models.CharField( verbose_name=_('Link to download the film (optional)'), help_text=_(u'DVD, MPEG, MP4 or MOV'), max_length=1000, blank=True ) film_link_pwd = models.CharField( verbose_name=_('Password for the link above (optional)'), max_length=1000, blank=True ) attend = models.IntegerField( verbose_name=_('I intend to visit final part of festival'), <|code_end|> , predict the next line using imports from the current file: from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cpm_generic.constants import COUNTRIES from submissions.constants import (YESNO, YESNOMAYBE, LANGUAGES, SECTIONS, BACKLINKS) and context including class names, function names, and sometimes code from other files: # Path: submissions/constants.py # YESNO = ( # (1, _('Yes')), # (2, _('No')), # ) # # YESNOMAYBE = ( # (0, _('Maybe')), # (1, _('Yes')), # (2, _('No')), # ) # # LANGUAGES = sorted( # ( # (lang.alpha2, _(lang.name)) # for lang in pycountry.languages # if hasattr(lang, 'alpha2') # ), # key=lambda x: x[1] # ) # # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) # # BACKLINKS = ( # (1, _('festival website')), # (2, _('Facebook')), # (3, _('Twitter')), # (4, _('vk.com')), # (5, _('email')), # (6, _('internet search')), # (7, _('friends')), # (8, _('festivals database')), # (9, _('I participated in CPM\'2012')), # (10, _('place of study')), # (11, _('work')), # (12, _('other')), # ) . Output only the next line.
choices=YESNOMAYBE, default=0)
Continue the code snippet: <|code_start|> class Submission(models.Model): title = models.CharField(verbose_name=_('Original title'), max_length=1000) title_en = models.CharField(verbose_name=_('English title'), max_length=1000) country = models.CharField(verbose_name=_('Country of production'), max_length=2, choices=COUNTRIES) language = models.CharField(verbose_name=_('Language of original version'), <|code_end|> . Use current file imports: from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cpm_generic.constants import COUNTRIES from submissions.constants import (YESNO, YESNOMAYBE, LANGUAGES, SECTIONS, BACKLINKS) and context (classes, functions, or code) from other files: # Path: submissions/constants.py # YESNO = ( # (1, _('Yes')), # (2, _('No')), # ) # # YESNOMAYBE = ( # (0, _('Maybe')), # (1, _('Yes')), # (2, _('No')), # ) # # LANGUAGES = sorted( # ( # (lang.alpha2, _(lang.name)) # for lang in pycountry.languages # if hasattr(lang, 'alpha2') # ), # key=lambda x: x[1] # ) # # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) # # BACKLINKS = ( # (1, _('festival website')), # (2, _('Facebook')), # (3, _('Twitter')), # (4, _('vk.com')), # (5, _('email')), # (6, _('internet search')), # (7, _('friends')), # (8, _('festivals database')), # (9, _('I participated in CPM\'2012')), # (10, _('place of study')), # (11, _('work')), # (12, _('other')), # ) . Output only the next line.
max_length=10, choices=LANGUAGES)
Predict the next line after this snippet: <|code_start|> class Submission(models.Model): title = models.CharField(verbose_name=_('Original title'), max_length=1000) title_en = models.CharField(verbose_name=_('English title'), max_length=1000) country = models.CharField(verbose_name=_('Country of production'), max_length=2, choices=COUNTRIES) language = models.CharField(verbose_name=_('Language of original version'), max_length=10, choices=LANGUAGES) genre = models.CharField(verbose_name=_('Genre'), max_length=1000, blank=True, null=True) section = models.IntegerField(verbose_name=_('Section'), <|code_end|> using the current file's imports: from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cpm_generic.constants import COUNTRIES from submissions.constants import (YESNO, YESNOMAYBE, LANGUAGES, SECTIONS, BACKLINKS) and any relevant context from other files: # Path: submissions/constants.py # YESNO = ( # (1, _('Yes')), # (2, _('No')), # ) # # YESNOMAYBE = ( # (0, _('Maybe')), # (1, _('Yes')), # (2, _('No')), # ) # # LANGUAGES = sorted( # ( # (lang.alpha2, _(lang.name)) # for lang in pycountry.languages # if hasattr(lang, 'alpha2') # ), # key=lambda x: x[1] # ) # # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) # # BACKLINKS = ( # (1, _('festival website')), # (2, _('Facebook')), # (3, _('Twitter')), # (4, _('vk.com')), # (5, _('email')), # (6, _('internet search')), # (7, _('friends')), # (8, _('festivals database')), # (9, _('I participated in CPM\'2012')), # (10, _('place of study')), # (11, _('work')), # (12, _('other')), # ) . Output only the next line.
choices=SECTIONS)
Predict the next line for this snippet: <|code_start|> genre = models.CharField(verbose_name=_('Genre'), max_length=1000, blank=True, null=True) section = models.IntegerField(verbose_name=_('Section'), choices=SECTIONS) synopsis = models.TextField(verbose_name=_('Synopsis')) length = models.IntegerField(verbose_name=_('Runtime (in minutes)')) aspect_ratio = models.CharField(verbose_name=_('Aspect ratio'), max_length=1000) year = models.IntegerField(verbose_name=_('Year of production')) premiere = models.IntegerField(verbose_name=_('Premiere'), choices=YESNO) film_awards = models.TextField(verbose_name=_('Film awards'), blank=True) director_awards = models.TextField( verbose_name=_('Director awards'), blank=True) budget = models.CharField(verbose_name=_('Film budget'), max_length=1000) film_link = models.CharField( verbose_name=_('Link to download the film (optional)'), help_text=_(u'DVD, MPEG, MP4 or MOV'), max_length=1000, blank=True ) film_link_pwd = models.CharField( verbose_name=_('Password for the link above (optional)'), max_length=1000, blank=True ) attend = models.IntegerField( verbose_name=_('I intend to visit final part of festival'), choices=YESNOMAYBE, default=0) backlink = models.IntegerField( verbose_name=_(u'The source of information about ' u'Cinema Perpetuum Mobile'), <|code_end|> with the help of current file imports: from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cpm_generic.constants import COUNTRIES from submissions.constants import (YESNO, YESNOMAYBE, LANGUAGES, SECTIONS, BACKLINKS) and context from other files: # Path: submissions/constants.py # YESNO = ( # (1, _('Yes')), # (2, _('No')), # ) # # YESNOMAYBE = ( # (0, _('Maybe')), # (1, _('Yes')), # (2, _('No')), # ) # # LANGUAGES = sorted( # ( # (lang.alpha2, _(lang.name)) # for lang in pycountry.languages # if hasattr(lang, 'alpha2') # ), # key=lambda x: x[1] # ) # # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) # # BACKLINKS = ( # (1, _('festival website')), # (2, _('Facebook')), # (3, _('Twitter')), # (4, _('vk.com')), # (5, _('email')), # (6, _('internet search')), # (7, _('friends')), # (8, _('festivals database')), # (9, _('I participated in CPM\'2012')), # (10, _('place of study')), # (11, _('work')), # (12, _('other')), # ) , which may contain function names, class names, or code. Output only the next line.
choices=BACKLINKS
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals DATA_DIR = os.path.join(os.path.dirname(__file__), '0016') def _get_data(): with open(os.path.join(DATA_DIR, 'films.json')) as data_file: return json.load(data_file) def add_films_2017(apps, schema_editor): Film = apps.get_model('cpm_data.Film') <|code_end|> , predict the next line using imports from the current file: import json import os from django.core.files import File from django.db import migrations from cpm_generic.migration_utils import get_image_model and context including class names, function names, and sometimes code from other files: # Path: cpm_generic/migration_utils.py # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image . Output only the next line.
Image = get_image_model(apps)
Given the following code snippet before the placeholder: <|code_start|> FieldPanel('name_be'), FieldPanel('name_ru'), ImageChooserPanel('photo'), FieldPanel('country'), FieldPanel('info_en'), FieldPanel('info_be'), FieldPanel('info_ru'), ] class SeasonRelatedJuryMember(Orderable): season = ParentalKey('Season', related_name='related_jury_members') jury_member = models.ForeignKey( 'cpm_data.JuryMember', null=True, blank=True, related_name='+' ) category_en = models.CharField(max_length=250, blank=True, default='') category_be = models.CharField(max_length=250, blank=True, default='') category_ru = models.CharField(max_length=250, blank=True, default='') category = TranslatedField('category_en', 'category_be', 'category_ru') name = property(lambda self: self.jury_member.name) info = property(lambda self: self.jury_member.info) photo = property(lambda self: self.jury_member.photo) country = property(lambda self: self.jury_member.country) panels = [ <|code_end|> , predict the next line using imports from the current file: from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailcore.models import Orderable # TODO: is this good? from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsearch import index from modeladminutils.edit_handlers import AdminModelChooserPanel from modeladminutils.models import SearchableManager from cpm_generic.constants import COUNTRIES from cpm_generic.models import TranslatedField and context including class names, function names, and sometimes code from other files: # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) # # Path: modeladminutils/models.py # class BaseSearchableManager(models.Manager): # def get_queryset(self): # # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) . Output only the next line.
AdminModelChooserPanel('jury_member'),
Predict the next line after this snippet: <|code_start|> duration_en = models.CharField(max_length=100, default='', blank=True) duration_be = models.CharField(max_length=100, default='', blank=True) duration_ru = models.CharField(max_length=100, default='', blank=True) duration = TranslatedField('duration_en', 'duration_be', 'duration_ru') genre_en = models.CharField(max_length=1000, default='', blank=True) genre_be = models.CharField(max_length=1000, default='', blank=True) genre_ru = models.CharField(max_length=1000, default='', blank=True) genre = TranslatedField('genre_en', 'genre_be', 'genre_ru') synopsis_short_en = RichTextField(default='', blank=True) synopsis_short_be = RichTextField(default='', blank=True) synopsis_short_ru = RichTextField(default='', blank=True) synopsis_short = TranslatedField('synopsis_short_en', 'synopsis_short_be', 'synopsis_short_ru') synopsis_en = RichTextField(default='', blank=True) synopsis_be = RichTextField(default='', blank=True) synopsis_ru = RichTextField(default='', blank=True) synopsis = TranslatedField('synopsis_en', 'synopsis_be', 'synopsis_ru') frame = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) <|code_end|> using the current file's imports: from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailcore.models import Orderable # TODO: is this good? from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsearch import index from modeladminutils.edit_handlers import AdminModelChooserPanel from modeladminutils.models import SearchableManager from cpm_generic.constants import COUNTRIES from cpm_generic.models import TranslatedField and any relevant context from other files: # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) # # Path: modeladminutils/models.py # class BaseSearchableManager(models.Manager): # def get_queryset(self): # # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) . Output only the next line.
objects = SearchableManager()
Here is a snippet: <|code_start|>from __future__ import unicode_literals class Film(index.Indexed, ClusterableModel): """Model representing accepted film Submissions contain raw data that need to be preprocessed/translated before publishing. This model contains all the data about an accepted submission that will be published. """ submission = models.ForeignKey( 'submissions.Submission', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) title_en = models.CharField(max_length=1000, default='', blank=True) title_be = models.CharField(max_length=1000, default='', blank=True) title_ru = models.CharField(max_length=1000, default='', blank=True) <|code_end|> . Write the next line using the current file imports: from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailcore.models import Orderable # TODO: is this good? from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsearch import index from modeladminutils.edit_handlers import AdminModelChooserPanel from modeladminutils.models import SearchableManager from cpm_generic.constants import COUNTRIES from cpm_generic.models import TranslatedField and context from other files: # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) # # Path: modeladminutils/models.py # class BaseSearchableManager(models.Manager): # def get_queryset(self): # # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) , which may include functions, classes, or code. Output only the next line.
title = TranslatedField('title_en', 'title_be', 'title_ru')
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-08-27 22:21 from __future__ import unicode_literals DATA_DIR = os.path.join(os.path.dirname(__file__), '0008') def _get_data(season_name): with open(os.path.join(DATA_DIR, '%s.json' % season_name)) as data_file: return json.load(data_file) def _get_image_path(filename): return os.path.join(DATA_DIR, 'images', filename) def _get_season(apps, season_name): Season = apps.get_model('cpm_data.Season') return Season.objects.get(name_en=season_name) def add_partners(apps, schema_editor, season_name): Partner = apps.get_model('cpm_data.Partner') SeasonRelatedPartner = apps.get_model('cpm_data.SeasonRelatedPartner') <|code_end|> . Use current file imports: (from functools import partial from django.core.files import File from django.db import migrations from cpm_generic.migration_utils import get_image_model import json import os) and context including class names, function names, or small code snippets from other files: # Path: cpm_generic/migration_utils.py # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image . Output only the next line.
Image = get_image_model(apps)
Given the following code snippet before the placeholder: <|code_start|> ) def get_country_display(self): return self.film.get_country_display() title = property(lambda self: self.film.title) director = property(lambda self: self.film.director) country = property(lambda self: self.film.country) city = property(lambda self: self.film.city) year = property(lambda self: self.film.year) duration = property(lambda self: self.film.duration) genre = property(lambda self: self.film.genre) synopsis_short = property(lambda self: self.film.synopsis_short) synopsis = property(lambda self: self.film.synopsis) frame = property(lambda self: self.film.frame) panels = [ AdminModelChooserPanel('film'), ] class FilmProgram(Page): # TODO: add season # TODO: need remove section as required property section = models.IntegerField(choices=SECTIONS) name_en = models.CharField(max_length=1000) name_be = models.CharField(max_length=1000) name_ru = models.CharField(max_length=1000) <|code_end|> , predict the next line using imports from the current file: from collections import defaultdict from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailcore.models import Orderable, Page from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailsearch import index from cpm_generic.models import TranslatedField from modeladminutils.edit_handlers import AdminModelChooserPanel from modeladminutils.models import SearchableManager from submissions.constants import SECTIONS and context including class names, function names, and sometimes code from other files: # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) # # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) # # Path: modeladminutils/models.py # class BaseSearchableManager(models.Manager): # def get_queryset(self): # # Path: submissions/constants.py # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) . Output only the next line.
name = TranslatedField('name_en', 'name_be', 'name_ru')
Next line prediction: <|code_start|> class FilmProgramRelatedFilm(Orderable): page = ParentalKey('FilmProgram', related_name='related_films') film = models.ForeignKey( 'cpm_data.Film', null=True, blank=True, related_name='+' ) def get_country_display(self): return self.film.get_country_display() title = property(lambda self: self.film.title) director = property(lambda self: self.film.director) country = property(lambda self: self.film.country) city = property(lambda self: self.film.city) year = property(lambda self: self.film.year) duration = property(lambda self: self.film.duration) genre = property(lambda self: self.film.genre) synopsis_short = property(lambda self: self.film.synopsis_short) synopsis = property(lambda self: self.film.synopsis) frame = property(lambda self: self.film.frame) panels = [ <|code_end|> . Use current file imports: (from collections import defaultdict from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailcore.models import Orderable, Page from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailsearch import index from cpm_generic.models import TranslatedField from modeladminutils.edit_handlers import AdminModelChooserPanel from modeladminutils.models import SearchableManager from submissions.constants import SECTIONS) and context including class names, function names, or small code snippets from other files: # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) # # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) # # Path: modeladminutils/models.py # class BaseSearchableManager(models.Manager): # def get_queryset(self): # # Path: submissions/constants.py # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) . Output only the next line.
AdminModelChooserPanel('film'),
Based on the snippet: <|code_start|> description_en = RichTextField(default='') description_be = RichTextField(default='') description_ru = RichTextField(default='') description = TranslatedField('description_en', 'description_be', 'description_ru') content_panels = Page.content_panels + [ FieldPanel('section'), FieldPanel('name_en'), FieldPanel('name_be'), FieldPanel('name_ru'), FieldPanel('description_en'), FieldPanel('description_be'), FieldPanel('description_ru'), InlinePanel('related_films', label="Films"), ] class Venue(index.Indexed, ClusterableModel): name_en = models.CharField(max_length=1000) name_be = models.CharField(max_length=1000) name_ru = models.CharField(max_length=1000) name = TranslatedField('name_en', 'name_be', 'name_ru') address_en = models.CharField(max_length=1000) address_be = models.CharField(max_length=1000) address_ru = models.CharField(max_length=1000) address = TranslatedField('address_en', 'address_be', 'address_ru') <|code_end|> , predict the immediate next line with the help of imports: from collections import defaultdict from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailcore.models import Orderable, Page from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailsearch import index from cpm_generic.models import TranslatedField from modeladminutils.edit_handlers import AdminModelChooserPanel from modeladminutils.models import SearchableManager from submissions.constants import SECTIONS and context (classes, functions, sometimes code) from other files: # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) # # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) # # Path: modeladminutils/models.py # class BaseSearchableManager(models.Manager): # def get_queryset(self): # # Path: submissions/constants.py # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) . Output only the next line.
objects = SearchableManager()
Given the following code snippet before the placeholder: <|code_start|> film = models.ForeignKey( 'cpm_data.Film', null=True, blank=True, related_name='+' ) def get_country_display(self): return self.film.get_country_display() title = property(lambda self: self.film.title) director = property(lambda self: self.film.director) country = property(lambda self: self.film.country) city = property(lambda self: self.film.city) year = property(lambda self: self.film.year) duration = property(lambda self: self.film.duration) genre = property(lambda self: self.film.genre) synopsis_short = property(lambda self: self.film.synopsis_short) synopsis = property(lambda self: self.film.synopsis) frame = property(lambda self: self.film.frame) panels = [ AdminModelChooserPanel('film'), ] class FilmProgram(Page): # TODO: add season # TODO: need remove section as required property <|code_end|> , predict the next line using imports from the current file: from collections import defaultdict from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailcore.models import Orderable, Page from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailsearch import index from cpm_generic.models import TranslatedField from modeladminutils.edit_handlers import AdminModelChooserPanel from modeladminutils.models import SearchableManager from submissions.constants import SECTIONS and context including class names, function names, and sometimes code from other files: # Path: cpm_generic/models.py # class TranslatedField(object): # def __init__(self, en_field, be_field, ru_field): # self.en_field = en_field # self.be_field = be_field # self.ru_field = ru_field # # def __get__(self, instance, owner): # fields = { # 'en': self.en_field, # 'be': self.be_field, # 'ru': self.ru_field, # } # field = fields.get(translation.get_language(), self.en_field) # return getattr(instance, field) # # Path: modeladminutils/edit_handlers.py # class AdminModelChooserPanel(object): # def __init__(self, field_name): # self.field_name = field_name # # def bind_to_model(self, model): # return type( # str('_AdminModelChooserPanel'), # (BaseAdminModelChooserPanel,), # { # 'model': model, # 'field_name': self.field_name, # } # ) # # Path: modeladminutils/models.py # class BaseSearchableManager(models.Manager): # def get_queryset(self): # # Path: submissions/constants.py # SECTIONS = ( # (1, _('Fiction')), # (2, _('Animation')), # (3, _('Documentary')), # (4, _('Experimental')), # ) . Output only the next line.
section = models.IntegerField(choices=SECTIONS)
Continue the code snippet: <|code_start|> 'description_ru': u'Спіс чальцоў журы CPM на зсе часы', } def _get_jurymember_kw(item): return { 'title': item['title'], 'slug': slugify(item['title']), 'name_en': item['name_en'], 'name_be': item['name_be'], 'name_ru': item['name_ru'], 'info_en': item['info_en'], 'info_be': item['info_be'], 'info_ru': item['info_ru'], 'country': item['country'], } def add_jury_member_pages(apps, schema_editor): HomePage = apps.get_model('home.HomePage') Image = get_image_model(apps) Collection = apps.get_model('wagtailcore.Collection') IndexPage = apps.get_model('cpm_generic.IndexPage') JuryMemberPage = apps.get_model("results.JuryMemberPage") index_page_ct = get_content_type(apps, 'cpm_generic', 'indexpage') jury_member_page_ct = get_content_type(apps, 'results', 'jurymemberpage') collection_id = Collection.objects.filter(depth=1)[0] homepage = HomePage.objects.get(slug='home') <|code_end|> . Use current file imports: import json import os from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, remove_subpage, get_content_type, get_image_model) and context (classes, functions, or code) from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image . Output only the next line.
juryindex_page = add_subpage(
Based on the snippet: <|code_start|> photo.save() add_subpage( parent=juryindex_page, model=JuryMemberPage, photo=photo, content_type=jury_member_page_ct, **_get_jurymember_kw(item) ) def remove_jury_member_pages(apps, schema_editor): HomePage = apps.get_model('home.HomePage') Image = get_image_model(apps) Collection = apps.get_model('wagtailcore.Collection') IndexPage = apps.get_model('cpm_generic.IndexPage') JuryMemberPage = apps.get_model("results.JuryMemberPage") index_page_ct = get_content_type(apps, 'cpm_generic', 'indexpage') jury_member_page_ct = get_content_type(apps, 'results', 'jurymemberpage') collection_id = Collection.objects.filter(depth=1)[0] homepage = HomePage.objects.get(slug='home') juryindex_page = IndexPage.objects.get(slug=_get_juryindex_kw()['slug']) for item in _get_data(): photo = Image.objects.get(title=item['title'], collection=collection_id) photo.delete() <|code_end|> , predict the immediate next line with the help of imports: import json import os from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, remove_subpage, get_content_type, get_image_model) and context (classes, functions, sometimes code) from other files: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image . Output only the next line.
remove_subpage(
Given snippet: <|code_start|> 'caption_en': u'Jury', 'caption_be': u'Журы', 'caption_ru': u'Жюри', 'description_en': u'List of CPM jury members for all times', 'description_be': u'Список членов жюри CPM на все времена', 'description_ru': u'Спіс чальцоў журы CPM на зсе часы', } def _get_jurymember_kw(item): return { 'title': item['title'], 'slug': slugify(item['title']), 'name_en': item['name_en'], 'name_be': item['name_be'], 'name_ru': item['name_ru'], 'info_en': item['info_en'], 'info_be': item['info_be'], 'info_ru': item['info_ru'], 'country': item['country'], } def add_jury_member_pages(apps, schema_editor): HomePage = apps.get_model('home.HomePage') Image = get_image_model(apps) Collection = apps.get_model('wagtailcore.Collection') IndexPage = apps.get_model('cpm_generic.IndexPage') JuryMemberPage = apps.get_model("results.JuryMemberPage") <|code_end|> , continue by predicting the next line. Consider current file imports: import json import os from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, remove_subpage, get_content_type, get_image_model) and context: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image which might include code, classes, or functions. Output only the next line.
index_page_ct = get_content_type(apps, 'cpm_generic', 'indexpage')
Using the snippet: <|code_start|> def _get_juryindex_kw(): return { 'title': u'Jury', 'slug': 'jury', 'caption_en': u'Jury', 'caption_be': u'Журы', 'caption_ru': u'Жюри', 'description_en': u'List of CPM jury members for all times', 'description_be': u'Список членов жюри CPM на все времена', 'description_ru': u'Спіс чальцоў журы CPM на зсе часы', } def _get_jurymember_kw(item): return { 'title': item['title'], 'slug': slugify(item['title']), 'name_en': item['name_en'], 'name_be': item['name_be'], 'name_ru': item['name_ru'], 'info_en': item['info_en'], 'info_be': item['info_be'], 'info_ru': item['info_ru'], 'country': item['country'], } def add_jury_member_pages(apps, schema_editor): HomePage = apps.get_model('home.HomePage') <|code_end|> , determine the next line of code. You have imports: import json import os from django.core.files import File from django.db import migrations from django.utils.text import slugify from cpm_generic.migration_utils import (add_subpage, remove_subpage, get_content_type, get_image_model) and context (class names, function names, or code) available: # Path: cpm_generic/migration_utils.py # def add_subpage(parent, model, *args, **kwargs): # step = 4 # alphabet = MP_Node.alphabet # numconv = NumConv(len(alphabet), alphabet) # # children_qs = Page.objects.filter(depth=parent.depth + 1, # path__startswith=parent.path) # sibling = children_qs.order_by('-path').first() # sibling_num = numconv.str2int(sibling.path[-step:]) if sibling else 0 # next_key = numconv.int2str(sibling_num + 1) # path = '%s%s%s' % (parent.path, # alphabet[0] * (step - len(next_key)), # next_key) # # parent.numchild += 1 # kwargs.setdefault('depth', parent.depth + 1) # kwargs.setdefault('path', path) # kwargs.setdefault('numchild', 0) # kwargs.setdefault('url_path', '%s%s/' % (parent.url_path, kwargs['slug'])) # # child = model(*args, **kwargs) # # child.save() # parent.save() # # return child # # def remove_subpage(parent, model, **kwargs): # parent.numchild -= 1 # # model.objects.filter(**kwargs).delete() # parent.save() # # def get_content_type(apps, app_label, model): # ContentType = apps.get_model('contenttypes.ContentType') # content_type, _ = ContentType.objects.get_or_create( # model=model, # app_label=app_label # ) # return content_type # # def get_image_model(apps): # """ Return Image model that works in migrations. # # Models created by Django migration subsystem contain fields, # but dont' contain methods of the original models. # # The hack with adding method get_upload_to lets us save images in # migrations, e.g.: # >>> from django.core.files import File # >>> Image = get_image_model() # >>> photo = Image(title='example title') # >>> with open(path) as f: # ... photo.file.save(name='name.png', content=File(f)) # # Args: # apps (django.db.migrations.state.StateApps): Apps registry. # # Returns: # type: Image model. # """ # from wagtail.wagtailimages.models import Image as LatestImage # # Image = apps.get_model('wagtailimages.Image') # Image.get_upload_to = LatestImage.get_upload_to.im_func # # return Image . Output only the next line.
Image = get_image_model(apps)
Continue the code snippet: <|code_start|> # strategy 2 return (abs((pt[0]+360)%360 - lon_1) < 180) and \ (segment[0][1] <= pt[1] <= segment[1][1]) else: # strategy 1 return isbetween_circular(pt[0], lon_1, lon_2) def intersection_spherical(segment1, segment2): """ compute the intersection between two great circle segments on a sphere Parameters ---------- segment1, segment2 : tuple of tuples Tuples of the form ((x1, y1), (x2, y2)) describing line segements """ gc1 = eulerpole(*segment1) gc2 = eulerpole(*segment2) n = cross(gc1, gc2) lon, lat = cart2sph(*n) lon_antipodal = (lon+360)%360-180 pt = (lon, lat) pt_antipodal = (lon_antipodal, -lat) if (check_in_segment_range(pt, segment1) and check_in_segment_range(pt, segment2)): return pt elif (check_in_segment_range(pt_antipodal, segment1) and check_in_segment_range(pt_antipodal, segment2)): return pt_antipodal else: <|code_end|> . Use current file imports: import numpy as np import warnings from math import sqrt, sin, cos, tan, asin, acos, atan, atan2, atanh, pi from .errors import NoIntersection and context (classes, functions, or code) from other files: # Path: karta/errors.py # class NoIntersection(Exception): # """ Indicates that no intersection exists between segments """ # def __init__(self, message=''): # self.message = message . Output only the next line.
raise NoIntersection()
Based on the snippet: <|code_start|> def coordinate_transformer(crs1, crs2): if crs1 == crs2: def transformer(x, y): return x, y else: def transformer(x, y): return crs1.transform(crs2, x, y) return transformer class CoordinateGenerator(object): """ Class that generates coordinates from grid indices in a specified coordinate system. """ <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from ..crs import CartesianCRS and context (classes, functions, sometimes code) from other files: # Path: karta/crs.py # class CartesianCRS(CRS): # """ Cartesian (flat-earth) reference systems with (x, y) coordinates """ # name = "Cartesian" # # def __init__(self): # self.ref_proj4 = "" # self.ref_wkt = "" # return # # @staticmethod # def project(x, y, inverse=False): # # Projection on a cartesian coordinate system is the identity # return x, y # # @staticmethod # def forward(x, y, az, dist, radians=False): # """ Forward geodetic problem from a point """ # if not radians: # az = np.array(az) / 180 * pi # # x2 = x + dist * np.sin(az) # y2 = y + dist * np.cos(az) # baz = geodesy.unroll_rad(az + pi) # # if not radians: # baz = np.array(baz) * 180 / pi # return x2, y2, baz # # @staticmethod # def inverse(x1, y1, x2, y2, radians=False): # """ Inverse geodetic problem to find the geodesic between points """ # dist = geodesy.plane_distance(x1, y1, x2, y2) # az = geodesy.plane_azimuth(x1, y1, x2, y2) # baz = geodesy.unroll_rad(az + pi) # # if not radians: # az = az * 180 / pi # baz = baz * 180 / pi # return az, baz, dist # # @staticmethod # def transform(*args): # raise NotImplementedError("Cartesian CRS cannot be accurately transformed") . Output only the next line.
def __init__(self, transform, size, transform_crs=CartesianCRS, output_crs=CartesianCRS):
Next line prediction: <|code_start|> # c = cmp(list[indx], key) # if c < 0: # return list[indx] # else: return list[indx - 1] if indx > 0 else None def higher(list, key, cmp=cmp): if not list: return None indx = cmp_bisect(list, key, cmp) if indx >= len(list): return None c = cmp(list[indx], key) if c <= 0: return list[indx + 1] if indx < len(list) - 1 else None else: return list[indx] def equal(list, key, cmp=cmp): if not list: return None indx = cmp_bisect(list, key, cmp) if indx >= len(list): return None return list[indx] if cmp(list[indx], key) == 0 else None def pkg_range_query(list, pkg_name, op1="", v1="", op2="", v2=""): # empty version means last version if op1 == "==" or not op1: if v1: <|code_end|> . Use current file imports: (from ethronsoft.gcspypi.utilities.version import complete_version from ethronsoft.gcspypi.exceptions import InvalidParameter from ethronsoft.gcspypi.package.package import Package from ethronsoft.gcspypi.package.package import Package import functools) and context including class names, function names, or small code snippets from other files: # Path: ethronsoft/gcspypi/utilities/version.py # def complete_version(v): # """adds missing '0' to a version that has less than 3 components # # Arguments: # v {str} -- The version to update # # Returns: # str -- The modified version # """ # # tokens = [x for x in v.split(".") if x.strip()] # if len(tokens) > 3: # raise InvalidParameter("Invalid Version") # for i in range(3 - len(tokens)): # tokens.append("0") # return ".".join(tokens) # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass . Output only the next line.
x = equal(list, Package(pkg_name, complete_version(v1)), pkg_comp_name_version)
Next line prediction: <|code_start|> def pkg_range_query(list, pkg_name, op1="", v1="", op2="", v2=""): # empty version means last version if op1 == "==" or not op1: if v1: x = equal(list, Package(pkg_name, complete_version(v1)), pkg_comp_name_version) else: x = lower(list, Package(pkg_name + 'x01', ""), pkg_comp_name) elif op1 == "<": if v1: x = lower(list, Package(pkg_name, complete_version(v1)), pkg_comp_name_version) else: x = lower(list, Package(pkg_name + 'x01', ""), pkg_comp_name) x = lower(list, x, pkg_comp_name) elif op1 == ">": if v1: x = higher(list, Package(pkg_name, complete_version(v1)), pkg_comp_name_version) else: x = None elif op1 == "<=": if v1: x = floor(list, Package(pkg_name, complete_version(v1)), pkg_comp_name_version) else: x = lower(list, Package(pkg_name + 'x01', ""), pkg_comp_name) #lower than last elif op1 == ">=": if v1: x = ceiling(list, Package(pkg_name, complete_version(v1)), pkg_comp_name_version) else: x = lower(list, Package(pkg_name + 'x01', ""), pkg_comp_name) else: <|code_end|> . Use current file imports: (from ethronsoft.gcspypi.utilities.version import complete_version from ethronsoft.gcspypi.exceptions import InvalidParameter from ethronsoft.gcspypi.package.package import Package from ethronsoft.gcspypi.package.package import Package import functools) and context including class names, function names, or small code snippets from other files: # Path: ethronsoft/gcspypi/utilities/version.py # def complete_version(v): # """adds missing '0' to a version that has less than 3 components # # Arguments: # v {str} -- The version to update # # Returns: # str -- The modified version # """ # # tokens = [x for x in v.split(".") if x.strip()] # if len(tokens) > 3: # raise InvalidParameter("Invalid Version") # for i in range(3 - len(tokens)): # tokens.append("0") # return ".".join(tokens) # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass . Output only the next line.
raise InvalidParameter("Invalid operator" + op1)
Given snippet: <|code_start|> def _make_metadata(content, content_type): return ObjectMetadata(content_type, hashlib.md5(content).hexdigest(), datetime.datetime.now()) class MockRepository(object): def __init__(self): self.name = "mock_repo" self._repository = { } def upload_content(self, object_name, content, content_type="text/plain"): self._repository[object_name] = { "content": content, "metadata": _make_metadata(content.encode("utf-8"), content_type) } def upload_file(self,object_name, file_obj): cnt = file_obj.read() self._repository[object_name] = { "content": cnt, "metadata": _make_metadata(cnt, "application/octet-stream") } def download_content(self, object_name): if not self.exists(object_name): <|code_end|> , continue by predicting the next line. Consider current file imports: from ethronsoft.gcspypi.exceptions import RepositoryError, NotFound from ethronsoft.gcspypi.repository.object_metadata import ObjectMetadata import hashlib import datetime and context: # Path: ethronsoft/gcspypi/exceptions/repository_errors.py # class RepositoryError(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class NotFound(Exception): # pass # # Path: ethronsoft/gcspypi/repository/object_metadata.py # class ObjectMetadata(object): # """ObjectMetadata represents the metadata associated with a repository Object # """ # # def __init__(self, mime, md5_hash, time_created): # """ObjectMetadata constructor # # Arguments: # mime {str} -- MIME type of object # md5_hash {str} -- Hash representing the object. Can be used to determine content equality # time_created {datetime} -- Timestamp for the object creation # """ # # self.mime = mime # self.md5 = md5_hash # self.time_created = time_created which might include code, classes, or functions. Output only the next line.
raise NotFound()
Continue the code snippet: <|code_start|># if self.major > o.major: # return False # elif self.major < o.major: # return True # else: # major equal # if self.minor > o.minor: # return False # elif self.minor < o.minor: # return True # else: # minor equal # if self.patch > o.patch: # return False # elif self.patch < o.patch: # return True # else: # patch equal # return False # def __cmp__(self, o): # if self < o: # return -1 # elif self > o: # return 1 # else: # return 0 class Package(object): def __init__(self, name, version="", requirements=set([]), type=""): self.name = name.replace("_", "-") <|code_end|> . Use current file imports: from ethronsoft.gcspypi.utilities.version import complete_version from ethronsoft.gcspypi.exceptions import InvalidState, InvalidParameter import os and context (classes, functions, or code) from other files: # Path: ethronsoft/gcspypi/utilities/version.py # def complete_version(v): # """adds missing '0' to a version that has less than 3 components # # Arguments: # v {str} -- The version to update # # Returns: # str -- The modified version # """ # # tokens = [x for x in v.split(".") if x.strip()] # if len(tokens) > 3: # raise InvalidParameter("Invalid Version") # for i in range(3 - len(tokens)): # tokens.append("0") # return ".".join(tokens) # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass . Output only the next line.
self.version = complete_version(version) if version else None
Here is a snippet: <|code_start|># return -1 # elif self > o: # return 1 # else: # return 0 class Package(object): def __init__(self, name, version="", requirements=set([]), type=""): self.name = name.replace("_", "-") self.version = complete_version(version) if version else None self.requirements = set([]) self.type = type for r in requirements: self.requirements.add(r.replace("_","-")) @staticmethod def repo_name(pkg, filename): if not pkg.version: raise InvalidState("cannot formulate package repository-name for a package without version") return "{name}/{version}/{filename}".format( name=pkg.name, version=pkg.version, filename=os.path.split(filename)[1] ) @staticmethod def from_text(text): if ">" in text or "<" in text: <|code_end|> . Write the next line using the current file imports: from ethronsoft.gcspypi.utilities.version import complete_version from ethronsoft.gcspypi.exceptions import InvalidState, InvalidParameter import os and context from other files: # Path: ethronsoft/gcspypi/utilities/version.py # def complete_version(v): # """adds missing '0' to a version that has less than 3 components # # Arguments: # v {str} -- The version to update # # Returns: # str -- The modified version # """ # # tokens = [x for x in v.split(".") if x.strip()] # if len(tokens) > 3: # raise InvalidParameter("Invalid Version") # for i in range(3 - len(tokens)): # tokens.append("0") # return ".".join(tokens) # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass , which may include functions, classes, or code. Output only the next line.
raise InvalidParameter("Cannot create a package with non deterministic version")
Predict the next line after this snippet: <|code_start|># else: # minor equal # if self.patch > o.patch: # return False # elif self.patch < o.patch: # return True # else: # patch equal # return False # def __cmp__(self, o): # if self < o: # return -1 # elif self > o: # return 1 # else: # return 0 class Package(object): def __init__(self, name, version="", requirements=set([]), type=""): self.name = name.replace("_", "-") self.version = complete_version(version) if version else None self.requirements = set([]) self.type = type for r in requirements: self.requirements.add(r.replace("_","-")) @staticmethod def repo_name(pkg, filename): if not pkg.version: <|code_end|> using the current file's imports: from ethronsoft.gcspypi.utilities.version import complete_version from ethronsoft.gcspypi.exceptions import InvalidState, InvalidParameter import os and any relevant context from other files: # Path: ethronsoft/gcspypi/utilities/version.py # def complete_version(v): # """adds missing '0' to a version that has less than 3 components # # Arguments: # v {str} -- The version to update # # Returns: # str -- The modified version # """ # # tokens = [x for x in v.split(".") if x.strip()] # if len(tokens) > 3: # raise InvalidParameter("Invalid Version") # for i in range(3 - len(tokens)): # tokens.append("0") # return ".".join(tokens) # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass . Output only the next line.
raise InvalidState("cannot formulate package repository-name for a package without version")
Based on the snippet: <|code_start|> class PackageBuilder(object): def __init__(self, raw_package): try: cwd = os.getcwd() tdir = tempfile.mkdtemp() os.chdir(tdir) <|code_end|> , predict the immediate next line with the help of imports: from ethronsoft.gcspypi.utilities.queries import get_package_type from ethronsoft.gcspypi.package.package import Package from ethronsoft.gcspypi.exceptions import InvalidState import json import os import shutil import tarfile import tempfile import zipfile and context (classes, functions, sometimes code) from other files: # Path: ethronsoft/gcspypi/utilities/queries.py # def get_package_type(path): # if ".zip" in path: # return "SOURCE" # elif ".tar" in path: # return "SOURCE" # elif ".whl" in path: # return "WHEEL" # else: # raise InvalidParameter("Unrecognized file extension. expected {.zip|.tar*|.whl}") # # Path: ethronsoft/gcspypi/package/package.py # class Package(object): # # def __init__(self, name, version="", requirements=set([]), type=""): # self.name = name.replace("_", "-") # self.version = complete_version(version) if version else None # self.requirements = set([]) # self.type = type # for r in requirements: # self.requirements.add(r.replace("_","-")) # # @staticmethod # def repo_name(pkg, filename): # if not pkg.version: # raise InvalidState("cannot formulate package repository-name for a package without version") # return "{name}/{version}/{filename}".format( # name=pkg.name, # version=pkg.version, # filename=os.path.split(filename)[1] # ) # # @staticmethod # def from_text(text): # if ">" in text or "<" in text: # raise InvalidParameter("Cannot create a package with non deterministic version") # if "==" in text: # name, version = text.split("==") # return Package(name.strip(), version.strip()) # else: # return Package(text) # # def __str__(self): # return self.full_name # # def __repr__(self): # pragma: no cover # return "<Package {}>".format(str(self)) # # def __eq__(self, o): # if not o: return False # return (self.name, self.version, self.type) == (o.name, o.version, o.type) # # def __ne__(self, o): # return not self.__eq__(o) # # def __hash__(self): # return hash((self.name, str(self.version), self.type)) # # @property # def full_name(self): # return self.name + ":" + self.version if self.version else self.name # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass . Output only the next line.
typ = get_package_type(raw_package)
Predict the next line after this snippet: <|code_start|> def __init__(self): self.metadata = {} def __call__(self, target): m = json.loads(target.read()) self.metadata["name"] = m["name"] self.metadata["version"] = m["version"] self.metadata["requirements"] = set([]) for reqs in m["run_requires"]: self.metadata["requirements"].update(reqs["requires"]) cmd = InfoCmd() self.__seek_and_apply(zpfile, "metadata.json", cmd) if not cmd.metadata: raise InvalidState("Could not find metadata.json") return cmd.metadata def __read_requirements(self, zpfile): class RequiresCmd(object): def __init__(self): self.requires = [] def __call__(self, target): self.requires = [x for x in target.read().splitlines()] cmd = RequiresCmd() self.__seek_and_apply(zpfile, "requires", cmd) return cmd.requires def build(self): <|code_end|> using the current file's imports: from ethronsoft.gcspypi.utilities.queries import get_package_type from ethronsoft.gcspypi.package.package import Package from ethronsoft.gcspypi.exceptions import InvalidState import json import os import shutil import tarfile import tempfile import zipfile and any relevant context from other files: # Path: ethronsoft/gcspypi/utilities/queries.py # def get_package_type(path): # if ".zip" in path: # return "SOURCE" # elif ".tar" in path: # return "SOURCE" # elif ".whl" in path: # return "WHEEL" # else: # raise InvalidParameter("Unrecognized file extension. expected {.zip|.tar*|.whl}") # # Path: ethronsoft/gcspypi/package/package.py # class Package(object): # # def __init__(self, name, version="", requirements=set([]), type=""): # self.name = name.replace("_", "-") # self.version = complete_version(version) if version else None # self.requirements = set([]) # self.type = type # for r in requirements: # self.requirements.add(r.replace("_","-")) # # @staticmethod # def repo_name(pkg, filename): # if not pkg.version: # raise InvalidState("cannot formulate package repository-name for a package without version") # return "{name}/{version}/{filename}".format( # name=pkg.name, # version=pkg.version, # filename=os.path.split(filename)[1] # ) # # @staticmethod # def from_text(text): # if ">" in text or "<" in text: # raise InvalidParameter("Cannot create a package with non deterministic version") # if "==" in text: # name, version = text.split("==") # return Package(name.strip(), version.strip()) # else: # return Package(text) # # def __str__(self): # return self.full_name # # def __repr__(self): # pragma: no cover # return "<Package {}>".format(str(self)) # # def __eq__(self, o): # if not o: return False # return (self.name, self.version, self.type) == (o.name, o.version, o.type) # # def __ne__(self, o): # return not self.__eq__(o) # # def __hash__(self): # return hash((self.name, str(self.version), self.type)) # # @property # def full_name(self): # return self.name + ":" + self.version if self.version else self.name # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass . Output only the next line.
return Package(self.__info["name"],
Here is a snippet: <|code_start|> self.__info["type"] = typ finally: os.chdir(cwd) shutil.rmtree(tdir) def __seek_and_apply(self, zpfile, target, command): zpfile.extractall(".") for r, _, f in os.walk("."): for x in f: if target in x: with open(os.path.join(r, x), "r") as target_file: command(target_file) return def __extract_source(self, zpfile): class InfoCmd(object): def __init__(self): self.metadata = {} def __call__(self, target): m = {} for line in target.readlines(): k, v = line.split(":") m[k.upper().strip()] = v.strip() self.metadata["name"] = m["name".upper()] self.metadata["version"] = m["version".upper()] cmd = InfoCmd() self.__seek_and_apply(zpfile, "PKG-INFO", cmd) if not cmd.metadata: <|code_end|> . Write the next line using the current file imports: from ethronsoft.gcspypi.utilities.queries import get_package_type from ethronsoft.gcspypi.package.package import Package from ethronsoft.gcspypi.exceptions import InvalidState import json import os import shutil import tarfile import tempfile import zipfile and context from other files: # Path: ethronsoft/gcspypi/utilities/queries.py # def get_package_type(path): # if ".zip" in path: # return "SOURCE" # elif ".tar" in path: # return "SOURCE" # elif ".whl" in path: # return "WHEEL" # else: # raise InvalidParameter("Unrecognized file extension. expected {.zip|.tar*|.whl}") # # Path: ethronsoft/gcspypi/package/package.py # class Package(object): # # def __init__(self, name, version="", requirements=set([]), type=""): # self.name = name.replace("_", "-") # self.version = complete_version(version) if version else None # self.requirements = set([]) # self.type = type # for r in requirements: # self.requirements.add(r.replace("_","-")) # # @staticmethod # def repo_name(pkg, filename): # if not pkg.version: # raise InvalidState("cannot formulate package repository-name for a package without version") # return "{name}/{version}/{filename}".format( # name=pkg.name, # version=pkg.version, # filename=os.path.split(filename)[1] # ) # # @staticmethod # def from_text(text): # if ">" in text or "<" in text: # raise InvalidParameter("Cannot create a package with non deterministic version") # if "==" in text: # name, version = text.split("==") # return Package(name.strip(), version.strip()) # else: # return Package(text) # # def __str__(self): # return self.full_name # # def __repr__(self): # pragma: no cover # return "<Package {}>".format(str(self)) # # def __eq__(self, o): # if not o: return False # return (self.name, self.version, self.type) == (o.name, o.version, o.type) # # def __ne__(self, o): # return not self.__eq__(o) # # def __hash__(self): # return hash((self.name, str(self.version), self.type)) # # @property # def full_name(self): # return self.name + ":" + self.version if self.version else self.name # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass , which may include functions, classes, or code. Output only the next line.
raise InvalidState("Could not find PKG-INFO")
Given the following code snippet before the placeholder: <|code_start|> def test_src_tar(): pkg_path = resource_filename(__name__, "data/test_package-1.0.0.tar.gz") pkg = PackageBuilder(pkg_path).build() assert pkg.name == "test-package" assert pkg.version == "1.0.0" assert pkg.requirements == set(["test-dep1", "test-dep2"]) assert pkg.type == "SOURCE" def test_src_wrong(): pkg_path = resource_filename(__name__, "data/WRONG-test_package-1.0.0.zip") <|code_end|> , predict the next line using imports from the current file: from ethronsoft.gcspypi.package.package_builder import PackageBuilder from ethronsoft.gcspypi.exceptions import InvalidState from pkg_resources import resource_filename import os import sys import pytest and context including class names, function names, and sometimes code from other files: # Path: ethronsoft/gcspypi/package/package_builder.py # class PackageBuilder(object): # # def __init__(self, raw_package): # try: # cwd = os.getcwd() # tdir = tempfile.mkdtemp() # os.chdir(tdir) # typ = get_package_type(raw_package) # if typ == "SOURCE": # if ".zip" in raw_package: # with zipfile.ZipFile(raw_package, "r") as f: # self.__info = self.__extract_source(f) # elif ".tar" in raw_package: # with tarfile.open(raw_package, "r") as f: # self.__info = self.__extract_source(f) # elif typ == "WHEEL": # with zipfile.ZipFile(raw_package, "r") as f: # self.__info = self.__extract_wheel(f) # # self.__info["type"] = typ # finally: # os.chdir(cwd) # shutil.rmtree(tdir) # # def __seek_and_apply(self, zpfile, target, command): # zpfile.extractall(".") # for r, _, f in os.walk("."): # for x in f: # if target in x: # with open(os.path.join(r, x), "r") as target_file: # command(target_file) # return # # def __extract_source(self, zpfile): # class InfoCmd(object): # def __init__(self): # self.metadata = {} # # def __call__(self, target): # m = {} # for line in target.readlines(): # k, v = line.split(":") # m[k.upper().strip()] = v.strip() # self.metadata["name"] = m["name".upper()] # self.metadata["version"] = m["version".upper()] # # cmd = InfoCmd() # self.__seek_and_apply(zpfile, "PKG-INFO", cmd) # if not cmd.metadata: # raise InvalidState("Could not find PKG-INFO") # return {"name": cmd.metadata["name"], # "version": cmd.metadata["version"], # "requirements": self.__read_requirements(zpfile)} # # def __extract_wheel(self, zpfile): # class InfoCmd(object): # def __init__(self): # self.metadata = {} # # def __call__(self, target): # m = json.loads(target.read()) # self.metadata["name"] = m["name"] # self.metadata["version"] = m["version"] # self.metadata["requirements"] = set([]) # for reqs in m["run_requires"]: # self.metadata["requirements"].update(reqs["requires"]) # # cmd = InfoCmd() # self.__seek_and_apply(zpfile, "metadata.json", cmd) # if not cmd.metadata: # raise InvalidState("Could not find metadata.json") # return cmd.metadata # # def __read_requirements(self, zpfile): # class RequiresCmd(object): # def __init__(self): # self.requires = [] # # def __call__(self, target): # self.requires = [x for x in target.read().splitlines()] # # cmd = RequiresCmd() # self.__seek_and_apply(zpfile, "requires", cmd) # return cmd.requires # # def build(self): # return Package(self.__info["name"], # self.__info["version"], # set(self.__info["requirements"]), # self.__info["type"]) # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass . Output only the next line.
with pytest.raises(InvalidState):
Given the code snippet: <|code_start|> class GCloudRepository(object): def __init__(self, bucket): """GCloudRepository constructor Arguments: bucket {str} -- The Google Cloud Storage Bucket to act as our repository Raises: cpm.exceptions.RepositoryError -- If the was an error connecting to the repository or to the bucket. Most often due to invalid credentials """ try: #NOTE: It is convenient to authenticate with application-default credentials. #Moving away from it is as simple as setting an environment variable and getting access #to server credentials but this is cumbersome for the front-end use of cpm. #Keeping this for as long as google doesn't deprecate feature warnings.filterwarnings("ignore", "Your application has authenticated using end user credentials") self.bucket = storage.Client().bucket(bucket) if not self.bucket.exists(): <|code_end|> , generate the next line using the imports in this file: from google.cloud import storage from ethronsoft.gcspypi.exceptions import RepositoryError, NotFound from .object_metadata import ObjectMetadata import six import sys import warnings and context (functions, classes, or occasionally code) from other files: # Path: ethronsoft/gcspypi/exceptions/repository_errors.py # class RepositoryError(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class NotFound(Exception): # pass # # Path: ethronsoft/gcspypi/repository/object_metadata.py # class ObjectMetadata(object): # """ObjectMetadata represents the metadata associated with a repository Object # """ # # def __init__(self, mime, md5_hash, time_created): # """ObjectMetadata constructor # # Arguments: # mime {str} -- MIME type of object # md5_hash {str} -- Hash representing the object. Can be used to determine content equality # time_created {datetime} -- Timestamp for the object creation # """ # # self.mime = mime # self.md5 = md5_hash # self.time_created = time_created . Output only the next line.
raise RepositoryError("{} does not exist".format(bucket))
Given snippet: <|code_start|> Arguments: object_name {str} -- Name of object to download Raises: cpm.exceptions.NotFound -- If the object_name does not exist Returns: str -- Content as string """ blob = self.bucket.blob(object_name) try: return blob.download_as_string() except Exception as e: six.raise_from(RepositoryError(str(e)), e) def download_file(self, object_name, file_obj): """Download the object_name to a file `file_name` Arguments: object_name {str} -- Name of object to download file_obj {file} -- File object to write into Raises: cpm.exceptions.NotFound -- If the object_name does not exist """ blob = self.bucket.blob(object_name) try: return blob.download_to_file(file_obj) except Exception as e: <|code_end|> , continue by predicting the next line. Consider current file imports: from google.cloud import storage from ethronsoft.gcspypi.exceptions import RepositoryError, NotFound from .object_metadata import ObjectMetadata import six import sys import warnings and context: # Path: ethronsoft/gcspypi/exceptions/repository_errors.py # class RepositoryError(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class NotFound(Exception): # pass # # Path: ethronsoft/gcspypi/repository/object_metadata.py # class ObjectMetadata(object): # """ObjectMetadata represents the metadata associated with a repository Object # """ # # def __init__(self, mime, md5_hash, time_created): # """ObjectMetadata constructor # # Arguments: # mime {str} -- MIME type of object # md5_hash {str} -- Hash representing the object. Can be used to determine content equality # time_created {datetime} -- Timestamp for the object creation # """ # # self.mime = mime # self.md5 = md5_hash # self.time_created = time_created which might include code, classes, or functions. Output only the next line.
six.raise_from(NotFound(str(e)), e)
Predict the next line after this snippet: <|code_start|> pass def exists(self, object_name): """Checks whether object `object_name` exists Arguments: object_name {str} -- Name of object to check for existence Returns: bool -- flag for existence """ return self.bucket.blob(object_name).exists() def metadata(self, object_name): """[summary] Arguments: object_name Name of object to get metadata for Raises: cpm.exceptions.NotFound -- If the object does not exist Returns: cpm.repository.ObjectMetadata -- The object Metadata """ if not self.bucket.blob(object_name).exists(): raise NotFound("{0} does not exist".format(object_name)) blob = self.bucket.get_blob(object_name) <|code_end|> using the current file's imports: from google.cloud import storage from ethronsoft.gcspypi.exceptions import RepositoryError, NotFound from .object_metadata import ObjectMetadata import six import sys import warnings and any relevant context from other files: # Path: ethronsoft/gcspypi/exceptions/repository_errors.py # class RepositoryError(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class NotFound(Exception): # pass # # Path: ethronsoft/gcspypi/repository/object_metadata.py # class ObjectMetadata(object): # """ObjectMetadata represents the metadata associated with a repository Object # """ # # def __init__(self, mime, md5_hash, time_created): # """ObjectMetadata constructor # # Arguments: # mime {str} -- MIME type of object # md5_hash {str} -- Hash representing the object. Can be used to determine content equality # time_created {datetime} -- Timestamp for the object creation # """ # # self.mime = mime # self.md5 = md5_hash # self.time_created = time_created . Output only the next line.
return ObjectMetadata(blob.content_type, blob.md5_hash, blob.time_created)
Based on the snippet: <|code_start|> def init_repository(console, repository): if not repository: raise InvalidParameter("missing repository. Use --repository flag or write entry repository=<repo_name> in ~/.gcspypirc") try: console.info("using repository {}".format(repository)) pending = console.badge("connecting...", "warning", overwrite=True) <|code_end|> , predict the immediate next line with the help of imports: from ethronsoft.gcspypi.repository.gcloud_remote import GCloudRepository from ethronsoft.gcspypi.exceptions import InvalidParameter import os and context (classes, functions, sometimes code) from other files: # Path: ethronsoft/gcspypi/repository/gcloud_remote.py # class GCloudRepository(object): # # def __init__(self, bucket): # """GCloudRepository constructor # # Arguments: # bucket {str} -- The Google Cloud Storage Bucket to act as our repository # # Raises: # cpm.exceptions.RepositoryError -- If the was an error connecting to the repository # or to the bucket. Most often due to invalid credentials # """ # try: # #NOTE: It is convenient to authenticate with application-default credentials. # #Moving away from it is as simple as setting an environment variable and getting access # #to server credentials but this is cumbersome for the front-end use of cpm. # #Keeping this for as long as google doesn't deprecate feature # warnings.filterwarnings("ignore", "Your application has authenticated using end user credentials") # self.bucket = storage.Client().bucket(bucket) # if not self.bucket.exists(): # raise RepositoryError("{} does not exist".format(bucket)) # self.name = bucket # except Exception as e: # six.raise_from(RepositoryError, e) # # def upload_content(self, object_name, content, content_type="text/plain"): # """Uploads the content to the repository, targetting object `object` # # Arguments: # content {str} -- The Content as a string # object_name {str} -- The name of the object to create/replace in the repository # content_type {str} -- The MIME Type for the Content (defaults to 'text/plain') # # Raises: # cpm.exceptions.RepositoryError -- If the was an error during the upload # """ # try: # blob = self.bucket.blob(object_name) # blob.upload_from_string(content, content_type) # except Exception as e: # six.raise_from(RepositoryError(str(e)), e) # # def upload_file(self, object_name, file_obj): # """Uploads the file to the repository, targetting object `object` # # Arguments: # file_obj {file} -- The file to upload # object_name {str} -- The name of the object to create/replace in the repository # # Raises: # cpm.exceptions.RepositoryError -- If the was an error during the upload # """ # try: # blob = self.bucket.blob(object_name) # blob.upload_from_file(file_obj) # except Exception as e: # six.raise_from(RepositoryError(str(e)), e) # # def download_content(self, object_name): # """Download the content of object_name as a string # # Arguments: # object_name {str} -- Name of object to download # # Raises: # cpm.exceptions.NotFound -- If the object_name does not exist # # Returns: # str -- Content as string # """ # blob = self.bucket.blob(object_name) # try: # return blob.download_as_string() # except Exception as e: # six.raise_from(RepositoryError(str(e)), e) # # def download_file(self, object_name, file_obj): # """Download the object_name to a file `file_name` # # Arguments: # object_name {str} -- Name of object to download # file_obj {file} -- File object to write into # # Raises: # cpm.exceptions.NotFound -- If the object_name does not exist # """ # blob = self.bucket.blob(object_name) # try: # return blob.download_to_file(file_obj) # except Exception as e: # six.raise_from(NotFound(str(e)), e) # # def delete(self, object_name): # """Attempt to delete object `object_name` # # Arguments: # object_name {str} -- Name of object to delete # # Returns: # bool -- flag for succesful deletion # """ # # blob = self.bucket.blob(object_name) # try: # return blob.delete() is not None # except Exception: # pass # # def exists(self, object_name): # """Checks whether object `object_name` exists # # Arguments: # object_name {str} -- Name of object to check for existence # # Returns: # bool -- flag for existence # """ # # return self.bucket.blob(object_name).exists() # # def metadata(self, object_name): # """[summary] # # Arguments: # object_name Name of object to get metadata for # # Raises: # cpm.exceptions.NotFound -- If the object does not exist # # Returns: # cpm.repository.ObjectMetadata -- The object Metadata # """ # # if not self.bucket.blob(object_name).exists(): # raise NotFound("{0} does not exist".format(object_name)) # blob = self.bucket.get_blob(object_name) # return ObjectMetadata(blob.content_type, blob.md5_hash, blob.time_created) # # def list(self, prefix=""): # """Lists all the objects in the bucket with prefix `prefix` # # Keyword Arguments: # prefix {str} -- The prefix to use for the search (default: {""}) # # Returns: # list -- List of objects matching the search # """ # # return [o.name for o in self.bucket.list_blobs(prefix=prefix)] # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass . Output only the next line.
repo = GCloudRepository(repository)
Here is a snippet: <|code_start|> def test_repo_name(): p = Package("some", "1.0.0") assert p.full_name == "some:1.0.0" wrong = Package("some", "") assert Package.repo_name(p, "/some/filename.txt") == "some/1.0.0/filename.txt" with pytest.raises(InvalidState): Package.repo_name(wrong, "/some/filename.txt") def test_equality(): p1 = Package("some", "1.0.0", type="A") p2 = Package("some", "1.0.0", type="A") p3 = Package("some", "1.0.0", type="B") p4 = Package("some", "", type="A") p5 = Package("other", "1.0.0", type="A") p6 = Package("other", "1.0.0", type="B") assert p1.full_name == str(p1) assert p1 == p2 assert hash(p1) == hash(p2) assert p1 != p3 assert hash(p1) != hash(p3) assert p1 != p4 assert p2 != p5 assert p5 != p6 def test_from_text(): <|code_end|> . Write the next line using the current file imports: from ethronsoft.gcspypi.package.package import Package from ethronsoft.gcspypi.exceptions import InvalidParameter, InvalidState import pytest and context from other files: # Path: ethronsoft/gcspypi/package/package.py # class Package(object): # # def __init__(self, name, version="", requirements=set([]), type=""): # self.name = name.replace("_", "-") # self.version = complete_version(version) if version else None # self.requirements = set([]) # self.type = type # for r in requirements: # self.requirements.add(r.replace("_","-")) # # @staticmethod # def repo_name(pkg, filename): # if not pkg.version: # raise InvalidState("cannot formulate package repository-name for a package without version") # return "{name}/{version}/{filename}".format( # name=pkg.name, # version=pkg.version, # filename=os.path.split(filename)[1] # ) # # @staticmethod # def from_text(text): # if ">" in text or "<" in text: # raise InvalidParameter("Cannot create a package with non deterministic version") # if "==" in text: # name, version = text.split("==") # return Package(name.strip(), version.strip()) # else: # return Package(text) # # def __str__(self): # return self.full_name # # def __repr__(self): # pragma: no cover # return "<Package {}>".format(str(self)) # # def __eq__(self, o): # if not o: return False # return (self.name, self.version, self.type) == (o.name, o.version, o.type) # # def __ne__(self, o): # return not self.__eq__(o) # # def __hash__(self): # return hash((self.name, str(self.version), self.type)) # # @property # def full_name(self): # return self.name + ":" + self.version if self.version else self.name # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass , which may include functions, classes, or code. Output only the next line.
with pytest.raises(InvalidParameter):
Given the code snippet: <|code_start|> def test_repo_name(): p = Package("some", "1.0.0") assert p.full_name == "some:1.0.0" wrong = Package("some", "") assert Package.repo_name(p, "/some/filename.txt") == "some/1.0.0/filename.txt" <|code_end|> , generate the next line using the imports in this file: from ethronsoft.gcspypi.package.package import Package from ethronsoft.gcspypi.exceptions import InvalidParameter, InvalidState import pytest and context (functions, classes, or occasionally code) from other files: # Path: ethronsoft/gcspypi/package/package.py # class Package(object): # # def __init__(self, name, version="", requirements=set([]), type=""): # self.name = name.replace("_", "-") # self.version = complete_version(version) if version else None # self.requirements = set([]) # self.type = type # for r in requirements: # self.requirements.add(r.replace("_","-")) # # @staticmethod # def repo_name(pkg, filename): # if not pkg.version: # raise InvalidState("cannot formulate package repository-name for a package without version") # return "{name}/{version}/{filename}".format( # name=pkg.name, # version=pkg.version, # filename=os.path.split(filename)[1] # ) # # @staticmethod # def from_text(text): # if ">" in text or "<" in text: # raise InvalidParameter("Cannot create a package with non deterministic version") # if "==" in text: # name, version = text.split("==") # return Package(name.strip(), version.strip()) # else: # return Package(text) # # def __str__(self): # return self.full_name # # def __repr__(self): # pragma: no cover # return "<Package {}>".format(str(self)) # # def __eq__(self, o): # if not o: return False # return (self.name, self.version, self.type) == (o.name, o.version, o.type) # # def __ne__(self, o): # return not self.__eq__(o) # # def __hash__(self): # return hash((self.name, str(self.version), self.type)) # # @property # def full_name(self): # return self.name + ":" + self.version if self.version else self.name # # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass # # Path: ethronsoft/gcspypi/exceptions/state_errors.py # class InvalidState(Exception): # pass . Output only the next line.
with pytest.raises(InvalidState):
Predict the next line after this snippet: <|code_start|>from __future__ import division def complete_version(v): """adds missing '0' to a version that has less than 3 components Arguments: v {str} -- The version to update Returns: str -- The modified version """ tokens = [x for x in v.split(".") if x.strip()] if len(tokens) > 3: <|code_end|> using the current file's imports: from ethronsoft.gcspypi.exceptions import InvalidParameter import functools and any relevant context from other files: # Path: ethronsoft/gcspypi/exceptions/boundary_errors.py # class InvalidParameter(Exception): # pass . Output only the next line.
raise InvalidParameter("Invalid Version")
Next line prediction: <|code_start|>""" Tests against manifest for CodeMirror configurations """ def test_raw_config_empty(manifesto): """Empty config""" manifesto.autoregister() config = manifesto.get_codemirror_parameters('empty') assert config == {} def test_get_config_success(settings, manifesto): """Use get_config on non registered name""" manifesto.autoregister() assert manifesto.get_config('empty') == { 'modes': [], 'addons': [], 'themes': [], 'css_bundle_name': 'dcm-empty_css', 'js_bundle_name': 'dcm-empty_js', } def test_get_config_error(settings, manifesto): """Use get_config on non registered name""" manifesto.autoregister() <|code_end|> . Use current file imports: (import pytest from djangocodemirror.exceptions import NotRegisteredError) and context including class names, function names, or small code snippets from other files: # Path: djangocodemirror/exceptions.py # class NotRegisteredError(KeyError): # pass . Output only the next line.
with pytest.raises(NotRegisteredError):
Continue the code snippet: <|code_start|>""" Sandbox URL Configuration """ urlpatterns = [ # Dummy homepage to list demo views url(r'^$', TemplateView.as_view( template_name="homepage.html" ), name='home'), # Sample with codemirror in the raw way url(r'^raw/$', TemplateView.as_view( template_name="raw.html" ), name='raw'), # Basic form sample <|code_end|> . Use current file imports: from django.conf import settings from django.conf.urls import url from django.views.generic.base import TemplateView from sandbox.views import BasicSampleFormView, ModesSampleFormView and context (classes, functions, or code) from other files: # Path: sandbox/views.py # class BasicSampleFormView(FormView): # template_name = 'form.html' # form_class = SampleForm # # def get_success_url(self): # return reverse('home') # # class ModesSampleFormView(BasicSampleFormView): # template_name = 'modes.html' # # def get_context_data(self, **kwargs): # context = super(ModesSampleFormView, self).get_context_data(**kwargs) # context.update({ # 'codemirror_mode': self.codemirror_mode, # }) # return context # # def get_initial(self): # """ # Try to find a demo source for given mode if any, if finded use it to # fill the demo textarea. # """ # initial = {} # # if self.kwargs.get('mode', None): # filename = "{}.txt".format(self.kwargs['mode']) # filepath = os.path.join(settings.BASE_DIR, 'demo_datas', filename) # if os.path.exists(filepath): # with io.open(filepath, 'r', encoding='utf-8') as fp: # initial['foo'] = fp.read() # # return initial # # def get(self, request, *args, **kwargs): # self.codemirror_mode = kwargs.get('mode', None) # return super(ModesSampleFormView, self).get(request, *args, **kwargs) # # def post(self, request, *args, **kwargs): # self.codemirror_mode = kwargs.get('mode', None) # return super(ModesSampleFormView, self).post(request, *args, **kwargs) . Output only the next line.
url(r'^form/$', BasicSampleFormView.as_view(
Next line prediction: <|code_start|>""" Sandbox URL Configuration """ urlpatterns = [ # Dummy homepage to list demo views url(r'^$', TemplateView.as_view( template_name="homepage.html" ), name='home'), # Sample with codemirror in the raw way url(r'^raw/$', TemplateView.as_view( template_name="raw.html" ), name='raw'), # Basic form sample url(r'^form/$', BasicSampleFormView.as_view( template_name="form.html" ), name='form'), # Mode index list <|code_end|> . Use current file imports: (from django.conf import settings from django.conf.urls import url from django.views.generic.base import TemplateView from sandbox.views import BasicSampleFormView, ModesSampleFormView) and context including class names, function names, or small code snippets from other files: # Path: sandbox/views.py # class BasicSampleFormView(FormView): # template_name = 'form.html' # form_class = SampleForm # # def get_success_url(self): # return reverse('home') # # class ModesSampleFormView(BasicSampleFormView): # template_name = 'modes.html' # # def get_context_data(self, **kwargs): # context = super(ModesSampleFormView, self).get_context_data(**kwargs) # context.update({ # 'codemirror_mode': self.codemirror_mode, # }) # return context # # def get_initial(self): # """ # Try to find a demo source for given mode if any, if finded use it to # fill the demo textarea. # """ # initial = {} # # if self.kwargs.get('mode', None): # filename = "{}.txt".format(self.kwargs['mode']) # filepath = os.path.join(settings.BASE_DIR, 'demo_datas', filename) # if os.path.exists(filepath): # with io.open(filepath, 'r', encoding='utf-8') as fp: # initial['foo'] = fp.read() # # return initial # # def get(self, request, *args, **kwargs): # self.codemirror_mode = kwargs.get('mode', None) # return super(ModesSampleFormView, self).get(request, *args, **kwargs) # # def post(self, request, *args, **kwargs): # self.codemirror_mode = kwargs.get('mode', None) # return super(ModesSampleFormView, self).post(request, *args, **kwargs) . Output only the next line.
url(r'^modes/$', ModesSampleFormView.as_view(
Given snippet: <|code_start|>""" Tests against manifest for CSS assets """ def test_css_empty_registry(settings, manifesto): """Empty registry""" assert manifesto.css() == settings.CODEMIRROR_BASE_CSS def test_css_registred_empty(settings, manifesto): """An empty registred config""" manifesto.autoregister() assert manifesto.css('empty') == settings.CODEMIRROR_BASE_CSS def test_resolve_theme_success(settings, manifesto): """Resolve a theme name""" result = manifesto.resolve_theme('ambiance') attempt = settings.CODEMIRROR_THEMES['ambiance'] assert result == attempt def test_resolve_theme_error(settings, manifesto): """Try to resolve a theme name that does not exist""" <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from django.conf import settings from djangocodemirror.exceptions import UnknowThemeError and context: # Path: djangocodemirror/exceptions.py # class UnknowThemeError(KeyError): # pass which might include code, classes, or functions. Output only the next line.
with pytest.raises(UnknowThemeError):
Next line prediction: <|code_start|> """ if name not in settings.CODEMIRROR_THEMES: msg = ("Given theme name '{}' does not exists in " "'settings.CODEMIRROR_THEMES'.") raise UnknowThemeError(msg.format(name)) return settings.CODEMIRROR_THEMES.get(name) def get_configs(self, name=None): """ Returns registred configurations. * If ``name`` argument is not given, default behavior is to return every config from all registred config; * If ``name`` argument is given, just return its config and nothing else; Keyword Arguments: name (string): Specific configuration name to return. Raises: NotRegisteredError: If given config name does not exist in registry. Returns: dict: Configurations. """ if name: if name not in self.registry: msg = "Given config name '{}' is not registered." <|code_end|> . Use current file imports: (import copy from django.conf import settings from .exceptions import (NotRegisteredError, UnknowConfigError, UnknowModeError, UnknowThemeError)) and context including class names, function names, or small code snippets from other files: # Path: djangocodemirror/exceptions.py # class NotRegisteredError(KeyError): # pass # # class UnknowConfigError(KeyError): # pass # # class UnknowModeError(KeyError): # pass # # class UnknowThemeError(KeyError): # pass . Output only the next line.
raise NotRegisteredError(msg.format(name))
Predict the next line for this snippet: <|code_start|> default_internal_config = { 'modes': [], # Enabled modes 'addons': [], # Addons filepaths to load 'themes': [], # Themes filepaths to load } _internal_only = ['modes', 'addons', 'themes', 'css_bundle_name', 'js_bundle_name', 'extra_css'] def __init__(self): self.registry = {} def register(self, name): """ Register configuration for an editor instance. Arguments: name (string): Config name from available ones in ``settings.CODEMIRROR_SETTINGS``. Raises: UnknowConfigError: If given config name does not exist in ``settings.CODEMIRROR_SETTINGS``. Returns: dict: Registred config dict. """ if name not in settings.CODEMIRROR_SETTINGS: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_SETTINGS'.") <|code_end|> with the help of current file imports: import copy from django.conf import settings from .exceptions import (NotRegisteredError, UnknowConfigError, UnknowModeError, UnknowThemeError) and context from other files: # Path: djangocodemirror/exceptions.py # class NotRegisteredError(KeyError): # pass # # class UnknowConfigError(KeyError): # pass # # class UnknowModeError(KeyError): # pass # # class UnknowThemeError(KeyError): # pass , which may contain function names, class names, or code. Output only the next line.
raise UnknowConfigError(msg.format(name))
Here is a snippet: <|code_start|> params.append(self.register(name)) return params def autoregister(self): """ Register every available configuration from ``settings.CODEMIRROR_SETTINGS``. """ for name in settings.CODEMIRROR_SETTINGS: self.register(name) def resolve_mode(self, name): """ From given mode name, return mode file path from ``settings.CODEMIRROR_MODES`` map. Arguments: name (string): Mode name. Raises: KeyError: When given name does not exist in ``settings.CODEMIRROR_MODES``. Returns: string: Mode file path. """ if name not in settings.CODEMIRROR_MODES: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_MODES'.") <|code_end|> . Write the next line using the current file imports: import copy from django.conf import settings from .exceptions import (NotRegisteredError, UnknowConfigError, UnknowModeError, UnknowThemeError) and context from other files: # Path: djangocodemirror/exceptions.py # class NotRegisteredError(KeyError): # pass # # class UnknowConfigError(KeyError): # pass # # class UnknowModeError(KeyError): # pass # # class UnknowThemeError(KeyError): # pass , which may include functions, classes, or code. Output only the next line.
raise UnknowModeError(msg.format(name))
Predict the next line for this snippet: <|code_start|> ``settings.CODEMIRROR_MODES``. Returns: string: Mode file path. """ if name not in settings.CODEMIRROR_MODES: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_MODES'.") raise UnknowModeError(msg.format(name)) return settings.CODEMIRROR_MODES.get(name) def resolve_theme(self, name): """ From given theme name, return theme file path from ``settings.CODEMIRROR_THEMES`` map. Arguments: name (string): Theme name. Raises: KeyError: When given name does not exist in ``settings.CODEMIRROR_THEMES``. Returns: string: Theme file path. """ if name not in settings.CODEMIRROR_THEMES: msg = ("Given theme name '{}' does not exists in " "'settings.CODEMIRROR_THEMES'.") <|code_end|> with the help of current file imports: import copy from django.conf import settings from .exceptions import (NotRegisteredError, UnknowConfigError, UnknowModeError, UnknowThemeError) and context from other files: # Path: djangocodemirror/exceptions.py # class NotRegisteredError(KeyError): # pass # # class UnknowConfigError(KeyError): # pass # # class UnknowModeError(KeyError): # pass # # class UnknowThemeError(KeyError): # pass , which may contain function names, class names, or code. Output only the next line.
raise UnknowThemeError(msg.format(name))
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ Sample views """ class BasicSampleFormView(FormView): template_name = 'form.html' <|code_end|> , determine the next line of code. You have imports: import io, os from django.conf import settings from django.views.generic.edit import FormView from django.urls import reverse from sandbox.forms import SampleForm and context (class names, function names, or code) available: # Path: sandbox/forms.py # class SampleForm(forms.Form): # """ # Just a very basic form for tests # """ # foo = CodeMirrorField(label="Foo", # required=True, # config_name="basic", # initial='Hello World!') . Output only the next line.
form_class = SampleForm
Given the code snippet: <|code_start|> assert registred == [ { 'modes': [], 'addons': [], 'themes': [], 'css_bundle_name': 'dcm-empty_css', 'js_bundle_name': 'dcm-empty_js', }, { 'mode': 'rst', 'modes': [], 'addons': [], 'themes': [], 'css_bundle_name': 'dcm-basic_css', 'js_bundle_name': 'dcm-basic_js', }, ] def test_autoregister(manifesto): """Auto register every config from settings""" manifesto.autoregister() # Check only about some names, not all assert ('empty' in manifesto.registry) == True assert ('basic' in manifesto.registry) == True assert ('with-all' in manifesto.registry) == True def test_register_nonexistent(settings, manifesto): """Try to register a config name that does not exist""" <|code_end|> , generate the next line using the imports in this file: import pytest from django.conf import settings from djangocodemirror.exceptions import UnknowConfigError and context (functions, classes, or occasionally code) from other files: # Path: djangocodemirror/exceptions.py # class UnknowConfigError(KeyError): # pass . Output only the next line.
with pytest.raises(UnknowConfigError):
Here is a snippet: <|code_start|> # Since we dont have names for addons, name it here to avoid retyping them for # every test ADDON_DIALOG = 'CodeMirror/lib/util/dialog.js' ADDON_SEARCH = 'CodeMirror/lib/util/search.js' ADDON_SEARCHCURSOR = 'CodeMirror/lib/util/searchcursor.js' def test_js_empty_registry(settings, manifesto): """Empty registry""" assert manifesto.js() == settings.CODEMIRROR_BASE_JS def test_js_registred_empty(settings, manifesto): """An empty registred config""" manifesto.autoregister() assert manifesto.js('empty') == settings.CODEMIRROR_BASE_JS def test_resolve_mode_success(settings, manifesto): """Resolve a mode name""" assert manifesto.resolve_mode('python') == settings.CODEMIRROR_MODES['python'] def test_resolve_mode_error(settings, manifesto): """Try to resolve a mode name that does not exist""" <|code_end|> . Write the next line using the current file imports: import pytest import json from django.conf import settings as legacy_settings from djangocodemirror.exceptions import UnknowModeError and context from other files: # Path: djangocodemirror/exceptions.py # class UnknowModeError(KeyError): # pass , which may include functions, classes, or code. Output only the next line.
with pytest.raises(UnknowModeError):
Here is a snippet: <|code_start|> def test_widget_init_manifest(): """Check registered config""" widget = CodeMirrorWidget(config_name="empty") config = widget.init_manifest("empty") assert config.get_configs() == { 'empty': { 'modes': [], 'addons': [], 'themes': [], 'css_bundle_name': 'dcm-empty_css', 'js_bundle_name': 'dcm-empty_js', } } def test_widget_basic(): """Basic widget usage""" widget = CodeMirrorWidget(config_name="basic") rendered = widget.render("sample", "Hello World!") expected = ("""<textarea id="id_sample" name="sample" rows="10" cols="40">""" """Hello World!</textarea>""") <|code_end|> . Write the next line using the current file imports: import pytest from djangocodemirror.widgets import CodeMirrorWidget, CodeMirrorAdminWidget from tests.utils import assert_and_parse_html and context from other files: # Path: djangocodemirror/widgets.py # class CodeMirrorWidget(forms.Textarea): # """ # Widget to add a CodeMirror or DjangoCodeMirror instance on a textarea # Take the same arguments than ``forms.Textarea`` and accepts one # suplementary optionnal arguments : # # Arguments: # config_name (string): A Codemirror config name available in # ``settings.CODEMIRROR_SETTINGS``. Default is ``empty``. # embed_config (bool): If ``True`` will add Codemirror Javascript config # just below the input. Default is ``False``. # # Attributes: # config_name (string): For given config name. # template_name (string): Template path for widget rendering. # """ # codemirror_field_js = settings.CODEMIRROR_FIELD_INIT_JS # template_name = "djangocodemirror/widget.html" # # def __init__(self, *args, **kwargs): # self.config_name = kwargs.pop("config_name", "empty") # self.embed_config = kwargs.pop("embed_config", False) # # super(CodeMirrorWidget, self).__init__(*args, **kwargs) # # def init_manifest(self, name): # """ # Initialize a manifest instance # # Arguments: # name (string): Config name to register. # # Returns: # CodeMirrorManifest: A manifest instance where config (from # ``config_name`` attribute) is registred. # """ # manifesto = CodeMirrorManifest() # manifesto.register(name) # return manifesto # # def get_codemirror_field_js(self): # """ # Return CodeMirror HTML template from # ``CodeMirrorWidget.codemirror_field_js``. # # Returns: # string: HTML template string. # """ # return self.codemirror_field_js # # def codemirror_config(self): # """ # Shortcut to get Codemirror parameters. # # Returns: # dict: CodeMirror parameters. # """ # return self.editor_manifest.get_codemirror_parameters(self.config_name) # # def codemirror_script(self, inputid): # """ # Build CodeMirror HTML script tag which contains CodeMirror init. # # Arguments: # inputid (string): Input id. # # Returns: # string: HTML for field CodeMirror instance. # """ # varname = slugify("{}_codemirror".format(inputid)).replace("-", "_") # html = self.get_codemirror_field_js() # opts = self.codemirror_config() # # return html.format(varname=varname, inputid=inputid, # settings=json.dumps(opts, sort_keys=True)) # # def get_context(self, name, value, attrs): # context = super(CodeMirrorWidget, self).get_context(name, value, attrs) # # # Widget allways need an id to be able to set CodeMirror Javascript # # config # if 'id' not in context['widget']['attrs']: # context['widget']['attrs']['id'] = 'id_{}'.format(name) # # # Append HTML for CodeMirror Javascript config just below the textarea # if self.embed_config: # context['widget'].update({ # 'script': self.codemirror_script(context['widget']['attrs']['id']), # noqa: E501 # }) # # return context # # def render(self, name, value, attrs=None, renderer=None): # """ # Returns this Widget rendered as HTML, as a Unicode string. # """ # if not hasattr(self, "editor_manifest"): # self.editor_manifest = self.init_manifest(self.config_name) # # config = self.editor_manifest.get_config(self.config_name) # if config.get('embed_config'): # self.embed_config = True # # context = self.get_context(name, value, attrs) # # return self._render(self.template_name, context, renderer) # # @property # def media(self): # """ # Adds necessary files (Js/CSS) to the widget's medias. # # Returns: # django.forms.Media: Media object with all assets from registered # config. # """ # if not hasattr(self, "editor_manifest"): # self.editor_manifest = self.init_manifest(self.config_name) # # return forms.Media( # css={"all": self.editor_manifest.css()}, # js=self.editor_manifest.js() # ) # # class CodeMirrorAdminWidget(CodeMirrorWidget): # """ # CodeMirror widget suited for usage in models admins. # # Act like CodeMirrorWidget but allways embed Codemirror Javascript config. # """ # def __init__(self, *args, **kwargs): # kwargs['embed_config'] = True # super(CodeMirrorAdminWidget, self).__init__(*args, **kwargs) # # Path: tests/utils.py # def assert_and_parse_html(html): # """ # Shortand to use Django HTML parsing as object to use in assert # """ # dom = parse_html(html) # return dom , which may include functions, classes, or code. Output only the next line.
assert assert_and_parse_html(rendered) == assert_and_parse_html(expected)
Given snippet: <|code_start|>""" Tests against form fields """ def test_field_basic(): """Basic field usage""" field = CodeMirrorField(label="Foo", required=True, config_name="basic", initial='Hello World!') rendered = field.widget.render("foo", "bar") expected = ("""<textarea id="id_foo" name="foo" rows="10" cols="40">""" """bar</textarea>""") <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from djangocodemirror.fields import CodeMirrorField from tests.utils import assert_and_parse_html and context: # Path: djangocodemirror/fields.py # class CodeMirrorField(forms.CharField): # """ # A CharField that comes with CodeMirrorWidget. # # Arguments: # config_name (string): A Codemirror config name available in # ``settings.CODEMIRROR_SETTINGS``. Default is ``empty``. # """ # def __init__(self, *args, **kwargs): # self.config_name = kwargs.pop('config_name', 'empty') # # Add Codemirror widget to the field # kwargs.update({'widget': CodeMirrorWidget}) # # # Initialize widget with given config name if the field has been # # bounded. # widget = kwargs.get('widget', None) or self.widget # if isinstance(widget, type): # kwargs['widget'] = widget(config_name=self.config_name) # # super(CodeMirrorField, self).__init__(*args, **kwargs) # # Path: tests/utils.py # def assert_and_parse_html(html): # """ # Shortand to use Django HTML parsing as object to use in assert # """ # dom = parse_html(html) # return dom which might include code, classes, or functions. Output only the next line.
assert assert_and_parse_html(rendered) == assert_and_parse_html(expected)
Predict the next line after this snippet: <|code_start|> 'lineWrapping': False, 'modes': ['rst'], }, 'basic': { 'mode': 'rst', 'foo': 'bar', 'css_bundle_name': None, 'lineWrapping': False, 'modes': ['rst'], }, 'with-options': { 'mode': 'rst', 'foo': 'bar', 'css_bundle_name': None, 'lineWrapping': False, 'modes': ['rst'], }, 'with-all': { 'mode': 'rst', 'foo': 'bar', 'css_bundle_name': None, 'lineWrapping': False, 'modes': ['rst'], }, } ), ]) def test_config_helper(on, names, attempted): """Helper to update parameters from selected config and with filtered returned dict""" <|code_end|> using the current file's imports: import pytest from djangocodemirror.helper import codemirror_settings_update and any relevant context from other files: # Path: djangocodemirror/helper.py # def codemirror_settings_update(configs, parameters, on=None, names=None): # """ # Return a new dictionnary of configs updated with given parameters. # # You may use ``on`` and ``names`` arguments to select config or filter out # some configs from returned dict. # # Arguments: # configs (dict): Dictionnary of configurations to update. # parameters (dict): Dictionnary of parameters to apply on selected # configurations. # # Keyword Arguments: # on (list): List of configuration names to select for update. If empty, # all given configurations will be updated. # names (list): List of configuration names to keep. If not empty, only # those configurations will be in returned dict. Else every # configs from original dict will be present. # # Returns: # dict: Dict of configurations with updated parameters. # """ # # Deep copy of given config # output = copy.deepcopy(configs) # # # Optionnaly filtering config from given names # if names: # output = {k: output[k] for k in names} # # # Select every config if selectors is empty # if not on: # on = output.keys() # # for k in on: # output[k].update(parameters) # # return output . Output only the next line.
result = codemirror_settings_update(SAMPLE_DICT, SAMPLE_PARAMETERS, on=on,
Based on the snippet: <|code_start|> def shift(seq, n): n %= len(seq) return seq[n:] + seq[:n] <|code_end|> , predict the immediate next line with the help of imports: from time import sleep from IoTPy.ioboard.boards.uper import UPER1 from IoTPy.things.led_strip import LedStrip and context (classes, functions, sometimes code) from other files: # Path: IoTPy/things/led_strip.py # class LedStrip: # # def __init__(self, spi): # self.spi = spi # # self.set_color(0) # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # pass # # def set_colors(self, colors): # data = "\x00\x00\x00\x00" # # for color in colors: # r = color >> 19 & 0x1F # g = color >> 11 & 0x1F # b = color & 0x1F # tmp = 0x8000 | (b << 10) | (r << 5) | g # data += chr(tmp >> 8) + chr(tmp & 0xFF) # # for i in xrange((len(colors)+7)/8): # data += '\x00' # # self.spi.write(data) # # def set_color(self, color): # self.set_colors([color] * 50) . Output only the next line.
with UPER1() as board, board.spi("SPI0", clock=2.9e6) as spi, LedStrip(spi) as leds:
Continue the code snippet: <|code_start|>#from builtins import chr def _encode_int(intarg): if intarg < 64: return chr(intarg).encode('latin-1') packedint = pack('>I', intarg).lstrip(b'\x00') return chr(0xc0 | (len(packedint) - 1)).encode('latin-1') + packedint def _encode_bytes(byte_string): if len(byte_string) < 64: return chr(0x40 | len(byte_string)).encode('latin-1') + byte_string packedlen = pack('>I', len(byte_string)).lstrip(b'\x00') if len(packedlen) == 1: return b'\xc4' + packedlen + byte_string elif len(packedlen) == 2: return b'\xc5' + packedlen + byte_string else: <|code_end|> . Use current file imports: from IoTPy.errors import IoTPy_APIError from six import binary_type, integer_types from struct import pack, unpack and context (classes, functions, or code) from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass . Output only the next line.
raise IoTPy_APIError("UPER API: - too long string passed to UPER, encode_bytes can't handle it.")
Using the snippet: <|code_start|> class AM2321: """ AM2321 temperature and humidity sensor class. :param interface: I2C communication interface. :type interface: :class:`IoTPy.pyuper.i2c.I2C` :param sensor_address: AM2321 sensor I2C address. Optional, default 0x5C (92). :type sensor_address: int """ def __init__(self, interface, sensor_address= 0x5c): self.interface = interface self.address = sensor_address self.temperature = -1000.0 self.humidity = -1 def __enter__(self): return self def __exit__(self, ex_type, ex_value, traceback): pass def _read_raw(self, command, regaddr, regcount): self.interface.transaction(self.address, b'\0', 0) self.interface.transaction(self.address, command+regaddr+chr(regcount).encode('latin-1'), 0) sleep(0.002) buf, err = self.interface.transaction(self.address, b'', regcount + 4) if err: <|code_end|> , determine the next line of code. You have imports: from time import sleep from struct import unpack from IoTPy.errors import IoTPy_ThingError and context (class names, function names, or code) available: # Path: IoTPy/errors.py # class IoTPy_ThingError(Exception): # pass . Output only the next line.
raise IoTPy_ThingError("AM2321 reading error.")
Based on the snippet: <|code_start|> PWM_PORT_RUNNING = [{'channels': 0, 'period': 0}, {'channels': 0, 'period': 0}] class PWM(object): """ PWM (Pulse Width Modulation) pin module. :param board: IoBoard to which the pin belongs to. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param pin: PWM pin number. :type pin: int :param freq: PWM frequency in Hertz. :type freq: float :param polarity: Active (on) state signal level: 0 (LOW) or 1 (HIGH). Optional, default 1. :type polarity: int """ _PWM_PORT_FUNCTIONS = [[50,51,52],[60,61,62]] _PWM_PORT_MAX = [0xffff, 0xffffffff] def __init__(self, board, pin, freq=100, polarity=1): self.board = board <|code_end|> , predict the immediate next line with the help of imports: from IoTPy.pinmaps import CAP_PWM from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp and context (classes, functions, sometimes code) from other files: # Path: IoTPy/pinmaps.py # CAP_PWM = 0x4 # # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command . Output only the next line.
if self.board.pinout[pin].capabilities & CAP_PWM:
Given the code snippet: <|code_start|> PWM_PORT_RUNNING = [{'channels': 0, 'period': 0}, {'channels': 0, 'period': 0}] class PWM(object): """ PWM (Pulse Width Modulation) pin module. :param board: IoBoard to which the pin belongs to. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param pin: PWM pin number. :type pin: int :param freq: PWM frequency in Hertz. :type freq: float :param polarity: Active (on) state signal level: 0 (LOW) or 1 (HIGH). Optional, default 1. :type polarity: int """ _PWM_PORT_FUNCTIONS = [[50,51,52],[60,61,62]] _PWM_PORT_MAX = [0xffff, 0xffffffff] def __init__(self, board, pin, freq=100, polarity=1): self.board = board if self.board.pinout[pin].capabilities & CAP_PWM: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("UPER API: Pin No:%d is not a PWM pin.", pin) <|code_end|> , generate the next line using the imports in this file: from IoTPy.pinmaps import CAP_PWM from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp and context (functions, classes, or occasionally code) from other files: # Path: IoTPy/pinmaps.py # CAP_PWM = 0x4 # # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command . Output only the next line.
raise IoTPy_APIError("Trying to assign PWM function to non PWM pin.")
Given the following code snippet before the placeholder: <|code_start|> PWM_PORT_RUNNING = [{'channels': 0, 'period': 0}, {'channels': 0, 'period': 0}] class PWM(object): """ PWM (Pulse Width Modulation) pin module. :param board: IoBoard to which the pin belongs to. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param pin: PWM pin number. :type pin: int :param freq: PWM frequency in Hertz. :type freq: float :param polarity: Active (on) state signal level: 0 (LOW) or 1 (HIGH). Optional, default 1. :type polarity: int """ _PWM_PORT_FUNCTIONS = [[50,51,52],[60,61,62]] _PWM_PORT_MAX = [0xffff, 0xffffffff] def __init__(self, board, pin, freq=100, polarity=1): self.board = board if self.board.pinout[pin].capabilities & CAP_PWM: self.logical_pin = self.board.pinout[pin].pinID else: <|code_end|> , predict the next line using imports from the current file: from IoTPy.pinmaps import CAP_PWM from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp and context including class names, function names, and sometimes code from other files: # Path: IoTPy/pinmaps.py # CAP_PWM = 0x4 # # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command . Output only the next line.
errmsg("UPER API: Pin No:%d is not a PWM pin.", pin)
Based on the snippet: <|code_start|> :type freq: float :param polarity: Active (on) state signal level: 0 (LOW) or 1 (HIGH). Optional, default 1. :type polarity: int """ _PWM_PORT_FUNCTIONS = [[50,51,52],[60,61,62]] _PWM_PORT_MAX = [0xffff, 0xffffffff] def __init__(self, board, pin, freq=100, polarity=1): self.board = board if self.board.pinout[pin].capabilities & CAP_PWM: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("UPER API: Pin No:%d is not a PWM pin.", pin) raise IoTPy_APIError("Trying to assign PWM function to non PWM pin.") self.pwm_port = self.board.pinout[pin].extra[0] self.pwm_pin = self.board.pinout[pin].extra[1] self.primary = True self.pulse_time = 0 self.polarity = polarity PWM_PORT_RUNNING[self.pwm_port]['channels'] += 1 if PWM_PORT_RUNNING[self.pwm_port]['channels'] == 1: self.set_frequency(freq) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): PWM_PORT_RUNNING[self.pwm_port]['channels'] -= 1 self.primary = True <|code_end|> , predict the immediate next line with the help of imports: from IoTPy.pinmaps import CAP_PWM from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp and context (classes, functions, sometimes code) from other files: # Path: IoTPy/pinmaps.py # CAP_PWM = 0x4 # # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command . Output only the next line.
self.board.low_level_io(0, encode_sfp(1, [self.logical_pin])) # set pin primary function
Continue the code snippet: <|code_start|> :type pin: int :raise: IoTPy_APIError """ # digital pin directions INPUT = 0 """ INPUT direction constant""" OUTPUT = 1 """ OUTPUT direction constant""" # GPIO resistors HIGH_Z = NONE = 0 """ no-pull (high-z) resistor constant """ PULL_UP = 1 """ pull-up resistor constant """ PULL_DOWN = 2 """ pull-down resistor constant """ # digital pin events LOW = 0 HIGH = 1 CHANGE = 2 RISE = 3 FALL = 4 def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_GPIO: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("UPER API: Pin No:%d is not GPIO pin.", pin) <|code_end|> . Use current file imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_GPIO from IoTPy.sfp import encode_sfp, decode_sfp import struct and context (classes, functions, or code) from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_GPIO = 0x1 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
raise IoTPy_APIError("Trying to assign GPIO function to non GPIO pin.")
Next line prediction: <|code_start|> :param pin: GPIO pin number. :type pin: int :raise: IoTPy_APIError """ # digital pin directions INPUT = 0 """ INPUT direction constant""" OUTPUT = 1 """ OUTPUT direction constant""" # GPIO resistors HIGH_Z = NONE = 0 """ no-pull (high-z) resistor constant """ PULL_UP = 1 """ pull-up resistor constant """ PULL_DOWN = 2 """ pull-down resistor constant """ # digital pin events LOW = 0 HIGH = 1 CHANGE = 2 RISE = 3 FALL = 4 def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_GPIO: self.logical_pin = self.board.pinout[pin].pinID else: <|code_end|> . Use current file imports: (from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_GPIO from IoTPy.sfp import encode_sfp, decode_sfp import struct) and context including class names, function names, or small code snippets from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_GPIO = 0x1 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
errmsg("UPER API: Pin No:%d is not GPIO pin.", pin)
Predict the next line for this snippet: <|code_start|> :param board: IoBoard to which the pin belongs to. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param pin: GPIO pin number. :type pin: int :raise: IoTPy_APIError """ # digital pin directions INPUT = 0 """ INPUT direction constant""" OUTPUT = 1 """ OUTPUT direction constant""" # GPIO resistors HIGH_Z = NONE = 0 """ no-pull (high-z) resistor constant """ PULL_UP = 1 """ pull-up resistor constant """ PULL_DOWN = 2 """ pull-down resistor constant """ # digital pin events LOW = 0 HIGH = 1 CHANGE = 2 RISE = 3 FALL = 4 def __init__(self, board, pin): self.board = board <|code_end|> with the help of current file imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_GPIO from IoTPy.sfp import encode_sfp, decode_sfp import struct and context from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_GPIO = 0x1 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args , which may contain function names, class names, or code. Output only the next line.
if self.board.pinout[pin].capabilities & CAP_GPIO: