Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>
try:
except ImportError:
etree = None
class FixturesTestCase(test.TestCase):
fixtures = ['actors', 'streams', 'contacts', 'streamentries',
'inboxentries', 'subscriptions', 'oauthconsumers',
'invites', 'emails', 'ims', 'activations',
... | xmpp.XmppConnection = test_util.TestXmppConnection |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', SurveyListView.as_view(), name='likert_list'),
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import... | url(r'^add/', SurveyCreateView.as_view(), name="likert_add"), |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', SurveyListView.as_view(), name='likert_list'),
url(r'^add/', SurveyCreateView.as_view(), name="likert_add"),
url(r'^added/$', TemplateView.as_view(template_n... | url(r'^survey/(?P<pk>\w+)/$', SurveyDetailView.as_view(), |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class LikertFieldTestCase(SimpleTestCase):
def setUp(self):
pass
def test_instantiation(self):
<|code_end|>
using the current file's imports:
from django.db.models.fields impor... | item = LikertField() |
Predict the next line for this snippet: <|code_start|> item = LikertField(blank=False)
self.assertFalse(item.blank)
def test_get_prep_value_int(self):
item = LikertField()
for value in xrange(1, 50+1):
self.assertIsInstance(item.get_prep_value(value), int)
def test_g... | self.assertIsInstance(ff, forms.LikertFormField) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class LikertFormFieldTestCase(SimpleTestCase):
def test_instantiation(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.exceptions import ValidationError
from ... | ff = LikertFormField() |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class LikertFormFieldTestCase(SimpleTestCase):
def test_instantiation(self):
ff = LikertFormField()
self.assertIsInstance(ff, fields.Field)
def test_widget... | self.assertIsInstance(ff.widget, LikertTextField) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
register = template.Library()
# Font-awesome stars ver 3
star_set_3 = {
'star': "<i class='icon-star likert-star'></i>",
'unlit': "<i class='icon-star-empty likert-star'></i>",
'noanswer': "<i class='icon-b... | return mark_safe(render_stars(num, max_stars, star_set_3)) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class StarToolsTestCase(SimpleTestCase):
def setUp(self):
self.star_set = {
'star': 's',
'unlit': 'u',
'noanswer': 'n'
}
def test_render_stars(self):
max... | stars = render_stars(num, max_stars, self.star_set) |
Given the following code snippet before the placeholder: <|code_start|> "<i class='glyphicon glyphicon-star-empty likert-star'></i>")
stars = bs_stars3(num, max_stars)
self.assertEqual(stars, expected_stars)
def test_bs_stars3_render_noanswer(self):
num = None
expected_st... | stars = fa_stars3(num) |
Using the snippet: <|code_start|> self.assertEqual(stars, expected_stars)
def test_fa_stars3_render_parameters(self):
num = 1
max_stars = 7
expected_stars = (
"<i class='icon-star likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>"
"<i... | stars = fa_stars4(num) |
Next line prediction: <|code_start|> self.assertEqual(stars.count(self.star_set['star']), max_stars)
self.assertEqual(stars.count(self.star_set['unlit']), 0)
def test_render_string_numbers(self):
"""
String representations of integers are rendered in the usual manner
"""
... | stars = bs_stars2(num) |
Given the following code snippet before the placeholder: <|code_start|> "<i class='icon-star likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>")
stars = bs_stars2(num)
self.assertEqual(stars, expected_stars)
... | stars = bs_stars3(num) |
Given snippet: <|code_start|> expected_stars = (
"<i class='glyphicon glyphicon-star likert-star'></i>"
"<i class='glyphicon glyphicon-star-empty likert-star'></i>"
"<i class='glyphicon glyphicon-star-empty likert-star'></i>"
"<i class='glyphicon glyphicon-star-emp... | stars = bs_stars3_bsr(num) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class LikertTextFieldTestCase(SimpleTestCase):
def test_instantiation(self):
<|code_end|>
, generate the next line using the imports in this file:
from django.forms import widgets
from django.test import Simp... | w = LikertTextField() |
Given snippet: <|code_start|>#
# Bootstrap glyphicon stars ver 2
star_set_2 = {
'star': "<i class='icon-star likert-star'></i>",
'unlit': "<i class='icon-star-empty likert-star'></i>",
'noanswer': "<i class='icon-ban-circle likert-star'></i>"
}
# Bootstrap glyphicon stars ver 3
star_set_3 = {
'star': "... | return mark_safe(render_stars(num, max_stars, star_set_2)) |
Here is a snippet: <|code_start|> self.assertEqual(response.status_code, 200)
class SurveyCreateViewTestCase(TestCase):
def test_add_view(self):
response = self.client.get(reverse('likert_add'))
self.assertEqual(response.status_code, 200)
def test_creation_full_valid(self):
po... | surveys = ParametersModel.objects.all() |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# from .forms import SurveyForm
class SurveyListView(ListView):
context_object_name = 'surveys'
<|code_end|>
using the current file's imports:
from django.core.urlresolvers import reverse_la... | model = ParametersModel |
Given the code snippet: <|code_start|>
class Command:
""" Commands that are general to the whole scene can be subclassed from this class. """
def __init__(self):
""" initialize """
pass
def execute(self):
""" execute the command """
raise NotImplementedError(caller + ' must be implemented in subclass')
c... | translation = Vec(camera.unprojectedCoordinatesOf([mouseEvent.x(), mouseEvent.y(), 1.0])) |
Predict the next line after this snippet: <|code_start|>""" Behavioral pattern: State pattern """
class Tool(Singleton):
def __init__(self):
Singleton.__init__(self)
self.prototypeObject = None
self.prototypeManager = PrototypeManager()
self.toolType = None
<|code_end|>
using the ... | self.lastPosition = Vec([0.0,0.0,0.0]) |
Predict the next line after this snippet: <|code_start|># no more nasty rounding with integer divisions
from __future__ import division
#import Numeric
try:
except ImportError:
app = QtGui.QApplication(sys.argv)
QtGui.QMessageBox.critical(None, "OpenGL grabber","PyOpenGL must be installed to run this example."... | self.position = Vec([0.0, 0.0, 0.0]) |
Next line prediction: <|code_start|> nameForTitle = QtCore.QString(self.saveFileName)
title = nameForTitle.remove(0, nameForTitle.lastIndexOf("/")+1)
self.setWindowTitle("- " + title + self.tr(" - Geometric Constraint Solver"))
def saveAs(self):
saveDialog = QtGui.QFi... | problem = randomproblem.random_triangular_problem_3D(numpoints, size, rounding, ratio) |
Based on the snippet: <|code_start|>
class CameraHandler(QtCore.QObject):
""" The camerahandler handles the rotation, translation, zooming, fitting and other actions of the camera. """
def __init__(self, glViewport, parent = None):
""" Initialization of the camerhandler.
Parameters:
glViewport: the viewport... | self.resolvePoint = Vec([0.0, 0.0, 0.0]) |
Given snippet: <|code_start|>except ImportError:
app = QtGui.QApplication(sys.argv)
QtGui.QMessageBox.critical(None, "OpenGL grabber","PyOpenGL must be installed to run this example.",
QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default, QtGui.QMessageBox.NoButton)
sys.exit(1)
class GLViewport(QtOpenGL.QGLWidget)... | self.mousePosition = Vec([0.0, 0.0, 0.0]) |
Given snippet: <|code_start|> nor_edu_person_nin=kwargs.pop('national_id', None)
)
if kwargs:
raise TypeError("Can't search Sesam for the specified parameter(s)")
if not student:
student_kwargs = dict(id=sesam_student.nor_edu_person_lin)
try:
student = Student.ob... | id = IdField() |
Given the following code snippet before the placeholder: <|code_start|> try:
student = Student.objects.get(**student_kwargs)
except Student.DoesNotExist:
# Just instantiate, don't save.
student = Student(**student_kwargs)
student.email = sesam_student.email
st... | amount = MoneyField( |
Given the following code snippet before the placeholder: <|code_start|> return '{} - {}: {} kr'.format(self.ticket_type, self.union,
self.amount)
class DiscountRegistration(models.Model):
id = IdField()
discount = models.ForeignKey(
'Discount',
re... | name = NameField() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
urlpatterns = [
url(r'^health/$', health_view),
url(r'^api/docs/', include_docs_urls(title='Kobra API')),
url(r'^api/v1/', include('kobra.api.v1.urls', namespace='v1')),
url(r'^admin/', include(admin.site.urls)),
# Matches everything... | url(r'^$', frontend_view, name='home'), |
Here is a snippet: <|code_start|> def test_list_authenticated_unowned(self):
url = reverse('v1:discountregistration-list')
user = UserFactory()
# Creates a DiscountRegistration owned by someone else
DiscountRegistrationFactory()
self.client.force_authenticate(user)
re... | discount = DiscountFactory(union=union) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class DiscountRegistrationApiTests(APITestCase):
def test_list_unauthenticated(self):
url = reverse('v1:discountregistration-list')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED... | DiscountRegistrationFactory() |
Given the following code snippet before the placeholder: <|code_start|> url = reverse('v1:discountregistration-list')
user = UserFactory()
# Creates a DiscountRegistration owned by someone else
DiscountRegistrationFactory()
self.client.force_authenticate(user)
response = ... | student = StudentFactory(union=union) |
Given snippet: <|code_start|>
def test_list_authenticated_unowned(self):
url = reverse('v1:discountregistration-list')
user = UserFactory()
# Creates a DiscountRegistration owned by someone else
DiscountRegistrationFactory()
self.client.force_authenticate(user)
respo... | union = UnionFactory() |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class DiscountRegistrationApiTests(APITestCase):
def test_list_unauthenticated(self):
url = reverse('v1:discountregistration-list')
response = self.client.get(url)
self.assertEqual(response.sta... | user = UserFactory() |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class DiscountPermissionFilter(DjangoFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(
ticket_type__event__organization__admins=request.user)
class DiscountRegistrationFil... | model = DiscountRegistration |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class DiscountPermissionFilter(DjangoFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(
ticket_type__event__organization__admins=request.user)
class DiscountRegistrationFilter(FilterSet):
e... | queryset=Event.objects.all()) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class DiscountApiTests(APITestCase):
def test_list_unauthenticated(self):
url = reverse('v1:discount-list')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_40... | unowned_discount = DiscountFactory() |
Next line prediction: <|code_start|> request_data = {
'ticket_type': new_ticket_type_url,
'union': reverse('v1:union-detail',
kwargs={'pk': discount.union.pk}),
'amount': discount.amount
}
self.client.force_authenticate(user)
... | DiscountRegistrationFactory(discount=discount) |
Continue the code snippet: <|code_start|> 'v1:union-detail', kwargs={'pk': temp_discount.union.pk}),
'amount': temp_discount.amount
}
response = self.client.post(url, data=request_data)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test... | owned_ticket_type = TicketTypeFactory() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class DiscountApiTests(APITestCase):
def test_list_unauthenticated(self):
url = reverse('v1:discount-list')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_list_aut... | user = UserFactory() |
Given the following code snippet before the placeholder: <|code_start|>
FeedClasses = namedtuple('FeedClasses', ['feed', 'item'])
FEED_CONFIG = {
'twitter': FeedClasses(TwitterFeed, TwitterFeedItem),
'instagram': FeedClasses(InstagramFeed, InstagramFeedItem),
<|code_end|>
, predict the next line using imports... | 'facebook': FeedClasses(FacebookFeed, FacebookFeedItem) |
Continue the code snippet: <|code_start|>
FeedClasses = namedtuple('FeedClasses', ['feed', 'item'])
FEED_CONFIG = {
'twitter': FeedClasses(TwitterFeed, TwitterFeedItem),
'instagram': FeedClasses(InstagramFeed, InstagramFeedItem),
<|code_end|>
. Use current file imports:
from collections import namedtuple
fro... | 'facebook': FeedClasses(FacebookFeed, FacebookFeedItem) |
Predict the next line for this snippet: <|code_start|>
FeedClasses = namedtuple('FeedClasses', ['feed', 'item'])
FEED_CONFIG = {
'twitter': FeedClasses(TwitterFeed, TwitterFeedItem),
<|code_end|>
with the help of current file imports:
from collections import namedtuple
from .facebook import FacebookFeed, Facebo... | 'instagram': FeedClasses(InstagramFeed, InstagramFeedItem), |
Predict the next line after this snippet: <|code_start|>
FeedClasses = namedtuple('FeedClasses', ['feed', 'item'])
FEED_CONFIG = {
'twitter': FeedClasses(TwitterFeed, TwitterFeedItem),
<|code_end|>
using the current file's imports:
from collections import namedtuple
from .facebook import FacebookFeed, FacebookF... | 'instagram': FeedClasses(InstagramFeed, InstagramFeedItem), |
Here is a snippet: <|code_start|> def dispatch(self, *args, **kwargs):
return super(ModerateAllowView, self).dispatch(*args, **kwargs)
def post(self, request, pk, post_id):
config = SocialFeedConfiguration.objects.get(pk=pk)
if 'original' not in request.POST:
err = {'message... | except ModeratedItem.DoesNotExist: |
Predict the next line after this snippet: <|code_start|>from __future__ import unicode_literals
class ModerateView(DetailView):
"""
ModerateView.
Collect the latest feeds and find out which ones are already
moderated/allowed in the feed (already have an `ModeratedItem`
associated with them
... | queryset = SocialFeedConfiguration.objects.filter(moderated=True) |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
class ModerateView(DetailView):
"""
ModerateView.
Collect the latest feeds and find out which ones are already
moderated/allowed in the feed (already have an `ModeratedItem`
associated with them
"""
template_... | feed = FeedFactory.create(self.object.source) |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
class SocialFeedConfigurationFactory(factory.DjangoModelFactory):
username = factory.Faker('user_name')
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
import factory
from wagtailsocialfeed.mode... | model = SocialFeedConfiguration |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
class SocialFeedConfigurationFactory(factory.DjangoModelFactory):
username = factory.Faker('user_name')
class Meta:
model = SocialFeedConfiguration
class SocialFeedPageFactory(factory.DjangoModelFactory):
title = fa... | model = SocialFeedPage |
Predict the next line for this snippet: <|code_start|>"""
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
<|code_end|>
with the help of current file imports:
from django.utils.... | class Serializer(base.Serializer): |
Given the code snippet: <|code_start|> if pk_field in self._current:
del self._current[pk_field]
self._current.pop('@natural_key', None)
self._current.pop('@natural_key_hash', None)
def end_object(self, obj):
entry = {
"collection" : smart_unicode(obj._meta.c... | doc_cls = get_base_document(d["collection"]) |
Continue the code snippet: <|code_start|>"""
Serialize data to/from JSON
"""
class Serializer(PythonSerializer):
"""
Convert a queryset to JSON.
"""
internal_use_only = False
def end_serialization(self):
simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options)
... | for obj in PythonDeserializer(simplejson.load(stream), **options): |
Given the code snippet: <|code_start|> assert False
return ret
'''
def get_formset(self, request, view, obj=None, **kwargs):
"""Returns a BaseInlineFormSet class for use in admin add/change views."""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_... | return inlinedocumentformset_factory(self.model, self.dotpath, **defaults) |
Here is a snippet: <|code_start|> return escape(force_unicode(value))
return ''
def render(self, name, value, attrs=None):
path_parts = list()
if self.dotpath:
path_parts.append(self.dotpath)
path_parts.append(name) #TODO consider this will break if there ... | class DotPathField(HiddenJSONField): |
Given the code snippet: <|code_start|> self.deleted_objects.append(obj)
#obj.delete()
continue
if form.has_changed():
self.changed_objects.append((obj, form.changed_data))
saved_instances.append(self.save_existing(form, obj, commit=c... | def documentformset_factory(document, form=DocumentForm, formfield_callback=None, |
Given snippet: <|code_start|> return saved_instances
def save_new_objects(self, commit=True):
self.new_objects = []
for form in self.extra_forms:
if not form.has_changed():
continue
# If someone has marked an add form for deletion, don't save the
... | form = documentform_factory(document, form=form, fields=fields, exclude=exclude, |
Given snippet: <|code_start|> self._resolve_loop()
def resolve_for_raw_data(self, data, schema=None):
field = None
if schema:
field = SchemaField(schema=schema)
data = schema.to_python(data)
else:
field = DictField()
entry = {'value':da... | raise DotPathNotFound('Arrived at a dead end', traverser=self) |
Continue the code snippet: <|code_start|>
class SchemaTestCase(unittest.TestCase):
def test_to_primitive(self):
obj = SimpleSchema(_python_data={'charfield':'charmander'})
prim_data = obj.to_primitive(obj)
self.assertEqual(prim_data, {'charfield':'charmander'})
def test_to_portable... | obj = SimpleDocument() |
Predict the next line for this snippet: <|code_start|> obj = SimpleSchema(_python_data={'charfield':'charmander'})
prim_data = obj.to_portable_primitive(obj)
self.assertEqual(prim_data, {'charfield':'charmander'})
def test_to_python(self):
obj = SimpleSchema(_primitive_data={'cha... | obj = ValidatingDocument() |
Given snippet: <|code_start|> try:
obj.full_clean()
except ValidationError as error:
self.assertFalse('allow_null' in error.message_dict)
else:
self.fail('Validation is broken')
obj.with_choices = 'c'
obj.not_null = 'foo'
obj.al... | obj.subschema = SimpleSchema2() |
Continue the code snippet: <|code_start|>
def reindex(self, name, collection, query_hash):
obj, created = self.get_or_create(name=name, collection=collection, defaults={'query_hash':query_hash})
query_index = get_index_router().registered_querysets[collection][query_hash]
do... | traverser = DotPathTraverser(dotpath) |
Continue the code snippet: <|code_start|>
query_index = get_index_router().registered_querysets[collection][query_hash]
documents = obj.get_document().objects.all()
for doc in documents:
self.evaluate_query_index(obj, query_index, doc.pk, doc.to_primitive(doc))
def o... | except DotPathNotFound: |
Given the following code snippet before the placeholder: <|code_start|> #TODO proper parsing
key, operation = self._parse_key(key)
items.append(QueryFilterOperation(key=key, operation=operation, value=value))
return items
def _add_filter_parts(self, inclusions=[], exc... | return QuerySet(query) |
Based on the snippet: <|code_start|>* BooleanProperty -> BooleanField,
* FloatProperty -> FloatField,
* DateTimeProperty -> DateTimeField,
* DateProperty -> DateField,
* TimeProperty -> TimeField
More fields types will be supported soon.
"""
def document_to_dict(document, instance, properties=Non... | except DotPathNotFound: |
Next line prediction: <|code_start|>
class DocumentFormMixin(editview.FormMixin, SingleObjectMixin):
def get_form_class(self):
"""
Returns the form class to use in this view
"""
if self.form_class:
return self.form_class
else:
if self.document is not... | class CustomDocumentForm(DocumentForm): |
Here is a snippet: <|code_start|> forms.CharField: {'widget': widgets.AdminTextInputWidget},
forms.ImageField: {'widget': widgets.AdminFileWidget},
forms.FileField: {'widget': widgets.AdminFileWidget},
}
class SchemaAdmin(object):
#class based views
create = views.CreateView
upd... | paginator = Paginator |
Here is a snippet: <|code_start|> return self.as_view(self.update.as_view(**params))
def get_select_schema_view(self, **kwargs):
params = self.get_view_kwargs()
params['schema'] = self.schema
params.update(kwargs)
return self.as_view(self.select_schema.as_view(**params))
... | return DocumentForm |
Predict the next line after this snippet: <|code_start|> return self.formfield_for_manytomany(prop, field, view, **kwargs)
request = kwargs.pop('request', None)
base_property = prop
if isinstance(prop, schema.ListField):
base_property = prop.subfield
... | if issubclass(field, PrimitiveListField) and 'subfield' in kwargs: |
Given the code snippet: <|code_start|> return self.formfield_for_foreignkey(prop, field, view, **kwargs)
if isinstance(prop, schema.ModelSetField):
return self.formfield_for_manytomany(prop, field, view, **kwargs)
request = kwargs.pop('request', None)
base_propert... | if issubclass(field, HiddenJSONField): |
Predict the next line for this snippet: <|code_start|> readonly_fields = ()
declared_fieldsets = None
save_as = False
save_on_top = False
paginator = Paginator
inlines = []
#list display options
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
lis... | proxy_django_model = DockitPermission #if we really need to give a model to django, let it be this one |
Given snippet: <|code_start|>
class PythonSerializerTestCase(unittest.TestCase):
def setUp(self):
self.serializer = Serializer()
#self.deserializer = Deserializer()
def test_serialize(self):
child = ChildDocument(charfield='bar')
child.save()
parent = ParentDocument(ti... | objects = list(Deserializer(payload)) |
Here is a snippet: <|code_start|>
class PythonSerializerTestCase(unittest.TestCase):
def setUp(self):
self.serializer = Serializer()
#self.deserializer = Deserializer()
def test_serialize(self):
child = ChildDocument(charfield='bar')
child.save()
<|code_end|>
. Write the next... | parent = ParentDocument(title='foo', subdocument=child, subschema=ChildSchema(ct=ContentType.objects.all()[0])) |
Given the following code snippet before the placeholder: <|code_start|>
class PythonSerializerTestCase(unittest.TestCase):
def setUp(self):
self.serializer = Serializer()
#self.deserializer = Deserializer()
def test_serialize(self):
<|code_end|>
, predict the next line using imports from the... | child = ChildDocument(charfield='bar') |
Given snippet: <|code_start|>
class PythonSerializerTestCase(unittest.TestCase):
def setUp(self):
self.serializer = Serializer()
#self.deserializer = Deserializer()
def test_serialize(self):
child = ChildDocument(charfield='bar')
child.save()
<|code_end|>
, continue by predic... | parent = ParentDocument(title='foo', subdocument=child, subschema=ChildSchema(ct=ContentType.objects.all()[0])) |
Predict the next line after this snippet: <|code_start|> def to_python(self, value):
if value and isinstance(value, basestring):
try:
return json.loads(value)
except ValueError:
raise ValidationError("Invalid JSON")#TODO more descriptive error?
... | widget = PrimitiveListWidget |
Using the snippet: <|code_start|>
class MongoIndexStorage(BaseIndexStorage, MongoStorageMixin):
name = "mongodb"
_indexers = dict() #TODO this should be automatic
def register_index(self, query_index):
query = self.get_query(query_index)
params = query._build_params(include_indexes=True... | class MongoDocumentStorage(BaseDocumentStorage, MongoStorageMixin): |
Predict the next line after this snippet: <|code_start|> if params:
return self.collection.find(params, fields=fields, as_class=ValuesResultClass)
return self.collection.find(fields=fields, as_class=ValuesResultClass)
def __len__(self):
return self.queryset.count()
d... | class MongoIndexStorage(BaseIndexStorage, MongoStorageMixin): |
Next line prediction: <|code_start|>try:
except ImportError:
class ValuesResultClass(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
if key == 'pk':
return dict.__getitem__(self, '_id')
raise
<|code_en... | class DocumentQuery(BaseDocumentQuery): |
Given the code snippet: <|code_start|>
def _get_permission_codename(action, opts):
return u'%s.%s' % (opts.collection, action)
def _get_all_permissions(opts):
"Returns (codename, name) for all permissions in the given opts."
perms = []
for action in ('add', 'change', 'delete'):
perms.append((_... | ctype = ContentType.objects.get_for_model(DockitPermission) |
Using the snippet: <|code_start|> searched_perms = list()
ctype = ContentType.objects.get_for_model(DockitPermission)
# The codenames and ctypes that should exist.
for klass in documents:
for perm in _get_all_permissions(klass._meta):
searched_perms.append(perm)
# Find all the Pe... | document_registered.connect(on_document_registered) |
Here is a snippet: <|code_start|> for perm in _get_all_permissions(klass._meta):
searched_perms.append(perm)
# Find all the Permissions that have a context_type for a model we're
# looking for. We don't need to check for codenames since we already have
# a list of the ones we're going t... | commit_on_success(create_permissions)(get_documents(), 1) |
Continue the code snippet: <|code_start|> #CONSIDER it might be a good idea to allow registering more serializers
return {'encoder': JSONEncoder(handlers=handlers),
'decoder': JSONDecoder(handlers=handlers),}
class PrimitiveProcessor(object):
def __init__(self, handlers):
self.handlers =... | return DotPathList(map(self.to_python, obj)) |
Predict the next line for this snippet: <|code_start|>def make_serializers():
handlers = [ModelHandler(), DecimalHandler()]
#CONSIDER it might be a good idea to allow registering more serializers
return {'encoder': JSONEncoder(handlers=handlers),
'decoder': JSONDecoder(handlers=handlers),}
clas... | obj = DotPathDict(obj) |
Given the code snippet: <|code_start|> # .pyc or .pyo the second time, ignore the extension when
# comparing.
if fname1.endswith('.'+fname2) or fname2.endswith('.'+fname1):
continue
document_dict[doc_name] = document
... | document_registered.send_robust(sender=document._meta.collection, document=document) |
Given snippet: <|code_start|> * group -- The group name for the object
'''
self.__class = className
self.__group = group
self.__refId = None
self.__aceId = None
self.__version = None
def setNonNoneArguments(self, argumentNames, localVars):
'''Takes a... | Keys.Class: self.__class, |
Given the code snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pysiriproxy. If not, see <http://www.gnu.org/licenses/>.
'''The plist module contains the Plist, and BinaryPlist classes.
These classes are designed t... | Keys.Birthday, |
Using the snippet: <|code_start|>responsible for managing the ability to transfer data between two
different connections.
'''
class ConnectionManager:
'''The ConnectionManager object managers incoming connection
directions and provides the ability to forward data between them.
It allows a connection di... | Directions.From_iPhone: None, |
Given snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with pysiriproxy. If not, see <http://www.gnu.org/licenses/>.
'''Contains the Player class.'''
class Player(Thread):
'''The Player class loads a file containing data which it proceeds
to send to the give... | self.__setMode(Modes.Line) |
Given snippet: <|code_start|>
def __filterApplies(self, function, direction, obj):
'''Determine if the given filter function applies to either the
given direction or the class of the given object.
* direction -- The direction
* obj -- The object
'''
objectClass = ob... | properties = obj.get(Keys.Properties) |
Predict the next line after this snippet: <|code_start|> '''Complete a request to Siri.
.. note:: This function should always be called by speech rules
otherwise Siri will continue to spin.
'''
self.__manager.completeRequest()
##### Private functions for loading f... | elif isSpeechRule(function): |
Predict the next line after this snippet: <|code_start|> return propValue
def __getProperty(self, propName, default=None):
'''Get the value of the given property.
* default -- The default value
'''
return getattr(self, propName, default)
def __filterApplies(sel... | return speechRuleMatches(function, text) |
Using the snippet: <|code_start|> '''
self.__manager.say(text, spoken)
def completeRequest(self):
'''Complete a request to Siri.
.. note:: This function should always be called by speech rules
otherwise Siri will continue to spin.
'''
self.__manage... | if isDirectionFilter(function) or isObjectClassFilter(function): |
Given the following code snippet before the placeholder: <|code_start|> '''Force the given property to exist.
* propName -- The name of the property
'''
propValue = self.__getProperty(propName)
# Check that the name property exists
if propValue is None:
rais... | return directionsMatch(function, direction) and \ |
Predict the next line for this snippet: <|code_start|>
* commandName -- The name of the object
* direction -- The direction the object traveled to be received
'''
self.log.debug("Processing %d filters" % len(self.__filters), level=10)
# Process all of the filters for this plugi... | @From_iPhone |
Using the snippet: <|code_start|> '''
self.__manager.say(text, spoken)
def completeRequest(self):
'''Complete a request to Siri.
.. note:: This function should always be called by speech rules
otherwise Siri will continue to spin.
'''
self.__manage... | if isDirectionFilter(function) or isObjectClassFilter(function): |
Here is a snippet: <|code_start|>
* propName -- The name of the property
'''
propValue = self.__getProperty(propName)
# Check that the name property exists
if propValue is None:
raise Exception("Plugins must have a '%s' property!" % propName)
return propVal... | objectClassesMatch(function, objectClass) |
Given the following code snippet before the placeholder: <|code_start|> * function -- The function
'''
return getattr(function, _DIRECTIONS_PROP, [])
def isDirectionFilter(function):
'''Determine if the given function is a directions filter.
* function -- The function
'''
directions = ge... | From_iPhone = _addDirection(Directions.From_iPhone) |
Given the following code snippet before the placeholder: <|code_start|>
def getObjectClasses(function):
'''Get the list of object classes that this filter function
supports.
* function -- The filter function
'''
return getattr(function, _CLASSES_PROP, [])
def objectClassesMatch(function, object... | for className in ClassNames.get(): |
Predict the next line after this snippet: <|code_start|>
'''
if cls.Callback is not None:
# Have to pass an instance of the Connection to the callback
# function in order for it to work
cls.Callback(cls(), obj)
else:
cls.__log(obj)
@classmetho... | Direction = Directions.From_iPhone |
Predict the next line for this snippet: <|code_start|> self.speakableText = displayText if spokenText is None else spokenText
self.dialogIdentifier = dialogIdentifier
self.listenAfterSpeaking = listenAfterSpeaking
class _MapItemSnippet(SiriObject):
'''The _MapItemSnippet class creates a map... | directionsType=DirectionTypes.Driving, callbacks=None, |
Given the following code snippet before the placeholder: <|code_start|># model.add(Activation('hard_sigmoid'))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
#loss='mse',
#loss='categorical_crossentropy',
optimizer='adam',
metrics=['ac... | history = LossHistory() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.