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',
'oauthaccesstokens']
passwords = {'obligated@example.com': 'bar',
'popular@example.com': 'baz',
'celebrity@example.com': 'baz',
'boyfriend@example.com': 'baz',
'girlfriend@example.com': 'baz',
'annoying@example.com': 'foo',
'unpopular@example.com': 'foo',
'hermit@example.com': 'baz',
'broken@example.com': 'baz',
'CapitalPunishment@example.com': 'baz',
'root@example.com': 'fakepassword',
'hotness@example.com': 'fakepassword'};
def setUp(self):
settings.DEBUG = False
<|code_end|>
. Use current file imports:
(import urlparse
import sys
import xml.etree.ElementTree as etree
import xml.parsers.expat
from beautifulsoup import BeautifulSoup
from django import http
from django import test
from django.conf import settings
from django.test import client
from common import clean
from common import memcache
from common import profile
from common import util
from common.protocol import sms
from common.protocol import xmpp
from common.test import util as test_util)
and context including class names, function names, or small code snippets from other files:
# Path: common/protocol/xmpp.py
# class JID(object):
# class XmppMessage(object):
# class XmppConnection(base.Connection):
# def __init__(self, node, host, resource=None):
# def from_uri(cls, uri):
# def base(self):
# def full(self):
# def __init__(self, sender, target, message):
# def from_request(cls, request):
# def send_message(self, to_jid_list, message, html_message=None,
# atom_message=None):
#
# Path: common/test/util.py
# def get_url(s):
# def get_relative_url(s):
# def exhaust_queue(nick):
# def exhaust_queue_any():
# def send_message(self, to_jid_list, message, html_message=None,
# atom_message=None):
# def send_message(self, to_list, message):
# def __init__(self, **kw):
# def REQUEST(self):
# def __init__(self, *args, **kw):
# def _get_valid(self, key):
# def set(self, key, value, time=0):
# def set_multi(self, mapping, time=0, key_prefix=''):
# def add(self, key, value, time=0):
# def add_multi(self, mapping, time=0, key_prefix=''):
# def incr(self, key, delta=1):
# def decr(self, key, delta=1):
# def delete(self, key, seconds=0):
# def delete_multi(self, keys, key_prefix=''):
# def get(self, key):
# def get_multi(self, keys, key_prefix=''):
# def __init__(self, module, **kw):
# def override(self):
# def reset(self):
# def override_clock(module, **kw):
# def __init__(self, **kw):
# def override(self):
# def reset(self):
# def override(**kw):
# class TestXmppConnection(xmpp.XmppConnection):
# class TestSmsConnection(sms.SmsConnection):
# class FakeRequest(object):
# class FakeMemcache(object):
# class ClockOverride(object):
# class SettingsOverride(object):
. Output only the next line. | 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
from django.views.generic import TemplateView
from .views import SurveyCreateView, SurveyDetailView, SurveyListView
and context including class names, function names, and sometimes code from other files:
# Path: test_projects/django18/likert_test_app/views.py
# class SurveyCreateView(CreateView):
# model = ParametersModel
# # fields = ['item', 'another_item']
# fields = [
# 'ice_cream_is_yummy', 'item', 'questions_should_not_be_optional']
# # form_class = SurveyForm
# template_name = 'likert/add.html'
# success_url = reverse_lazy('likert_added')
#
# class SurveyDetailView(DetailView):
# context_object_name = 'survey'
# model = ParametersModel
# template_name = 'likert/detail.html'
#
# class SurveyListView(ListView):
# context_object_name = 'surveys'
# model = ParametersModel
# template_name = 'likert/index.html'
. Output only the next line. | 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_name='likert/added.html'),
name='likert_added'),
<|code_end|>
using the current file's imports:
from django.conf.urls import url
from django.views.generic import TemplateView
from .views import SurveyCreateView, SurveyDetailView, SurveyListView
and any relevant context from other files:
# Path: test_projects/django18/likert_test_app/views.py
# class SurveyCreateView(CreateView):
# model = ParametersModel
# # fields = ['item', 'another_item']
# fields = [
# 'ice_cream_is_yummy', 'item', 'questions_should_not_be_optional']
# # form_class = SurveyForm
# template_name = 'likert/add.html'
# success_url = reverse_lazy('likert_added')
#
# class SurveyDetailView(DetailView):
# context_object_name = 'survey'
# model = ParametersModel
# template_name = 'likert/detail.html'
#
# class SurveyListView(ListView):
# context_object_name = 'surveys'
# model = ParametersModel
# template_name = 'likert/index.html'
. Output only the next line. | 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 import Field
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.models import LikertField
from likert_field import forms
and any relevant context from other files:
# Path: likert_field/models.py
# class LikertField(models.IntegerField):
# """A Likert field is simply stored as an IntegerField"""
#
# description = _('Likert item field')
#
# def __init__(self, *args, **kwargs):
# """
# LikertField stores items with no answer as NULL
#
# By default responses are optional, so 'blank' is True
# """
# if kwargs.get('null', True):
# kwargs['null'] = True
#
# if kwargs.get('blank', True):
# kwargs['blank'] = True
#
# super(LikertField, self).__init__(*args, **kwargs)
#
# def __str__(self):
# return "%s" % force_text(self.description)
#
# def get_prep_value(self, value):
# """
# Perform preliminary non-db specific value checks and conversions.
#
# The field expects a number as a string (ie. '2'). Unscored fields are
# empty strings and are stored as NULL
# """
# if value is None:
# return None
#
# if isinstance(value, string_types) and len(value) == 0:
# return None
#
# value = int(value)
# if value < 0:
# value = 0
#
# return value
#
# def formfield(self, **kwargs):
# defaults = {
# 'min_value': 0,
# 'form_class': forms.LikertFormField
# }
# defaults.update(kwargs)
# return super(LikertField, self).formfield(**defaults)
#
# Path: likert_field/forms.py
# class LikertFormField(fields.IntegerField):
# def __init__(self, min_value=0, *args, **kwargs):
. Output only the next line. | 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_get_prep_value_strings(self):
item = LikertField()
for value in xrange(1, 50+1):
self.assertIsInstance(item.get_prep_value(str(value)), int)
def test_get_prep_value_negative_int(self):
item = LikertField()
self.assertIsInstance(item.get_prep_value(-1), int)
self.assertEqual(item.get_prep_value(-1), 0)
def test_get_prep_value_empty_string(self):
item = LikertField()
self.assertTrue(item.get_prep_value('') is None)
def test_get_prep_value_null(self):
item = LikertField()
self.assertTrue(item.get_prep_value(None) is None)
def test_formfield(self):
item = LikertField()
ff = item.formfield()
self.assertEqual(ff.min_value, 0)
<|code_end|>
with the help of current file imports:
from django.db.models.fields import Field
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.models import LikertField
from likert_field import forms
and context from other files:
# Path: likert_field/models.py
# class LikertField(models.IntegerField):
# """A Likert field is simply stored as an IntegerField"""
#
# description = _('Likert item field')
#
# def __init__(self, *args, **kwargs):
# """
# LikertField stores items with no answer as NULL
#
# By default responses are optional, so 'blank' is True
# """
# if kwargs.get('null', True):
# kwargs['null'] = True
#
# if kwargs.get('blank', True):
# kwargs['blank'] = True
#
# super(LikertField, self).__init__(*args, **kwargs)
#
# def __str__(self):
# return "%s" % force_text(self.description)
#
# def get_prep_value(self, value):
# """
# Perform preliminary non-db specific value checks and conversions.
#
# The field expects a number as a string (ie. '2'). Unscored fields are
# empty strings and are stored as NULL
# """
# if value is None:
# return None
#
# if isinstance(value, string_types) and len(value) == 0:
# return None
#
# value = int(value)
# if value < 0:
# value = 0
#
# return value
#
# def formfield(self, **kwargs):
# defaults = {
# 'min_value': 0,
# 'form_class': forms.LikertFormField
# }
# defaults.update(kwargs)
# return super(LikertField, self).formfield(**defaults)
#
# Path: likert_field/forms.py
# class LikertFormField(fields.IntegerField):
# def __init__(self, min_value=0, *args, **kwargs):
, which may contain function names, class names, or code. Output only the next line. | 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 django.forms import fields
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.forms import LikertFormField
from likert_field.widgets import LikertTextField
and context:
# Path: likert_field/forms.py
# class LikertFormField(fields.IntegerField):
# widget = LikertTextField
# default_error_messages = {
# 'invalid': _('Please rate how strongly you agree or disagree with '
# 'the statement.'),
# 'min_value': _(
# 'Ensure your response is greater than or equal to '
# '%(limit_value)s.'),
# 'max_value': _(
# 'Ensure your response is less than or equal to %(limit_value)s.'),
# }
#
# def __init__(self, min_value=0, *args, **kwargs):
# kwargs.setdefault('widget', self.widget)
# kwargs.setdefault('min_value', min_value)
# super(LikertFormField, self).__init__(*args, **kwargs)
#
# Path: likert_field/widgets.py
# class LikertTextField(widgets.TextInput):
# """A Likert field represented as a text input"""
#
# def render(self, name, value, attrs=None):
# """
# Returns this Widget rendered as HTML, as a Unicode string.
# """
# rendered_attrs = {'class': 'likert-field'}
# if attrs:
# rendered_attrs.update(attrs)
#
# return super(LikertTextField, self).render(name, value, rendered_attrs)
which might include code, classes, or functions. Output only the next line. | 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_class(self):
ff = LikertFormField()
<|code_end|>
, predict the next line using imports from the current file:
from django.core.exceptions import ValidationError
from django.forms import fields
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.forms import LikertFormField
from likert_field.widgets import LikertTextField
and context including class names, function names, and sometimes code from other files:
# Path: likert_field/forms.py
# class LikertFormField(fields.IntegerField):
# widget = LikertTextField
# default_error_messages = {
# 'invalid': _('Please rate how strongly you agree or disagree with '
# 'the statement.'),
# 'min_value': _(
# 'Ensure your response is greater than or equal to '
# '%(limit_value)s.'),
# 'max_value': _(
# 'Ensure your response is less than or equal to %(limit_value)s.'),
# }
#
# def __init__(self, min_value=0, *args, **kwargs):
# kwargs.setdefault('widget', self.widget)
# kwargs.setdefault('min_value', min_value)
# super(LikertFormField, self).__init__(*args, **kwargs)
#
# Path: likert_field/widgets.py
# class LikertTextField(widgets.TextInput):
# """A Likert field represented as a text input"""
#
# def render(self, name, value, attrs=None):
# """
# Returns this Widget rendered as HTML, as a Unicode string.
# """
# rendered_attrs = {'class': 'likert-field'}
# if attrs:
# rendered_attrs.update(attrs)
#
# return super(LikertTextField, self).render(name, value, rendered_attrs)
. Output only the next line. | 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-ban-circle likert-star'></i>"
}
# Font-awesome stars ver 4
star_set_4 = {
'star': "<i class='fa fa-star likert-star'></i>",
'unlit': "<i class='fa fa-star-o likert-star'></i>",
'noanswer': "<i class='fa fa-ban likert-star'></i>"
}
def fa_stars3(num, max_stars=5):
"""
Stars for Font Awesome 3
If num is not None, the returned string will contain num solid stars
followed by max_stars - num empty stars
"""
<|code_end|>
. Write the next line using the current file imports:
from django import template
from .likert_star_tools import render_stars
from django.utils.safestring import mark_safe
and context from other files:
# Path: likert_field/templatetags/likert_star_tools.py
# def render_stars(num, max_stars, star_set):
# """
# Star renderer returns a HTML string of stars
#
# If num is None or a blank string, it returns the unanswered tag
#
# Otherwise, the returned string will contain num solid stars
# followed by max_stars - num empty stars
#
# If num > max_stars, render max_stars solid stars
#
# star_set is a dictionary of strings with keys: star, unlit, noanswer
# """
# if num is None or (isinstance(num, string_types) and len(num) == 0):
# return star_set['noanswer']
#
# difference = int(max_stars) - int(num)
# if difference < 0:
# num = max_stars
# difference = 0
#
# return ''.join(
# star_set['star'] * int(num) + star_set['unlit'] * difference)
, which may include functions, classes, or code. Output only the next line. | 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_test_stars = 50
for max_stars in xrange(1, max_test_stars + 1):
for num in xrange(max_stars + 1):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.templatetags.likert_star_tools import render_stars
from likert_field.templatetags.likert_fa_stars import fa_stars3, fa_stars4
from likert_field.templatetags.likert_bs_stars import (
bs_stars2, bs_stars3, bs_stars3_bsr)
and context:
# Path: likert_field/templatetags/likert_star_tools.py
# def render_stars(num, max_stars, star_set):
# """
# Star renderer returns a HTML string of stars
#
# If num is None or a blank string, it returns the unanswered tag
#
# Otherwise, the returned string will contain num solid stars
# followed by max_stars - num empty stars
#
# If num > max_stars, render max_stars solid stars
#
# star_set is a dictionary of strings with keys: star, unlit, noanswer
# """
# if num is None or (isinstance(num, string_types) and len(num) == 0):
# return star_set['noanswer']
#
# difference = int(max_stars) - int(num)
# if difference < 0:
# num = max_stars
# difference = 0
#
# return ''.join(
# star_set['star'] * int(num) + star_set['unlit'] * difference)
#
# Path: likert_field/templatetags/likert_fa_stars.py
# def fa_stars3(num, max_stars=5):
# """
# Stars for Font Awesome 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def fa_stars4(num, max_stars=5):
# """
# Stars for Font Awesome 4
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_4))
#
# Path: likert_field/templatetags/likert_bs_stars.py
# def bs_stars2(num, max_stars=5):
# """
# Stars for Bootstrap 2
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_2))
#
# def bs_stars3(num, max_stars=5):
# """
# Stars for Bootstrap 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def bs_stars3_bsr(num, max_stars=5):
# """
# Stars for Bootstrap 3 w bootstrap-star-rating
#
# BSR uses a minus sign for an empty response
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3_bsr))
which might include code, classes, or functions. Output only the next line. | 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_stars = (
"<i class='glyphicon glyphicon-ban-circle likert-star'></i>")
stars = bs_stars3(num)
self.assertEqual(stars, expected_stars)
def test_bs_stars3_bsr_render_noanswer(self):
"""The BSR variant is the same as bs_stars3 except NULL handler"""
num = None
expected_stars = (
"<i class='glyphicon glyphicon-minus-sign likert-star'></i>")
stars = bs_stars3_bsr(num)
self.assertEqual(stars, expected_stars)
class FontAwesomeTestCase(SimpleTestCase):
def test_fa_stars3_render(self):
num = 2
expected_stars = (
"<i class='icon-star likert-star'></i>"
"<i class='icon-star likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>")
<|code_end|>
, predict the next line using imports from the current file:
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.templatetags.likert_star_tools import render_stars
from likert_field.templatetags.likert_fa_stars import fa_stars3, fa_stars4
from likert_field.templatetags.likert_bs_stars import (
bs_stars2, bs_stars3, bs_stars3_bsr)
and context including class names, function names, and sometimes code from other files:
# Path: likert_field/templatetags/likert_star_tools.py
# def render_stars(num, max_stars, star_set):
# """
# Star renderer returns a HTML string of stars
#
# If num is None or a blank string, it returns the unanswered tag
#
# Otherwise, the returned string will contain num solid stars
# followed by max_stars - num empty stars
#
# If num > max_stars, render max_stars solid stars
#
# star_set is a dictionary of strings with keys: star, unlit, noanswer
# """
# if num is None or (isinstance(num, string_types) and len(num) == 0):
# return star_set['noanswer']
#
# difference = int(max_stars) - int(num)
# if difference < 0:
# num = max_stars
# difference = 0
#
# return ''.join(
# star_set['star'] * int(num) + star_set['unlit'] * difference)
#
# Path: likert_field/templatetags/likert_fa_stars.py
# def fa_stars3(num, max_stars=5):
# """
# Stars for Font Awesome 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def fa_stars4(num, max_stars=5):
# """
# Stars for Font Awesome 4
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_4))
#
# Path: likert_field/templatetags/likert_bs_stars.py
# def bs_stars2(num, max_stars=5):
# """
# Stars for Bootstrap 2
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_2))
#
# def bs_stars3(num, max_stars=5):
# """
# Stars for Bootstrap 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def bs_stars3_bsr(num, max_stars=5):
# """
# Stars for Bootstrap 3 w bootstrap-star-rating
#
# BSR uses a minus sign for an empty response
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3_bsr))
. Output only the next line. | 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 class='icon-star-empty likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>")
stars = fa_stars3(num, max_stars)
self.assertEqual(stars, expected_stars)
def test_fa_stars3_render_noanswer(self):
num = None
expected_stars = "<i class='icon-ban-circle likert-star'></i>"
stars = fa_stars3(num)
self.assertEqual(stars, expected_stars)
def test_fa_stars4_render(self):
num = 2
expected_stars = (
"<i class='fa fa-star likert-star'></i>"
"<i class='fa fa-star likert-star'></i>"
"<i class='fa fa-star-o likert-star'></i>"
"<i class='fa fa-star-o likert-star'></i>"
"<i class='fa fa-star-o likert-star'></i>")
<|code_end|>
, determine the next line of code. You have imports:
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.templatetags.likert_star_tools import render_stars
from likert_field.templatetags.likert_fa_stars import fa_stars3, fa_stars4
from likert_field.templatetags.likert_bs_stars import (
bs_stars2, bs_stars3, bs_stars3_bsr)
and context (class names, function names, or code) available:
# Path: likert_field/templatetags/likert_star_tools.py
# def render_stars(num, max_stars, star_set):
# """
# Star renderer returns a HTML string of stars
#
# If num is None or a blank string, it returns the unanswered tag
#
# Otherwise, the returned string will contain num solid stars
# followed by max_stars - num empty stars
#
# If num > max_stars, render max_stars solid stars
#
# star_set is a dictionary of strings with keys: star, unlit, noanswer
# """
# if num is None or (isinstance(num, string_types) and len(num) == 0):
# return star_set['noanswer']
#
# difference = int(max_stars) - int(num)
# if difference < 0:
# num = max_stars
# difference = 0
#
# return ''.join(
# star_set['star'] * int(num) + star_set['unlit'] * difference)
#
# Path: likert_field/templatetags/likert_fa_stars.py
# def fa_stars3(num, max_stars=5):
# """
# Stars for Font Awesome 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def fa_stars4(num, max_stars=5):
# """
# Stars for Font Awesome 4
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_4))
#
# Path: likert_field/templatetags/likert_bs_stars.py
# def bs_stars2(num, max_stars=5):
# """
# Stars for Bootstrap 2
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_2))
#
# def bs_stars3(num, max_stars=5):
# """
# Stars for Bootstrap 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def bs_stars3_bsr(num, max_stars=5):
# """
# Stars for Bootstrap 3 w bootstrap-star-rating
#
# BSR uses a minus sign for an empty response
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3_bsr))
. Output only the next line. | 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
"""
max_test_stars = 50
for max_stars in xrange(1, max_test_stars + 1):
for num in xrange(max_stars + 1):
num = str(num)
max_stars = str(max_stars)
stars = render_stars(num, max_stars, self.star_set)
self.assertEqual(len(stars), int(max_stars))
self.assertEqual(stars.count(self.star_set['star']), int(num))
self.assertEqual(
stars.count(self.star_set['unlit']),
int(max_stars) - int(num))
class BootstrapTestCase(SimpleTestCase):
def test_bs_stars2_render(self):
num = 3
expected_stars = (
"<i class='icon-star likert-star'></i>"
"<i class='icon-star likert-star'></i>"
"<i class='icon-star likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>"
"<i class='icon-star-empty likert-star'></i>")
<|code_end|>
. Use current file imports:
(from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.templatetags.likert_star_tools import render_stars
from likert_field.templatetags.likert_fa_stars import fa_stars3, fa_stars4
from likert_field.templatetags.likert_bs_stars import (
bs_stars2, bs_stars3, bs_stars3_bsr))
and context including class names, function names, or small code snippets from other files:
# Path: likert_field/templatetags/likert_star_tools.py
# def render_stars(num, max_stars, star_set):
# """
# Star renderer returns a HTML string of stars
#
# If num is None or a blank string, it returns the unanswered tag
#
# Otherwise, the returned string will contain num solid stars
# followed by max_stars - num empty stars
#
# If num > max_stars, render max_stars solid stars
#
# star_set is a dictionary of strings with keys: star, unlit, noanswer
# """
# if num is None or (isinstance(num, string_types) and len(num) == 0):
# return star_set['noanswer']
#
# difference = int(max_stars) - int(num)
# if difference < 0:
# num = max_stars
# difference = 0
#
# return ''.join(
# star_set['star'] * int(num) + star_set['unlit'] * difference)
#
# Path: likert_field/templatetags/likert_fa_stars.py
# def fa_stars3(num, max_stars=5):
# """
# Stars for Font Awesome 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def fa_stars4(num, max_stars=5):
# """
# Stars for Font Awesome 4
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_4))
#
# Path: likert_field/templatetags/likert_bs_stars.py
# def bs_stars2(num, max_stars=5):
# """
# Stars for Bootstrap 2
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_2))
#
# def bs_stars3(num, max_stars=5):
# """
# Stars for Bootstrap 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def bs_stars3_bsr(num, max_stars=5):
# """
# Stars for Bootstrap 3 w bootstrap-star-rating
#
# BSR uses a minus sign for an empty response
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3_bsr))
. Output only the next line. | 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)
def test_bs_stars2_render_parameters(self):
num = 1
max_stars = 3
expected_stars = (
"<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, max_stars)
self.assertEqual(stars, expected_stars)
def test_bs_stars2_render_noanswer(self):
num = None
expected_stars = "<i class='icon-ban-circle likert-star'></i>"
stars = bs_stars2(num)
self.assertEqual(stars, expected_stars)
def test_bs_stars3_render(self):
num = 1
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-empty likert-star'></i>"
"<i class='glyphicon glyphicon-star-empty likert-star'></i>")
<|code_end|>
, predict the next line using imports from the current file:
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.templatetags.likert_star_tools import render_stars
from likert_field.templatetags.likert_fa_stars import fa_stars3, fa_stars4
from likert_field.templatetags.likert_bs_stars import (
bs_stars2, bs_stars3, bs_stars3_bsr)
and context including class names, function names, and sometimes code from other files:
# Path: likert_field/templatetags/likert_star_tools.py
# def render_stars(num, max_stars, star_set):
# """
# Star renderer returns a HTML string of stars
#
# If num is None or a blank string, it returns the unanswered tag
#
# Otherwise, the returned string will contain num solid stars
# followed by max_stars - num empty stars
#
# If num > max_stars, render max_stars solid stars
#
# star_set is a dictionary of strings with keys: star, unlit, noanswer
# """
# if num is None or (isinstance(num, string_types) and len(num) == 0):
# return star_set['noanswer']
#
# difference = int(max_stars) - int(num)
# if difference < 0:
# num = max_stars
# difference = 0
#
# return ''.join(
# star_set['star'] * int(num) + star_set['unlit'] * difference)
#
# Path: likert_field/templatetags/likert_fa_stars.py
# def fa_stars3(num, max_stars=5):
# """
# Stars for Font Awesome 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def fa_stars4(num, max_stars=5):
# """
# Stars for Font Awesome 4
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_4))
#
# Path: likert_field/templatetags/likert_bs_stars.py
# def bs_stars2(num, max_stars=5):
# """
# Stars for Bootstrap 2
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_2))
#
# def bs_stars3(num, max_stars=5):
# """
# Stars for Bootstrap 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def bs_stars3_bsr(num, max_stars=5):
# """
# Stars for Bootstrap 3 w bootstrap-star-rating
#
# BSR uses a minus sign for an empty response
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3_bsr))
. Output only the next line. | 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-empty likert-star'></i>"
"<i class='glyphicon glyphicon-star-empty likert-star'></i>")
stars = bs_stars3(num)
self.assertEqual(stars, expected_stars)
def test_bs_stars3_render_parameters(self):
num = 1
max_stars = 2
expected_stars = (
"<i class='glyphicon glyphicon-star likert-star'></i>"
"<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_stars = (
"<i class='glyphicon glyphicon-ban-circle likert-star'></i>")
stars = bs_stars3(num)
self.assertEqual(stars, expected_stars)
def test_bs_stars3_bsr_render_noanswer(self):
"""The BSR variant is the same as bs_stars3 except NULL handler"""
num = None
expected_stars = (
"<i class='glyphicon glyphicon-minus-sign likert-star'></i>")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import SimpleTestCase
from django.utils.six.moves import xrange
from likert_field.templatetags.likert_star_tools import render_stars
from likert_field.templatetags.likert_fa_stars import fa_stars3, fa_stars4
from likert_field.templatetags.likert_bs_stars import (
bs_stars2, bs_stars3, bs_stars3_bsr)
and context:
# Path: likert_field/templatetags/likert_star_tools.py
# def render_stars(num, max_stars, star_set):
# """
# Star renderer returns a HTML string of stars
#
# If num is None or a blank string, it returns the unanswered tag
#
# Otherwise, the returned string will contain num solid stars
# followed by max_stars - num empty stars
#
# If num > max_stars, render max_stars solid stars
#
# star_set is a dictionary of strings with keys: star, unlit, noanswer
# """
# if num is None or (isinstance(num, string_types) and len(num) == 0):
# return star_set['noanswer']
#
# difference = int(max_stars) - int(num)
# if difference < 0:
# num = max_stars
# difference = 0
#
# return ''.join(
# star_set['star'] * int(num) + star_set['unlit'] * difference)
#
# Path: likert_field/templatetags/likert_fa_stars.py
# def fa_stars3(num, max_stars=5):
# """
# Stars for Font Awesome 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def fa_stars4(num, max_stars=5):
# """
# Stars for Font Awesome 4
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_4))
#
# Path: likert_field/templatetags/likert_bs_stars.py
# def bs_stars2(num, max_stars=5):
# """
# Stars for Bootstrap 2
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_2))
#
# def bs_stars3(num, max_stars=5):
# """
# Stars for Bootstrap 3
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3))
#
# def bs_stars3_bsr(num, max_stars=5):
# """
# Stars for Bootstrap 3 w bootstrap-star-rating
#
# BSR uses a minus sign for an empty response
#
# If num is not None, the returned string will contain num solid stars
# followed by max_stars - num empty stars
# """
# return mark_safe(render_stars(num, max_stars, star_set_3_bsr))
which might include code, classes, or functions. Output only the next line. | 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 SimpleTestCase
from likert_field.widgets import LikertTextField
and context (functions, classes, or occasionally code) from other files:
# Path: likert_field/widgets.py
# class LikertTextField(widgets.TextInput):
# """A Likert field represented as a text input"""
#
# def render(self, name, value, attrs=None):
# """
# Returns this Widget rendered as HTML, as a Unicode string.
# """
# rendered_attrs = {'class': 'likert-field'}
# if attrs:
# rendered_attrs.update(attrs)
#
# return super(LikertTextField, self).render(name, value, rendered_attrs)
. Output only the next line. | 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': "<i class='glyphicon glyphicon-star likert-star'></i>",
'unlit': "<i class='glyphicon glyphicon-star-empty likert-star'></i>",
'noanswer': "<i class='glyphicon glyphicon-ban-circle likert-star'></i>"
}
# Bootstrap glyphicon stars ver 3 for bootstrap-star-rating
star_set_3_bsr = {
'star': "<i class='glyphicon glyphicon-star likert-star'></i>",
'unlit': "<i class='glyphicon glyphicon-star-empty likert-star'></i>",
'noanswer': "<i class='glyphicon glyphicon-minus-sign likert-star'></i>"
}
def bs_stars2(num, max_stars=5):
"""
Stars for Bootstrap 2
If num is not None, the returned string will contain num solid stars
followed by max_stars - num empty stars
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import template
from django.utils.safestring import mark_safe
from .likert_star_tools import render_stars
and context:
# Path: likert_field/templatetags/likert_star_tools.py
# def render_stars(num, max_stars, star_set):
# """
# Star renderer returns a HTML string of stars
#
# If num is None or a blank string, it returns the unanswered tag
#
# Otherwise, the returned string will contain num solid stars
# followed by max_stars - num empty stars
#
# If num > max_stars, render max_stars solid stars
#
# star_set is a dictionary of strings with keys: star, unlit, noanswer
# """
# if num is None or (isinstance(num, string_types) and len(num) == 0):
# return star_set['noanswer']
#
# difference = int(max_stars) - int(num)
# if difference < 0:
# num = max_stars
# difference = 0
#
# return ''.join(
# star_set['star'] * int(num) + star_set['unlit'] * difference)
which might include code, classes, or functions. Output only the next line. | 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):
post_data = {
'ice_cream_is_yummy': '5',
'item': '3',
'questions_should_not_be_optional': '1'
}
response = self.client.post(reverse('likert_add'), post_data)
self.assertEqual(response.status_code, 302)
self.assertTrue(response.has_header('location'))
self.assertEqual(
response['location'].count(reverse('likert_added')),
1)
def test_creation_null(self):
post_data = {
'ice_cream_is_yummy': '5',
'item': '',
'questions_should_not_be_optional': '5'
}
response = self.client.post(reverse('likert_add'), post_data)
self.assertEqual(response.status_code, 302)
<|code_end|>
. Write the next line using the current file imports:
from django.test import TestCase
from django.core.urlresolvers import reverse
from .models import ParametersModel
and context from other files:
# Path: test_projects/django18/likert_test_app/models.py
# class ParametersModel(models.Model):
# ice_cream_is_yummy = LikertField()
# # cabbage_is_yummy = LikertField(max_value=4)
# item = LikertField('ice cream beats cabbage')
# # seven = LikertField('seven is my lucky number', max_value=7)
# # ten = LikertField('ten is the best', max_value=10)
#
# questions_should_not_be_optional = LikertField(blank=False)
, which may include functions, classes, or code. Output only the next line. | 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_lazy
from django.views.generic import CreateView, DetailView, ListView
from .models import ParametersModel
and any relevant context from other files:
# Path: test_projects/django18/likert_test_app/models.py
# class ParametersModel(models.Model):
# ice_cream_is_yummy = LikertField()
# # cabbage_is_yummy = LikertField(max_value=4)
# item = LikertField('ice cream beats cabbage')
# # seven = LikertField('seven is my lucky number', max_value=7)
# # ten = LikertField('ten is the best', max_value=10)
#
# questions_should_not_be_optional = LikertField(blank=False)
. Output only the next line. | 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')
class UpdateTaskbarCommand(Command):
""" Update the taskbar whena mouse move event occurs in on of the many views/viewports. """
def __init__(self, glViewport, mainWindow):
Command.__init__(self)
self.mainWindow = mainWindow
self.glViewport = glViewport
def execute(self, mouseEvent):
""" Process the mouse move event and update the text in the taskbar
Parameters:
mouseEvent: new position of the mouse in 2D
"""
camera = self.glViewport.getCamera()
""" convert the 2D viewport coordinates into 3D projected on a Y-plane in 3D and
for the other viewports to the orthogonal plane. """
<|code_end|>
, generate the next line using the imports in this file:
from includes import *
from geosolver.matfunc import Vec
from LinearAlgebra import *
from camera import CameraType
from prototypeObjects import PrototypeManager
and context (functions, classes, or occasionally code) from other files:
# Path: geosolver/matfunc.py
# class Vec(Table):
# def dot( self, otherVec ): return reduce(operator.add, map(operator.mul, self, otherVec), 0.0)
# def norm( self ): return math.sqrt(abs( self.dot(self.conjugate()) ))
# def normSquared( self ): return abs( self.dot(self.conjugate()) )
# def normalize( self ): return self / self.norm()
# def outer( self, otherVec ): return Mat([otherVec*x for x in self])
# def cross( self, otherVec ):
# 'Compute a Vector or Cross Product with another vector'
# assert len(self) == len(otherVec) == 3, 'Cross product only defined for 3-D vectors'
# u, v = self, otherVec
# return Vec([ u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0] ])
# def house( self, index ):
# 'Compute a Householder vector which zeroes all but the index element after a reflection'
# v = Vec( Table([0]*index).concat(self[index:]) ).normalize()
# t = v[index]
# sigma = 1.0 - t**2
# if sigma != 0.0:
# t = v[index] = t<=0 and t-1.0 or -sigma / (t + 1.0)
# v /= t
# return v, 2.0 * t**2 / (sigma + t**2)
# def polyval( self, x ):
# 'Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5'
# return reduce( lambda cum,c: cum*x+c, self, 0.0 )
# def ratval( self, x ):
# 'Vec([10,20,30,40,50]).ratfit(5) evaluates to (10*x**2 + 20*x + 30) / (40*x**2 + 50*x + 1) at x=5.'
# degree = len(self) / 2
# num, den = self[:degree+1], self[degree+1:] + [1]
# return num.polyval(x) / den.polyval(x)
. Output only the next line. | 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 current file's imports:
from includes import *
from singleton import *
from prototypeObjects import *
from geosolver.matfunc import Vec
and any relevant context from other files:
# Path: geosolver/matfunc.py
# class Vec(Table):
# def dot( self, otherVec ): return reduce(operator.add, map(operator.mul, self, otherVec), 0.0)
# def norm( self ): return math.sqrt(abs( self.dot(self.conjugate()) ))
# def normSquared( self ): return abs( self.dot(self.conjugate()) )
# def normalize( self ): return self / self.norm()
# def outer( self, otherVec ): return Mat([otherVec*x for x in self])
# def cross( self, otherVec ):
# 'Compute a Vector or Cross Product with another vector'
# assert len(self) == len(otherVec) == 3, 'Cross product only defined for 3-D vectors'
# u, v = self, otherVec
# return Vec([ u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0] ])
# def house( self, index ):
# 'Compute a Householder vector which zeroes all but the index element after a reflection'
# v = Vec( Table([0]*index).concat(self[index:]) ).normalize()
# t = v[index]
# sigma = 1.0 - t**2
# if sigma != 0.0:
# t = v[index] = t<=0 and t-1.0 or -sigma / (t + 1.0)
# v /= t
# return v, 2.0 * t**2 / (sigma + t**2)
# def polyval( self, x ):
# 'Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5'
# return reduce( lambda cum,c: cum*x+c, self, 0.0 )
# def ratval( self, x ):
# 'Vec([10,20,30,40,50]).ratfit(5) evaluates to (10*x**2 + 20*x + 30) / (40*x**2 + 50*x + 1) at x=5.'
# degree = len(self) / 2
# num, den = self[:degree+1], self[degree+1:] + [1]
# return num.polyval(x) / den.polyval(x)
. Output only the next line. | 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.",
QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default, QtGui.QMessageBox.NoButton)
sys.exit(1)
class CameraType:
PERSPECTIVE, ORTHOGRAPHIC, OVERLAY = range(3)
class Camera:
def __init__(self, glViewport, camType):
self.cameraType = camType
self.setScreenWidthAndHeight(800,600)
self.farPlane = 2000.0
self.nearPlane = 0.01
self.zFarCoef = math.sqrt(3.0)
self.zNearCoef = 0.005
<|code_end|>
using the current file's imports:
import numpy.numarray as Numeric
from includes import *
from geosolver.matfunc import Vec
from quaternion import *
from prototypeObjects import *
from OpenGL.GL import *
from OpenGL.GLU import *
and any relevant context from other files:
# Path: geosolver/matfunc.py
# class Vec(Table):
# def dot( self, otherVec ): return reduce(operator.add, map(operator.mul, self, otherVec), 0.0)
# def norm( self ): return math.sqrt(abs( self.dot(self.conjugate()) ))
# def normSquared( self ): return abs( self.dot(self.conjugate()) )
# def normalize( self ): return self / self.norm()
# def outer( self, otherVec ): return Mat([otherVec*x for x in self])
# def cross( self, otherVec ):
# 'Compute a Vector or Cross Product with another vector'
# assert len(self) == len(otherVec) == 3, 'Cross product only defined for 3-D vectors'
# u, v = self, otherVec
# return Vec([ u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0] ])
# def house( self, index ):
# 'Compute a Householder vector which zeroes all but the index element after a reflection'
# v = Vec( Table([0]*index).concat(self[index:]) ).normalize()
# t = v[index]
# sigma = 1.0 - t**2
# if sigma != 0.0:
# t = v[index] = t<=0 and t-1.0 or -sigma / (t + 1.0)
# v /= t
# return v, 2.0 * t**2 / (sigma + t**2)
# def polyval( self, x ):
# 'Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5'
# return reduce( lambda cum,c: cum*x+c, self, 0.0 )
# def ratval( self, x ):
# 'Vec([10,20,30,40,50]).ratfit(5) evaluates to (10*x**2 + 20*x + 30) / (40*x**2 + 50*x + 1) at x=5.'
# degree = len(self) / 2
# num, den = self[:degree+1], self[degree+1:] + [1]
# return num.polyval(x) / den.polyval(x)
. Output only the next line. | 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.QFileDialog()
saveDialog.setDefaultSuffix(".gcs")
filename = saveDialog.getSaveFileName(self, self.tr("Save As.."), "", self.tr("GCS Files (*.gcs)"))
if not filename.isEmpty():
if not filename.endsWith(saveDialog.defaultSuffix()):
filename.append(saveDialog.defaultSuffix())
self.saveFileName = filename
self.save()
def importFile(self):
filename = QtGui.QFileDialog.getOpenFileName(self, self.tr("Import File"), "", self.tr("GCS Files (*.gcs)"))
if not filename.isEmpty():
self.importCommand = ImportCommand(self)
self.importCommand.execute(filename)
# Rick 20090522
def generateRandom(self):
## first do as if File->New was selected
self.new()
## then show randomProblemDialog
#ui = Ui_randomProblemDialog()
#dialog = QtDialog()
## create random problem
(numpoints, ratio, size, rounding) = (10, 0.0, 100.0, 0.0)
<|code_end|>
. Use current file imports:
(import preferencesDlg, decompositionView
from includes import *
from viewportManager import *
from prototypeObjects import PrototypeManager
from tools import *
from panel import *
from solutionView import *
from parameters import Settings
from geosolver import randomproblem
from ui_randomProblemDialog import Ui_randomProblemDialog)
and context including class names, function names, or small code snippets from other files:
# Path: geosolver/randomproblem.py
# def _constraint_group(problem, group, dependend, angleratio):
# def _round(val,roundoff):
# def random_problem_2D(numpoints, radius=10.0, roundoff=0.0, angleratio=0.5):
# def add_random_constraint(problem, ratio):
# def randomize_angles(problem):
# def randomize_hedgehogs(problem):
# def randomize_balloons(problem):
# def random_distance_problem_3D(npoints, radius, roundoff):
# def random_triangular_problem_3D(npoints, radius, roundoff, pangle):
# def test():
. Output only the next line. | 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 which is controlled by the camera
parent: parent of the camerahandler
"""
QtCore.QObject.__init__(self, parent)
<|code_end|>
, predict the immediate next line with the help of imports:
from includes import *
from camera import *
from geosolver.matfunc import Vec
and context (classes, functions, sometimes code) from other files:
# Path: geosolver/matfunc.py
# class Vec(Table):
# def dot( self, otherVec ): return reduce(operator.add, map(operator.mul, self, otherVec), 0.0)
# def norm( self ): return math.sqrt(abs( self.dot(self.conjugate()) ))
# def normSquared( self ): return abs( self.dot(self.conjugate()) )
# def normalize( self ): return self / self.norm()
# def outer( self, otherVec ): return Mat([otherVec*x for x in self])
# def cross( self, otherVec ):
# 'Compute a Vector or Cross Product with another vector'
# assert len(self) == len(otherVec) == 3, 'Cross product only defined for 3-D vectors'
# u, v = self, otherVec
# return Vec([ u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0] ])
# def house( self, index ):
# 'Compute a Householder vector which zeroes all but the index element after a reflection'
# v = Vec( Table([0]*index).concat(self[index:]) ).normalize()
# t = v[index]
# sigma = 1.0 - t**2
# if sigma != 0.0:
# t = v[index] = t<=0 and t-1.0 or -sigma / (t + 1.0)
# v /= t
# return v, 2.0 * t**2 / (sigma + t**2)
# def polyval( self, x ):
# 'Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5'
# return reduce( lambda cum,c: cum*x+c, self, 0.0 )
# def ratval( self, x ):
# 'Vec([10,20,30,40,50]).ratfit(5) evaluates to (10*x**2 + 20*x + 30) / (40*x**2 + 50*x + 1) at x=5.'
# degree = len(self) / 2
# num, den = self[:degree+1], self[degree+1:] + [1]
# return num.polyval(x) / den.polyval(x)
. Output only the next line. | 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):
def __init__(self, viewport, vpType, shareWidget=None, format=None, parent=None):
QtOpenGL.QGLWidget.__init__(self, format, parent)
self.gridColor = QtGui.QColor(190,190,190)
#self.gridVisible = True
self.viewport = viewport
self.sceneObjects = SceneObject(self)
self.setMouseTracking(True)
self.windowWidth = 0
self.windowHeight = 0
self.zoomfactor = 1.0
self.scaleAxis = 1.0
self.viewportType = vpType
self.camera = None
self.cameraHandler = CameraHandler(self)
self.selectionHandler = SelectionHandler()
self.settings = Settings()
self.bindings = {}
self.bufferSize = 4000
self.selectRegionWidth = 3
self.selectRegionHeight = 3
self.selectionRect = QtCore.QRect()
self.selectedName = -1
self.texture = None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from includes import *
from camera import *
from cameraHandler import *
from prototypeObjects import *
from sceneObjects import *
from parameters import Settings
from geosolver.matfunc import Vec
from OpenGL.GL import *
from OpenGL.GLU import *
import viewport
and context:
# Path: geosolver/matfunc.py
# class Vec(Table):
# def dot( self, otherVec ): return reduce(operator.add, map(operator.mul, self, otherVec), 0.0)
# def norm( self ): return math.sqrt(abs( self.dot(self.conjugate()) ))
# def normSquared( self ): return abs( self.dot(self.conjugate()) )
# def normalize( self ): return self / self.norm()
# def outer( self, otherVec ): return Mat([otherVec*x for x in self])
# def cross( self, otherVec ):
# 'Compute a Vector or Cross Product with another vector'
# assert len(self) == len(otherVec) == 3, 'Cross product only defined for 3-D vectors'
# u, v = self, otherVec
# return Vec([ u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0] ])
# def house( self, index ):
# 'Compute a Householder vector which zeroes all but the index element after a reflection'
# v = Vec( Table([0]*index).concat(self[index:]) ).normalize()
# t = v[index]
# sigma = 1.0 - t**2
# if sigma != 0.0:
# t = v[index] = t<=0 and t-1.0 or -sigma / (t + 1.0)
# v /= t
# return v, 2.0 * t**2 / (sigma + t**2)
# def polyval( self, x ):
# 'Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5'
# return reduce( lambda cum,c: cum*x+c, self, 0.0 )
# def ratval( self, x ):
# 'Vec([10,20,30,40,50]).ratfit(5) evaluates to (10*x**2 + 20*x + 30) / (40*x**2 + 50*x + 1) at x=5.'
# degree = len(self) / 2
# num, den = self[:degree+1], self[degree+1:] + [1]
# return num.polyval(x) / den.polyval(x)
which might include code, classes, or functions. Output only the next line. | 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.objects.get(**student_kwargs)
except Student.DoesNotExist:
# Just instantiate, don't save.
student = Student(**student_kwargs)
student.email = sesam_student.email
student.liu_id = sesam_student.liu_id
student.liu_lin = sesam_student.liu_lin
student.full_name = sesam_student.full_name
student.first_name = sesam_student.first_name
student.last_name = sesam_student.last_name
student.union = Union.objects.get_or_create(
name=sesam_student.main_union)[0] if sesam_student.main_union else None
# The student_union field in Sesam is not a good indicator of section
# membership and is therefore deprecated.
student.section = None
return student
class Discount(models.Model):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import sesam
from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin
)
from django.db import models
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from .db_fields import IdField, MoneyField, NameField
and context:
# Path: kobra/db_fields.py
# class IdField(models.UUIDField):
# def __init__(self, *args, **kwargs):
# kwargs['primary_key'] = kwargs.get('primary_key', True)
# kwargs['default'] = kwargs.get('default', uuid.uuid4)
# kwargs['editable'] = kwargs.get('editable', False)
# kwargs['verbose_name'] = kwargs.get('verbose_name', _('ID'))
# super(IdField, self).__init__(*args, **kwargs)
#
# class MoneyField(models.DecimalField):
# def __init__(self, *args, **kwargs):
# kwargs['max_digits'] = kwargs.get('max_digits', 12)
# kwargs['decimal_places'] = 2
# super(MoneyField, self).__init__(*args, **kwargs)
#
# class NameField(StripValueMixin, models.CharField):
# def __init__(self, *args, **kwargs):
# kwargs['max_length'] = kwargs.get('max_length', 64)
# kwargs['verbose_name'] = kwargs.get('verbose_name', _('name'))
# super(NameField, self).__init__(*args, **kwargs)
which might include code, classes, or functions. Output only the next line. | 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
student.liu_id = sesam_student.liu_id
student.liu_lin = sesam_student.liu_lin
student.full_name = sesam_student.full_name
student.first_name = sesam_student.first_name
student.last_name = sesam_student.last_name
student.union = Union.objects.get_or_create(
name=sesam_student.main_union)[0] if sesam_student.main_union else None
# The student_union field in Sesam is not a good indicator of section
# membership and is therefore deprecated.
student.section = None
return student
class Discount(models.Model):
id = IdField()
ticket_type = models.ForeignKey(
'TicketType',
related_name='discounts')
union = models.ForeignKey(
'Union',
related_name='discounts')
<|code_end|>
, predict the next line using imports from the current file:
import logging
import sesam
from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin
)
from django.db import models
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from .db_fields import IdField, MoneyField, NameField
and context including class names, function names, and sometimes code from other files:
# Path: kobra/db_fields.py
# class IdField(models.UUIDField):
# def __init__(self, *args, **kwargs):
# kwargs['primary_key'] = kwargs.get('primary_key', True)
# kwargs['default'] = kwargs.get('default', uuid.uuid4)
# kwargs['editable'] = kwargs.get('editable', False)
# kwargs['verbose_name'] = kwargs.get('verbose_name', _('ID'))
# super(IdField, self).__init__(*args, **kwargs)
#
# class MoneyField(models.DecimalField):
# def __init__(self, *args, **kwargs):
# kwargs['max_digits'] = kwargs.get('max_digits', 12)
# kwargs['decimal_places'] = 2
# super(MoneyField, self).__init__(*args, **kwargs)
#
# class NameField(StripValueMixin, models.CharField):
# def __init__(self, *args, **kwargs):
# kwargs['max_length'] = kwargs.get('max_length', 64)
# kwargs['verbose_name'] = kwargs.get('verbose_name', _('name'))
# super(NameField, self).__init__(*args, **kwargs)
. Output only the next line. | 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',
related_name='discount_registrations',
on_delete=models.PROTECT)
student = models.ForeignKey(
'Student',
related_name='discount_registrations',
on_delete=models.PROTECT)
timestamp = models.DateTimeField(
default=now)
class Meta:
ordering = ['-timestamp']
permissions = [
['view_discountregistration', _('Can view discount registration')]
]
class Event(models.Model):
id = IdField()
<|code_end|>
, predict the next line using imports from the current file:
import logging
import sesam
from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin
)
from django.db import models
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from .db_fields import IdField, MoneyField, NameField
and context including class names, function names, and sometimes code from other files:
# Path: kobra/db_fields.py
# class IdField(models.UUIDField):
# def __init__(self, *args, **kwargs):
# kwargs['primary_key'] = kwargs.get('primary_key', True)
# kwargs['default'] = kwargs.get('default', uuid.uuid4)
# kwargs['editable'] = kwargs.get('editable', False)
# kwargs['verbose_name'] = kwargs.get('verbose_name', _('ID'))
# super(IdField, self).__init__(*args, **kwargs)
#
# class MoneyField(models.DecimalField):
# def __init__(self, *args, **kwargs):
# kwargs['max_digits'] = kwargs.get('max_digits', 12)
# kwargs['decimal_places'] = 2
# super(MoneyField, self).__init__(*args, **kwargs)
#
# class NameField(StripValueMixin, models.CharField):
# def __init__(self, *args, **kwargs):
# kwargs['max_length'] = kwargs.get('max_length', 64)
# kwargs['verbose_name'] = kwargs.get('verbose_name', _('name'))
# super(NameField, self).__init__(*args, **kwargs)
. Output only the next line. | 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* and therefore must come last.
# *everything except /static/... since this breaks the static file serving.
# All other URLs are handled by the frontend app router.
url(r'^(?!static/)', include([
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.documentation import include_docs_urls
from .views import health_view, frontend_view
and context (functions, classes, or occasionally code) from other files:
# Path: kobra/views.py
# def health_view(request):
# return HttpResponse()
#
# def frontend_view(request):
# return TemplateResponse(request, template='index.html', context=dict(
# FRONTEND_ENV=json.dumps(settings.FRONTEND_SETTINGS),
# ))
. Output only the next line. | 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)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, [])
def test_list_authenticated_owned(self):
url = reverse('v1:discountregistration-list')
user = UserFactory()
owned_discount_registration = DiscountRegistrationFactory()
owned_discount_registration.discount.ticket_type.event.organization.admins\
.add(user)
# Creates a DiscountRegistration owned by someone else
DiscountRegistrationFactory()
self.client.force_authenticate(user)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['id'], str(owned_discount_registration.id))
def test_create_unauthenticated(self):
url = reverse('v1:discountregistration-list')
union = UnionFactory()
<|code_end|>
. Write the next line using the current file imports:
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
StudentFactory, UnionFactory, UserFactory)
and context from other files:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class StudentFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
# liu_id = factory.LazyAttributeSequence(
# lambda self, seq: '{:.5}{:03d}'.format(
# self.name.lower(), seq))
# mifare_id = factory.fuzzy.FuzzyInteger(0, 0xffffffffffffff)
#
# union = factory.SubFactory(UnionFactory)
# section = factory.SubFactory(SectionFactory)
#
# email = factory.Faker('email')
#
# id = factory.LazyFunction(uuid.uuid4)
# liu_lin = factory.LazyFunction(uuid.uuid4)
#
# class Meta:
# model = Student
#
# class UnionFactory(factory.DjangoModelFactory):
# name = factory.Faker('company')
#
# class Meta:
# model = Union
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
, which may include functions, classes, or code. Output only the next line. | 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)
def test_list_authenticated(self):
url = reverse('v1:discountregistration-list')
user = UserFactory()
self.client.force_authenticate(user)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, [])
def test_list_authenticated_unowned(self):
url = reverse('v1:discountregistration-list')
user = UserFactory()
# Creates a DiscountRegistration owned by someone else
<|code_end|>
, determine the next line of code. You have imports:
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
StudentFactory, UnionFactory, UserFactory)
and context (class names, function names, or code) available:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class StudentFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
# liu_id = factory.LazyAttributeSequence(
# lambda self, seq: '{:.5}{:03d}'.format(
# self.name.lower(), seq))
# mifare_id = factory.fuzzy.FuzzyInteger(0, 0xffffffffffffff)
#
# union = factory.SubFactory(UnionFactory)
# section = factory.SubFactory(SectionFactory)
#
# email = factory.Faker('email')
#
# id = factory.LazyFunction(uuid.uuid4)
# liu_lin = factory.LazyFunction(uuid.uuid4)
#
# class Meta:
# model = Student
#
# class UnionFactory(factory.DjangoModelFactory):
# name = factory.Faker('company')
#
# class Meta:
# model = Union
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
. Output only the next line. | 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 = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, [])
def test_list_authenticated_owned(self):
url = reverse('v1:discountregistration-list')
user = UserFactory()
owned_discount_registration = DiscountRegistrationFactory()
owned_discount_registration.discount.ticket_type.event.organization.admins\
.add(user)
# Creates a DiscountRegistration owned by someone else
DiscountRegistrationFactory()
self.client.force_authenticate(user)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['id'], str(owned_discount_registration.id))
def test_create_unauthenticated(self):
url = reverse('v1:discountregistration-list')
union = UnionFactory()
discount = DiscountFactory(union=union)
<|code_end|>
, predict the next line using imports from the current file:
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
StudentFactory, UnionFactory, UserFactory)
and context including class names, function names, and sometimes code from other files:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class StudentFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
# liu_id = factory.LazyAttributeSequence(
# lambda self, seq: '{:.5}{:03d}'.format(
# self.name.lower(), seq))
# mifare_id = factory.fuzzy.FuzzyInteger(0, 0xffffffffffffff)
#
# union = factory.SubFactory(UnionFactory)
# section = factory.SubFactory(SectionFactory)
#
# email = factory.Faker('email')
#
# id = factory.LazyFunction(uuid.uuid4)
# liu_lin = factory.LazyFunction(uuid.uuid4)
#
# class Meta:
# model = Student
#
# class UnionFactory(factory.DjangoModelFactory):
# name = factory.Faker('company')
#
# class Meta:
# model = Union
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
. Output only the next line. | 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)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, [])
def test_list_authenticated_owned(self):
url = reverse('v1:discountregistration-list')
user = UserFactory()
owned_discount_registration = DiscountRegistrationFactory()
owned_discount_registration.discount.ticket_type.event.organization.admins\
.add(user)
# Creates a DiscountRegistration owned by someone else
DiscountRegistrationFactory()
self.client.force_authenticate(user)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['id'], str(owned_discount_registration.id))
def test_create_unauthenticated(self):
url = reverse('v1:discountregistration-list')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
StudentFactory, UnionFactory, UserFactory)
and context:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class StudentFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
# liu_id = factory.LazyAttributeSequence(
# lambda self, seq: '{:.5}{:03d}'.format(
# self.name.lower(), seq))
# mifare_id = factory.fuzzy.FuzzyInteger(0, 0xffffffffffffff)
#
# union = factory.SubFactory(UnionFactory)
# section = factory.SubFactory(SectionFactory)
#
# email = factory.Faker('email')
#
# id = factory.LazyFunction(uuid.uuid4)
# liu_lin = factory.LazyFunction(uuid.uuid4)
#
# class Meta:
# model = Student
#
# class UnionFactory(factory.DjangoModelFactory):
# name = factory.Faker('company')
#
# class Meta:
# model = Union
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
which might include code, classes, or functions. Output only the next line. | 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.status_code, status.HTTP_401_UNAUTHORIZED)
def test_list_authenticated(self):
url = reverse('v1:discountregistration-list')
<|code_end|>
, predict the next line using imports from the current file:
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
StudentFactory, UnionFactory, UserFactory)
and context including class names, function names, and sometimes code from other files:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class StudentFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
# liu_id = factory.LazyAttributeSequence(
# lambda self, seq: '{:.5}{:03d}'.format(
# self.name.lower(), seq))
# mifare_id = factory.fuzzy.FuzzyInteger(0, 0xffffffffffffff)
#
# union = factory.SubFactory(UnionFactory)
# section = factory.SubFactory(SectionFactory)
#
# email = factory.Faker('email')
#
# id = factory.LazyFunction(uuid.uuid4)
# liu_lin = factory.LazyFunction(uuid.uuid4)
#
# class Meta:
# model = Student
#
# class UnionFactory(factory.DjangoModelFactory):
# name = factory.Faker('company')
#
# class Meta:
# model = Union
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
. Output only the next line. | 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 DiscountRegistrationFilter(FilterSet):
event = django_filters.ModelChoiceFilter(
name='discount__ticket_type__event',
queryset=Event.objects.all())
class Meta:
<|code_end|>
with the help of current file imports:
import django_filters
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from rest_framework import filters
from ...models import DiscountRegistration, Event, TicketType
and context from other files:
# Path: kobra/models.py
# class DiscountRegistration(models.Model):
# id = IdField()
#
# discount = models.ForeignKey(
# 'Discount',
# related_name='discount_registrations',
# on_delete=models.PROTECT)
# student = models.ForeignKey(
# 'Student',
# related_name='discount_registrations',
# on_delete=models.PROTECT)
#
# timestamp = models.DateTimeField(
# default=now)
#
# class Meta:
# ordering = ['-timestamp']
#
# permissions = [
# ['view_discountregistration', _('Can view discount registration')]
# ]
#
# class Event(models.Model):
# id = IdField()
#
# name = NameField()
#
# organization = models.ForeignKey(
# 'Organization',
# related_name='events')
#
# class Meta:
# ordering = ['name']
#
# permissions = [
# ['view_event', _('Can view event')]
# ]
#
# def __str__(self):
# return '{} / {}'.format(self.organization, self.name)
#
# class TicketType(models.Model):
# id = IdField()
#
# name = NameField()
# event = models.ForeignKey(
# 'Event',
# related_name='ticket_types',
# verbose_name=_('event'))
#
# personal_discount_limit = models.PositiveIntegerField(
# default=1,
# null=True,
# blank=True,
# verbose_name=_('personal discount limit'),
# help_text=_('The maximum number of discount registrations per person '
# 'for this ticket type. This should almost always be 1. '
# 'Blank means no limit. Setting this incorrectly can make '
# 'your organization liable for repayment.'))
#
# class Meta:
# ordering = ['name']
#
# permissions = [
# ['view_tickettype', _('Can view ticket type')]
# ]
#
# unique_together = [['event', 'name']]
#
# def __str__(self):
# return '{} / {}'.format(self.event, self.name)
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# for union in Union.objects.all():
# Discount.objects.get_or_create(ticket_type=self, union=union)
, which may contain function names, class names, or code. Output only the next line. | 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):
event = django_filters.ModelChoiceFilter(
name='discount__ticket_type__event',
<|code_end|>
, determine the next line of code. You have imports:
import django_filters
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from rest_framework import filters
from ...models import DiscountRegistration, Event, TicketType
and context (class names, function names, or code) available:
# Path: kobra/models.py
# class DiscountRegistration(models.Model):
# id = IdField()
#
# discount = models.ForeignKey(
# 'Discount',
# related_name='discount_registrations',
# on_delete=models.PROTECT)
# student = models.ForeignKey(
# 'Student',
# related_name='discount_registrations',
# on_delete=models.PROTECT)
#
# timestamp = models.DateTimeField(
# default=now)
#
# class Meta:
# ordering = ['-timestamp']
#
# permissions = [
# ['view_discountregistration', _('Can view discount registration')]
# ]
#
# class Event(models.Model):
# id = IdField()
#
# name = NameField()
#
# organization = models.ForeignKey(
# 'Organization',
# related_name='events')
#
# class Meta:
# ordering = ['name']
#
# permissions = [
# ['view_event', _('Can view event')]
# ]
#
# def __str__(self):
# return '{} / {}'.format(self.organization, self.name)
#
# class TicketType(models.Model):
# id = IdField()
#
# name = NameField()
# event = models.ForeignKey(
# 'Event',
# related_name='ticket_types',
# verbose_name=_('event'))
#
# personal_discount_limit = models.PositiveIntegerField(
# default=1,
# null=True,
# blank=True,
# verbose_name=_('personal discount limit'),
# help_text=_('The maximum number of discount registrations per person '
# 'for this ticket type. This should almost always be 1. '
# 'Blank means no limit. Setting this incorrectly can make '
# 'your organization liable for repayment.'))
#
# class Meta:
# ordering = ['name']
#
# permissions = [
# ['view_tickettype', _('Can view ticket type')]
# ]
#
# unique_together = [['event', 'name']]
#
# def __str__(self):
# return '{} / {}'.format(self.event, self.name)
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# for union in Union.objects.all():
# Discount.objects.get_or_create(ticket_type=self, union=union)
. Output only the next line. | 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_401_UNAUTHORIZED)
def test_list_authenticated(self):
url = reverse('v1:discount-list')
user = UserFactory()
self.client.force_authenticate(user)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, [])
def test_list_authenticated_unowned(self):
url = reverse('v1:discount-list')
user = UserFactory()
# Creates a Discount "owned" by someone else
<|code_end|>
, predict the next line using imports from the current file:
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
TicketTypeFactory, UserFactory)
and context including class names, function names, and sometimes code from other files:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class TicketTypeFactory(factory.DjangoModelFactory):
# name = factory.Faker('word')
# event = factory.SubFactory(EventFactory)
#
# class Meta:
# model = TicketType
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
. Output only the next line. | 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)
response = self.client.put(url, data=request_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_delete_unauthenticated(self):
discount = DiscountFactory()
url = reverse('v1:discount-detail', kwargs={'pk': discount.pk})
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_delete_authenticated_unowned_without_registrations(self):
user = UserFactory()
discount = DiscountFactory()
url = reverse('v1:discount-detail', kwargs={'pk': discount.pk})
self.client.force_authenticate(user)
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_delete_authenticated_unowned_with_registrations(self):
user = UserFactory()
discount = DiscountFactory()
<|code_end|>
. Use current file imports:
(from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
TicketTypeFactory, UserFactory))
and context including class names, function names, or small code snippets from other files:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class TicketTypeFactory(factory.DjangoModelFactory):
# name = factory.Faker('word')
# event = factory.SubFactory(EventFactory)
#
# class Meta:
# model = TicketType
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
. Output only the next line. | 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_create_authenticated_unowned_ticket_type(self):
url = reverse('v1:discount-list')
user = UserFactory()
# I'm lazy. Let's use the factory, but don't save the object.
temp_discount = DiscountFactory.build()
request_data = {
'ticket_type': reverse(
'v1:tickettype-detail',
kwargs={'pk': temp_discount.ticket_type.pk}),
'union': reverse(
'v1:union-detail', kwargs={'pk': temp_discount.union.pk}),
'amount': temp_discount.amount
}
self.client.force_authenticate(user)
response = self.client.post(url, data=request_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_authenticated_owned_ticket_type(self):
url = reverse('v1:discount-list')
user = UserFactory()
<|code_end|>
. Use current file imports:
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
TicketTypeFactory, UserFactory)
and context (classes, functions, or code) from other files:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class TicketTypeFactory(factory.DjangoModelFactory):
# name = factory.Faker('word')
# event = factory.SubFactory(EventFactory)
#
# class Meta:
# model = TicketType
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
. Output only the next line. | 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_authenticated(self):
url = reverse('v1:discount-list')
<|code_end|>
, determine the next line of code. You have imports:
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ....factories import (DiscountFactory, DiscountRegistrationFactory,
TicketTypeFactory, UserFactory)
and context (class names, function names, or code) available:
# Path: kobra/factories.py
# class DiscountFactory(factory.DjangoModelFactory):
# ticket_type = factory.SubFactory(TicketTypeFactory)
# union = factory.Iterator(Union.objects.all())
# amount = factory.fuzzy.FuzzyInteger(5, 30)
#
# class Meta:
# model = Discount
#
# class DiscountRegistrationFactory(factory.DjangoModelFactory):
# discount = factory.SubFactory(DiscountFactory)
# student = factory.SubFactory(StudentFactory)
#
# class Meta:
# model = DiscountRegistration
#
# class TicketTypeFactory(factory.DjangoModelFactory):
# name = factory.Faker('word')
# event = factory.SubFactory(EventFactory)
#
# class Meta:
# model = TicketType
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Faker('name')
#
# email = factory.Faker('email')
#
# class Meta:
# model = settings.AUTH_USER_MODEL
. Output only the next line. | 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 from the current file:
from collections import namedtuple
from .facebook import FacebookFeed, FacebookFeedItem
from .instagram import InstagramFeed, InstagramFeedItem
from .twitter import TwitterFeed, TwitterFeedItem
and context including class names, function names, and sometimes code from other files:
# Path: wagtailsocialfeed/utils/feed/facebook.py
# class FacebookFeed(AbstractFeed):
# item_cls = FacebookFeedItem
# query_cls = FacebookFeedQuery
#
# class FacebookFeedItem(FeedItem):
# """Implements facebook-specific behaviour."""
#
# @classmethod
# def get_post_date(cls, raw):
# if 'created_time' in raw:
# return dateparser.parse(raw.get('created_time'))
# return None
#
# @classmethod
# def from_raw(cls, raw):
# item_type = PostType(raw['type'])
# image = {}
# if 'picture' in raw:
# image = {
# 'thumb': {'url': raw['picture']},
# # 'small': raw['images']['low_resolution'],
# # 'medium': raw['images']['standard_resolution'],
# # 'largel': None,
# }
#
# return cls(
# id=raw['id'],
# type='facebook',
# text=item_type.get_text_from(raw),
# image_dict=image,
# posted=cls.get_post_date(raw),
# original_data=raw,
# )
#
# Path: wagtailsocialfeed/utils/feed/instagram.py
# class InstagramFeed(AbstractFeed):
# item_cls = InstagramFeedItem
# query_cls = InstagramFeedQuery
#
# class InstagramFeedItem(FeedItem):
# """Implements instagram-specific behaviour"""
#
# @classmethod
# def get_post_date(cls, raw):
# if 'date' in raw:
# timestamp = None
# try:
# timestamp = float(raw['date'])
# except ValueError:
# return None
# return timezone.make_aware(
# datetime.datetime.fromtimestamp(timestamp), timezone=timezone.utc)
#
# return None
#
# @classmethod
# def from_raw(cls, raw):
# image = {}
# caption = None
# if 'display_src' in raw:
# image = {
# 'thumb': raw['thumbnail_resources'][1],
# 'small': raw['thumbnail_resources'][2],
# 'medium': raw['thumbnail_resources'][3],
# 'large': raw['thumbnail_resources'][4],
# 'original_link': "https://www.instagram.com/p/" + raw['code']
# }
#
# if 'caption' in raw:
# caption = raw['caption']
#
# return cls(
# id=raw['id'],
# type='instagram',
# text=caption,
# image_dict=image,
# posted=cls.get_post_date(raw),
# original_data=raw,
# )
#
# Path: wagtailsocialfeed/utils/feed/twitter.py
# class TwitterFeed(AbstractFeed):
# item_cls = TwitterFeedItem
# query_cls = TwitterFeedQuery
#
# class TwitterFeedItem(FeedItem):
# @classmethod
# def get_post_date(cls, raw):
# # Use the dateutil parser because on some platforms
# # python's own strptime doesn't support the %z directive.
# # Format: '%a %b %d %H:%M:%S %z %Y'
# return dateparser.parse(raw.get('created_at'))
#
# @classmethod
# def from_raw(cls, raw):
# image = None
# extended = raw.get('extended_entities', None)
# if extended:
# image = process_images(extended.get('media', None))
# date = cls.get_post_date(raw)
# return cls(
# id=raw['id'],
# type='twitter',
# text=raw['text'],
# image_dict=image,
# posted=date,
# original_data=raw
# )
. Output only the next line. | '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
from .facebook import FacebookFeed, FacebookFeedItem
from .instagram import InstagramFeed, InstagramFeedItem
from .twitter import TwitterFeed, TwitterFeedItem
and context (classes, functions, or code) from other files:
# Path: wagtailsocialfeed/utils/feed/facebook.py
# class FacebookFeed(AbstractFeed):
# item_cls = FacebookFeedItem
# query_cls = FacebookFeedQuery
#
# class FacebookFeedItem(FeedItem):
# """Implements facebook-specific behaviour."""
#
# @classmethod
# def get_post_date(cls, raw):
# if 'created_time' in raw:
# return dateparser.parse(raw.get('created_time'))
# return None
#
# @classmethod
# def from_raw(cls, raw):
# item_type = PostType(raw['type'])
# image = {}
# if 'picture' in raw:
# image = {
# 'thumb': {'url': raw['picture']},
# # 'small': raw['images']['low_resolution'],
# # 'medium': raw['images']['standard_resolution'],
# # 'largel': None,
# }
#
# return cls(
# id=raw['id'],
# type='facebook',
# text=item_type.get_text_from(raw),
# image_dict=image,
# posted=cls.get_post_date(raw),
# original_data=raw,
# )
#
# Path: wagtailsocialfeed/utils/feed/instagram.py
# class InstagramFeed(AbstractFeed):
# item_cls = InstagramFeedItem
# query_cls = InstagramFeedQuery
#
# class InstagramFeedItem(FeedItem):
# """Implements instagram-specific behaviour"""
#
# @classmethod
# def get_post_date(cls, raw):
# if 'date' in raw:
# timestamp = None
# try:
# timestamp = float(raw['date'])
# except ValueError:
# return None
# return timezone.make_aware(
# datetime.datetime.fromtimestamp(timestamp), timezone=timezone.utc)
#
# return None
#
# @classmethod
# def from_raw(cls, raw):
# image = {}
# caption = None
# if 'display_src' in raw:
# image = {
# 'thumb': raw['thumbnail_resources'][1],
# 'small': raw['thumbnail_resources'][2],
# 'medium': raw['thumbnail_resources'][3],
# 'large': raw['thumbnail_resources'][4],
# 'original_link': "https://www.instagram.com/p/" + raw['code']
# }
#
# if 'caption' in raw:
# caption = raw['caption']
#
# return cls(
# id=raw['id'],
# type='instagram',
# text=caption,
# image_dict=image,
# posted=cls.get_post_date(raw),
# original_data=raw,
# )
#
# Path: wagtailsocialfeed/utils/feed/twitter.py
# class TwitterFeed(AbstractFeed):
# item_cls = TwitterFeedItem
# query_cls = TwitterFeedQuery
#
# class TwitterFeedItem(FeedItem):
# @classmethod
# def get_post_date(cls, raw):
# # Use the dateutil parser because on some platforms
# # python's own strptime doesn't support the %z directive.
# # Format: '%a %b %d %H:%M:%S %z %Y'
# return dateparser.parse(raw.get('created_at'))
#
# @classmethod
# def from_raw(cls, raw):
# image = None
# extended = raw.get('extended_entities', None)
# if extended:
# image = process_images(extended.get('media', None))
# date = cls.get_post_date(raw)
# return cls(
# id=raw['id'],
# type='twitter',
# text=raw['text'],
# image_dict=image,
# posted=date,
# original_data=raw
# )
. Output only the next line. | '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, FacebookFeedItem
from .instagram import InstagramFeed, InstagramFeedItem
from .twitter import TwitterFeed, TwitterFeedItem
and context from other files:
# Path: wagtailsocialfeed/utils/feed/facebook.py
# class FacebookFeed(AbstractFeed):
# item_cls = FacebookFeedItem
# query_cls = FacebookFeedQuery
#
# class FacebookFeedItem(FeedItem):
# """Implements facebook-specific behaviour."""
#
# @classmethod
# def get_post_date(cls, raw):
# if 'created_time' in raw:
# return dateparser.parse(raw.get('created_time'))
# return None
#
# @classmethod
# def from_raw(cls, raw):
# item_type = PostType(raw['type'])
# image = {}
# if 'picture' in raw:
# image = {
# 'thumb': {'url': raw['picture']},
# # 'small': raw['images']['low_resolution'],
# # 'medium': raw['images']['standard_resolution'],
# # 'largel': None,
# }
#
# return cls(
# id=raw['id'],
# type='facebook',
# text=item_type.get_text_from(raw),
# image_dict=image,
# posted=cls.get_post_date(raw),
# original_data=raw,
# )
#
# Path: wagtailsocialfeed/utils/feed/instagram.py
# class InstagramFeed(AbstractFeed):
# item_cls = InstagramFeedItem
# query_cls = InstagramFeedQuery
#
# class InstagramFeedItem(FeedItem):
# """Implements instagram-specific behaviour"""
#
# @classmethod
# def get_post_date(cls, raw):
# if 'date' in raw:
# timestamp = None
# try:
# timestamp = float(raw['date'])
# except ValueError:
# return None
# return timezone.make_aware(
# datetime.datetime.fromtimestamp(timestamp), timezone=timezone.utc)
#
# return None
#
# @classmethod
# def from_raw(cls, raw):
# image = {}
# caption = None
# if 'display_src' in raw:
# image = {
# 'thumb': raw['thumbnail_resources'][1],
# 'small': raw['thumbnail_resources'][2],
# 'medium': raw['thumbnail_resources'][3],
# 'large': raw['thumbnail_resources'][4],
# 'original_link': "https://www.instagram.com/p/" + raw['code']
# }
#
# if 'caption' in raw:
# caption = raw['caption']
#
# return cls(
# id=raw['id'],
# type='instagram',
# text=caption,
# image_dict=image,
# posted=cls.get_post_date(raw),
# original_data=raw,
# )
#
# Path: wagtailsocialfeed/utils/feed/twitter.py
# class TwitterFeed(AbstractFeed):
# item_cls = TwitterFeedItem
# query_cls = TwitterFeedQuery
#
# class TwitterFeedItem(FeedItem):
# @classmethod
# def get_post_date(cls, raw):
# # Use the dateutil parser because on some platforms
# # python's own strptime doesn't support the %z directive.
# # Format: '%a %b %d %H:%M:%S %z %Y'
# return dateparser.parse(raw.get('created_at'))
#
# @classmethod
# def from_raw(cls, raw):
# image = None
# extended = raw.get('extended_entities', None)
# if extended:
# image = process_images(extended.get('media', None))
# date = cls.get_post_date(raw)
# return cls(
# id=raw['id'],
# type='twitter',
# text=raw['text'],
# image_dict=image,
# posted=date,
# original_data=raw
# )
, which may contain function names, class names, or code. Output only the next line. | '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, FacebookFeedItem
from .instagram import InstagramFeed, InstagramFeedItem
from .twitter import TwitterFeed, TwitterFeedItem
and any relevant context from other files:
# Path: wagtailsocialfeed/utils/feed/facebook.py
# class FacebookFeed(AbstractFeed):
# item_cls = FacebookFeedItem
# query_cls = FacebookFeedQuery
#
# class FacebookFeedItem(FeedItem):
# """Implements facebook-specific behaviour."""
#
# @classmethod
# def get_post_date(cls, raw):
# if 'created_time' in raw:
# return dateparser.parse(raw.get('created_time'))
# return None
#
# @classmethod
# def from_raw(cls, raw):
# item_type = PostType(raw['type'])
# image = {}
# if 'picture' in raw:
# image = {
# 'thumb': {'url': raw['picture']},
# # 'small': raw['images']['low_resolution'],
# # 'medium': raw['images']['standard_resolution'],
# # 'largel': None,
# }
#
# return cls(
# id=raw['id'],
# type='facebook',
# text=item_type.get_text_from(raw),
# image_dict=image,
# posted=cls.get_post_date(raw),
# original_data=raw,
# )
#
# Path: wagtailsocialfeed/utils/feed/instagram.py
# class InstagramFeed(AbstractFeed):
# item_cls = InstagramFeedItem
# query_cls = InstagramFeedQuery
#
# class InstagramFeedItem(FeedItem):
# """Implements instagram-specific behaviour"""
#
# @classmethod
# def get_post_date(cls, raw):
# if 'date' in raw:
# timestamp = None
# try:
# timestamp = float(raw['date'])
# except ValueError:
# return None
# return timezone.make_aware(
# datetime.datetime.fromtimestamp(timestamp), timezone=timezone.utc)
#
# return None
#
# @classmethod
# def from_raw(cls, raw):
# image = {}
# caption = None
# if 'display_src' in raw:
# image = {
# 'thumb': raw['thumbnail_resources'][1],
# 'small': raw['thumbnail_resources'][2],
# 'medium': raw['thumbnail_resources'][3],
# 'large': raw['thumbnail_resources'][4],
# 'original_link': "https://www.instagram.com/p/" + raw['code']
# }
#
# if 'caption' in raw:
# caption = raw['caption']
#
# return cls(
# id=raw['id'],
# type='instagram',
# text=caption,
# image_dict=image,
# posted=cls.get_post_date(raw),
# original_data=raw,
# )
#
# Path: wagtailsocialfeed/utils/feed/twitter.py
# class TwitterFeed(AbstractFeed):
# item_cls = TwitterFeedItem
# query_cls = TwitterFeedQuery
#
# class TwitterFeedItem(FeedItem):
# @classmethod
# def get_post_date(cls, raw):
# # Use the dateutil parser because on some platforms
# # python's own strptime doesn't support the %z directive.
# # Format: '%a %b %d %H:%M:%S %z %Y'
# return dateparser.parse(raw.get('created_at'))
#
# @classmethod
# def from_raw(cls, raw):
# image = None
# extended = raw.get('extended_entities', None)
# if extended:
# image = process_images(extended.get('media', None))
# date = cls.get_post_date(raw)
# return cls(
# id=raw['id'],
# type='twitter',
# text=raw['text'],
# image_dict=image,
# posted=date,
# original_data=raw
# )
. Output only the next line. | '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': six.text_type(error_messages['no_original'])}
return JsonResponse(err, status=400)
original = request.POST['original']
item, created = config.moderated_items.get_or_create_for(original)
return JsonResponse({
'message': 'The post is now allowed on the feed',
'post_id': post_id,
'allowed': True
})
class ModerateRemoveView(View):
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(ModerateRemoveView, self).dispatch(*args, **kwargs)
def post(self, request, pk, post_id):
config = SocialFeedConfiguration.objects.get(pk=pk)
try:
item = config.moderated_items.get(external_id=post_id)
<|code_end|>
. Write the next line using the current file imports:
from django.http import JsonResponse
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View
from django.views.generic.detail import DetailView
from wagtail.wagtailadmin.forms import SearchForm
from .models import ModeratedItem, SocialFeedConfiguration
from .utils.feed.factory import FeedFactory
and context from other files:
# Path: wagtailsocialfeed/models.py
# class ModeratedItem(models.Model):
# config = models.ForeignKey(SocialFeedConfiguration,
# related_name='moderated_items',
# on_delete=models.CASCADE)
# moderated = models.DateTimeField(auto_now_add=True)
# posted = models.DateTimeField(blank=False, null=False)
#
# external_id = models.CharField(max_length=255,
# blank=False)
# content = models.TextField(blank=False)
#
# objects = ModeratedItemManager()
#
# class Meta:
# ordering = ['-posted', ]
#
# def __str__(self):
# return "{}<{}> ({} posted {})".format(
# self.__class__.__name__,
# self.type,
# self.external_id,
# self.posted
# )
#
# def get_content(self):
# if not hasattr(self, '_feeditem'):
# item_cls = FeedItemFactory.get_class(self.config.source)
# self._feeditem = item_cls.from_moderated(self)
# return self._feeditem
#
# @cached_property
# def type(self):
# return self.config.source
#
# class SocialFeedConfiguration(models.Model):
# FEED_CHOICES = (
# ('twitter', _('Twitter')),
# ('instagram', _('Instagram')),
# ('facebook', _('Facebook'))
# )
#
# source = models.CharField(_('Feed source'),
# max_length=100,
# choices=FEED_CHOICES,
# blank=False)
# username = models.CharField(_('User to track'),
# max_length=255,
# blank=False)
# moderated = models.BooleanField(default=False)
#
# def __str__(self):
# name = self.username
# if self.source == 'twitter':
# name = "@{}".format(self.username)
# return "{} ({})".format(self.source, name)
#
# Path: wagtailsocialfeed/utils/feed/factory.py
# class FeedFactory(object):
# @classmethod
# def create(cls, source):
# try:
# return FEED_CONFIG[source].feed()
# except KeyError:
# raise NotImplementedError(
# "Feed class for type '{}' not available".format(source))
, which may include functions, classes, or code. Output only the next line. | 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
"""
template_name = 'wagtailsocialfeed/admin/moderate.html'
<|code_end|>
using the current file's imports:
from django.http import JsonResponse
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View
from django.views.generic.detail import DetailView
from wagtail.wagtailadmin.forms import SearchForm
from .models import ModeratedItem, SocialFeedConfiguration
from .utils.feed.factory import FeedFactory
and any relevant context from other files:
# Path: wagtailsocialfeed/models.py
# class ModeratedItem(models.Model):
# config = models.ForeignKey(SocialFeedConfiguration,
# related_name='moderated_items',
# on_delete=models.CASCADE)
# moderated = models.DateTimeField(auto_now_add=True)
# posted = models.DateTimeField(blank=False, null=False)
#
# external_id = models.CharField(max_length=255,
# blank=False)
# content = models.TextField(blank=False)
#
# objects = ModeratedItemManager()
#
# class Meta:
# ordering = ['-posted', ]
#
# def __str__(self):
# return "{}<{}> ({} posted {})".format(
# self.__class__.__name__,
# self.type,
# self.external_id,
# self.posted
# )
#
# def get_content(self):
# if not hasattr(self, '_feeditem'):
# item_cls = FeedItemFactory.get_class(self.config.source)
# self._feeditem = item_cls.from_moderated(self)
# return self._feeditem
#
# @cached_property
# def type(self):
# return self.config.source
#
# class SocialFeedConfiguration(models.Model):
# FEED_CHOICES = (
# ('twitter', _('Twitter')),
# ('instagram', _('Instagram')),
# ('facebook', _('Facebook'))
# )
#
# source = models.CharField(_('Feed source'),
# max_length=100,
# choices=FEED_CHOICES,
# blank=False)
# username = models.CharField(_('User to track'),
# max_length=255,
# blank=False)
# moderated = models.BooleanField(default=False)
#
# def __str__(self):
# name = self.username
# if self.source == 'twitter':
# name = "@{}".format(self.username)
# return "{} ({})".format(self.source, name)
#
# Path: wagtailsocialfeed/utils/feed/factory.py
# class FeedFactory(object):
# @classmethod
# def create(cls, source):
# try:
# return FEED_CONFIG[source].feed()
# except KeyError:
# raise NotImplementedError(
# "Feed class for type '{}' not available".format(source))
. Output only the next line. | 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_name = 'wagtailsocialfeed/admin/moderate.html'
queryset = SocialFeedConfiguration.objects.filter(moderated=True)
def page_title(self):
return _('Moderating {}').format(self.object)
def get_search_form(self):
if 'q' in self.request.GET:
return SearchForm(self.request.GET, placeholder=_("Search posts"))
return SearchForm(placeholder=_("Search posts"))
def get_context_data(self, **kwargs):
context = super(ModerateView, self).get_context_data(**kwargs)
<|code_end|>
, generate the next line using the imports in this file:
from django.http import JsonResponse
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View
from django.views.generic.detail import DetailView
from wagtail.wagtailadmin.forms import SearchForm
from .models import ModeratedItem, SocialFeedConfiguration
from .utils.feed.factory import FeedFactory
and context (functions, classes, or occasionally code) from other files:
# Path: wagtailsocialfeed/models.py
# class ModeratedItem(models.Model):
# config = models.ForeignKey(SocialFeedConfiguration,
# related_name='moderated_items',
# on_delete=models.CASCADE)
# moderated = models.DateTimeField(auto_now_add=True)
# posted = models.DateTimeField(blank=False, null=False)
#
# external_id = models.CharField(max_length=255,
# blank=False)
# content = models.TextField(blank=False)
#
# objects = ModeratedItemManager()
#
# class Meta:
# ordering = ['-posted', ]
#
# def __str__(self):
# return "{}<{}> ({} posted {})".format(
# self.__class__.__name__,
# self.type,
# self.external_id,
# self.posted
# )
#
# def get_content(self):
# if not hasattr(self, '_feeditem'):
# item_cls = FeedItemFactory.get_class(self.config.source)
# self._feeditem = item_cls.from_moderated(self)
# return self._feeditem
#
# @cached_property
# def type(self):
# return self.config.source
#
# class SocialFeedConfiguration(models.Model):
# FEED_CHOICES = (
# ('twitter', _('Twitter')),
# ('instagram', _('Instagram')),
# ('facebook', _('Facebook'))
# )
#
# source = models.CharField(_('Feed source'),
# max_length=100,
# choices=FEED_CHOICES,
# blank=False)
# username = models.CharField(_('User to track'),
# max_length=255,
# blank=False)
# moderated = models.BooleanField(default=False)
#
# def __str__(self):
# name = self.username
# if self.source == 'twitter':
# name = "@{}".format(self.username)
# return "{} ({})".format(self.source, name)
#
# Path: wagtailsocialfeed/utils/feed/factory.py
# class FeedFactory(object):
# @classmethod
# def create(cls, source):
# try:
# return FEED_CONFIG[source].feed()
# except KeyError:
# raise NotImplementedError(
# "Feed class for type '{}' not available".format(source))
. Output only the next line. | 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.models import SocialFeedConfiguration, SocialFeedPage
and context (functions, classes, or occasionally code) from other files:
# Path: wagtailsocialfeed/models.py
# class SocialFeedConfiguration(models.Model):
# FEED_CHOICES = (
# ('twitter', _('Twitter')),
# ('instagram', _('Instagram')),
# ('facebook', _('Facebook'))
# )
#
# source = models.CharField(_('Feed source'),
# max_length=100,
# choices=FEED_CHOICES,
# blank=False)
# username = models.CharField(_('User to track'),
# max_length=255,
# blank=False)
# moderated = models.BooleanField(default=False)
#
# def __str__(self):
# name = self.username
# if self.source == 'twitter':
# name = "@{}".format(self.username)
# return "{} ({})".format(self.source, name)
#
# class SocialFeedPage(Page):
# feedconfig = models.ForeignKey(SocialFeedConfiguration,
# blank=True,
# null=True,
# on_delete=models.PROTECT,
# help_text=_("Leave blank to show all the feeds."))
#
# content_panels = Page.content_panels + [
# FieldPanel('feedconfig'),
# ]
#
# def get_context(self, request, *args, **kwargs):
# context = super(SocialFeedPage,
# self).get_context(request, *args, **kwargs)
# feed = None
# if self.feedconfig:
# feed = get_feed_items(self.feedconfig)
# else:
# feed = get_feed_items_mix(SocialFeedConfiguration.objects.all())
#
# context['feed'] = feed
# return context
. Output only the next line. | 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 = factory.Faker('word')
path = '0000'
depth = 0
feedconfig = factory.SubFactory(SocialFeedConfigurationFactory)
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
import factory
from wagtailsocialfeed.models import SocialFeedConfiguration, SocialFeedPage
and context (functions, classes, or occasionally code) from other files:
# Path: wagtailsocialfeed/models.py
# class SocialFeedConfiguration(models.Model):
# FEED_CHOICES = (
# ('twitter', _('Twitter')),
# ('instagram', _('Instagram')),
# ('facebook', _('Facebook'))
# )
#
# source = models.CharField(_('Feed source'),
# max_length=100,
# choices=FEED_CHOICES,
# blank=False)
# username = models.CharField(_('User to track'),
# max_length=255,
# blank=False)
# moderated = models.BooleanField(default=False)
#
# def __str__(self):
# name = self.username
# if self.source == 'twitter':
# name = "@{}".format(self.username)
# return "{} ({})".format(self.source, name)
#
# class SocialFeedPage(Page):
# feedconfig = models.ForeignKey(SocialFeedConfiguration,
# blank=True,
# null=True,
# on_delete=models.PROTECT,
# help_text=_("Leave blank to show all the feeds."))
#
# content_panels = Page.content_panels + [
# FieldPanel('feedconfig'),
# ]
#
# def get_context(self, request, *args, **kwargs):
# context = super(SocialFeedPage,
# self).get_context(request, *args, **kwargs)
# feed = None
# if self.feedconfig:
# feed = get_feed_items(self.feedconfig)
# else:
# feed = get_feed_items_mix(SocialFeedConfiguration.objects.all())
#
# context['feed'] = feed
# return context
. Output only the next line. | 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.encoding import smart_unicode
from dockit.core.serializers import base
from dockit.schema.loading import get_base_document
and context from other files:
# Path: dockit/core/serializers/base.py
# class Serializer(object):
# class Deserializer(object):
# class UnSet:
# class DeserializedObject(object):
# def serialize(self, queryset, **options):
# def start_serialization(self):
# def end_serialization(self):
# def start_object(self, obj):
# def end_object(self, obj):
# def getvalue(self):
# def __init__(self, stream_or_string, **options):
# def __iter__(self):
# def next(self):
# def __init__(self, obj, natural_key=UnSet):
# def __repr__(self):
# def save(self, enforce_natural_key=True):
#
# Path: dockit/schema/loading.py
# def get_base_document(self, key):
# if self.pending_documents and self.app_cache_ready():
# self.post_app_ready()
# return self.documents[key]
, which may contain function names, class names, or code. Output only the next line. | 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.collection),
"pk" : smart_unicode(obj._get_pk_val(), strings_only=True),
"natural_key": obj.natural_key,
"natural_key_hash": obj.natural_key_hash,
"fields" : self._current,
}
self.objects.append(entry)
self._current = None
def getvalue(self):
return self.objects
def Deserializer(object_list, **options):
"""
Deserialize simple Python objects back into Django ORM instances.
It's expected that you pass the Python objects themselves (instead of a
stream or a string) to the constructor
"""
#models.get_apps()
use_natural_keys = options.get('use_natural_keys', True)
for d in object_list:
# Look up the model and starting build a dict of data for it.
<|code_end|>
, generate the next line using the imports in this file:
from django.utils.encoding import smart_unicode
from dockit.core.serializers import base
from dockit.schema.loading import get_base_document
and context (functions, classes, or occasionally code) from other files:
# Path: dockit/core/serializers/base.py
# class Serializer(object):
# class Deserializer(object):
# class UnSet:
# class DeserializedObject(object):
# def serialize(self, queryset, **options):
# def start_serialization(self):
# def end_serialization(self):
# def start_object(self, obj):
# def end_object(self, obj):
# def getvalue(self):
# def __init__(self, stream_or_string, **options):
# def __iter__(self):
# def next(self):
# def __init__(self, obj, natural_key=UnSet):
# def __repr__(self):
# def save(self, enforce_natural_key=True):
#
# Path: dockit/schema/loading.py
# def get_base_document(self, key):
# if self.pending_documents and self.app_cache_ready():
# self.post_app_ready()
# return self.documents[key]
. Output only the next line. | 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)
def getvalue(self):
if callable(getattr(self.stream, 'getvalue', None)):
return self.stream.getvalue()
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
if isinstance(stream_or_string, basestring):
stream = StringIO(stream_or_string)
else:
stream = stream_or_string
<|code_end|>
. Use current file imports:
import datetime
import decimal
from StringIO import StringIO
from dockit.core.serializers.python import Serializer as PythonSerializer
from dockit.core.serializers.python import Deserializer as PythonDeserializer
from django.utils import datetime_safe
from django.utils import simplejson
and context (classes, functions, or code) from other files:
# Path: dockit/core/serializers/python.py
# class Serializer(base.Serializer):
# """
# Serializes a QuerySet to basic Python objects.
# """
#
# internal_use_only = True
#
# def start_serialization(self):
# self._current = None
# self.objects = []
#
# def end_serialization(self):
# pass
#
# def start_object(self, obj):
# self._current = obj.to_portable_primitive(obj)
# pk_field = obj._meta.get_id_field_name()
# 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.collection),
# "pk" : smart_unicode(obj._get_pk_val(), strings_only=True),
# "natural_key": obj.natural_key,
# "natural_key_hash": obj.natural_key_hash,
# "fields" : self._current,
# }
# self.objects.append(entry)
# self._current = None
#
# def getvalue(self):
# return self.objects
#
# Path: dockit/core/serializers/python.py
# def Deserializer(object_list, **options):
# """
# Deserialize simple Python objects back into Django ORM instances.
#
# It's expected that you pass the Python objects themselves (instead of a
# stream or a string) to the constructor
# """
# #models.get_apps()
# use_natural_keys = options.get('use_natural_keys', True)
# for d in object_list:
# # Look up the model and starting build a dict of data for it.
# doc_cls = get_base_document(d["collection"])
# data = d['fields']
# if use_natural_keys and 'natural_key' in d:
# data['@natural_key'] = d['natural_key']
# elif 'pk' in d:
# data[doc_cls._meta.pk.attname] = doc_cls._meta.pk.to_python(d["pk"])
#
# if 'natural_key' in d:
# yield base.DeserializedObject(doc_cls.to_python(data), natural_key=d['natural_key'])
# else:
# yield base.DeserializedObject(doc_cls.to_python(data))
. Output only the next line. | 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_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(kwargs.get("exclude", []))
exclude.extend(self.get_readonly_fields(request, obj))
# if exclude is an empty list we use None, since that's the actual
# default
exclude = exclude or None
defaults = {
"form": self.get_form_class(request, obj), #TODO this needs meta
"formset": self.formset,
"fields": fields,
"exclude": exclude,
"formfield_callback": curry(self.formfield_for_field, request=request, view=view), #view=None
"extra": self.extra,
"max_num": self.max_num,
"can_delete": self.can_delete,
"schema": self.schema,
}
defaults.update(kwargs)
<|code_end|>
, generate the next line using the imports in this file:
from documentadmin import SchemaAdmin
from django import forms
from django.contrib.admin.util import flatten_fieldsets
from django.utils.functional import curry
from dockit.forms.formsets import BaseInlineFormSet, inlinedocumentformset_factory
from django.conf import settings
from fields import DotPathField
and context (functions, classes, or occasionally code) from other files:
# Path: dockit/forms/formsets.py
# class BaseInlineFormSet(BaseDocumentFormSet): #simply merge as one?
# """A formset for child objects related to a parent."""
# def __init__(self, data=None, files=None, instance=None,
# save_as_new=False, prefix=None, dotpath=None):
# self.instance = instance
# self.save_as_new = save_as_new
# self.dotpath = dotpath or self.form._meta.dotpath
# self.singleton = False
# # is there a better way to get the object descriptor?
# qs = self.instance.dot_notation(self.base_dotpath) or []
# if not isinstance(qs, (list, set)):
# qs = [qs]
# self.singleton = True
# super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix,
# queryset=qs)
#
# @property
# def base_dotpath(self):
# return self.dotpath.rsplit('.', 1)[0]
#
# def initial_form_count(self):
# if self.save_as_new:
# return 0
# return super(BaseInlineFormSet, self).initial_form_count()
#
# def _construct_form(self, i, **kwargs):
# if self.singleton:
# kwargs['dotpath'] = self.base_dotpath
# else:
# kwargs['dotpath'] = '%s.%i' % (self.base_dotpath, i)
# kwargs['instance'] = self.instance
# form = super(BaseDocumentFormSet, self)._construct_form(i, **kwargs)
# if self.save_as_new:
# # Remove the primary key from the form's data, we are only
# # creating new instances
# #form.data[form.add_prefix(self._pk_field.name)] = None
#
# # Remove the foreign key from the form's data
# #form.data[form.add_prefix(self.fk.name)] = None
# pass
#
# # Set the fk value here so that the form can do it's validation.
# #?????
# #setattr(form.instance, self.fk.get_attname(), self.instance.pk)
# return form
#
# #def get_default_prefix(self):
# # return self.dotpath.rsplit('.', 1)[-1]
# #get_default_prefix = classmethod(get_default_prefix)
#
# def save_new(self, form, commit=True):
# """Saves and returns a new model instance for the given form."""
# return form._inner_save()
#
# def save_existing(self, form, instance, commit=True):
# """Saves and returns an existing model instance for the given form."""
# return form._inner_save()
#
# def save(self, commit=True, instance=None):
# """Saves model instances for every form, adding and changing instances
# as necessary, and returns the list of instances.
# """
# if instance:
# self.instance = instance
# if not commit:
# self.saved_forms = []
# def save_m2m():
# for form in self.saved_forms:
# form.save_m2m()
# self.save_m2m = save_m2m
# new_list = self.save_existing_objects(commit) + self.save_new_objects(commit)
# if commit:
# if self.singleton:
# self.instance.dot_notation_set_value(self.base_dotpath, new_list[0])
# else:
# self.instance.dot_notation_set_value(self.base_dotpath, new_list)
# return new_list
#
# def inlinedocumentformset_factory(document, dotpath, form=DocumentForm,
# formset=BaseInlineFormSet,
# fields=None, exclude=None, schema=None,
# extra=3, can_order=False, can_delete=True, max_num=None,
# formfield_callback=None):
# """
# Returns an ``InlineFormSet`` for the given kwargs.
#
# You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
# to ``parent_model``.
# """
# kwargs = {
# 'form': form,
# 'formfield_callback': formfield_callback,
# 'formset': formset,
# 'extra': extra,
# 'can_delete': can_delete,
# 'can_order': can_order,
# 'fields': fields,
# 'exclude': exclude,
# 'max_num': max_num,
# 'schema': schema,
# 'dotpath': dotpath + '.*',
# }
# FormSet = documentformset_factory(document, **kwargs)
# #FormSet.fk = fk
# return FormSet
. Output only the next line. | 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 is a prefix!
dotpath = '.'.join(path_parts)
json_value = self.prep_value(value)
data_attrs = self.build_attrs(attrs, type='hidden', name=name, value=json_value)
data_html = mark_safe(u'<input%s />' % flatatt(data_attrs))
if isinstance(value, list):
rows = list()
index = -1
for index, item in enumerate(value):
item_dotpath = '%s.%s' % (dotpath, index)
butn_html = self.render_button(item_dotpath, edit=True)
rows.append('<td>%s</td><td>%s</td>' % (self.get_label(item_dotpath, item), butn_html))
item_dotpath = '%s.%s' % (dotpath, index+1)
butn_html = self.render_button(item_dotpath)
rows.append('<td>%s</td><td>%s</td>' % (self.get_label(item_dotpath), butn_html))
return mark_safe('%s<table><tr>%s</tr></table>' % (data_html, '</tr><tr>'.join(rows)))
else:
butn_html = self.render_button(dotpath, edit=bool(value))
desc_html = self.get_label(dotpath, value)
return mark_safe(''.join((data_html, desc_html, butn_html)))
<|code_end|>
. Write the next line using the current file imports:
from django.forms import widgets
from django.utils.encoding import force_unicode
from django.forms.util import flatatt
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils import simplejson as json
from dockit.forms.fields import HiddenJSONField
from urllib import urlencode
and context from other files:
# Path: dockit/forms/fields.py
# class HiddenJSONField(Field):
# widget = HiddenInput
#
# 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?
# return None
#
# def validate(self, value):
# return Field.validate(self, value)
#
# def prepare_value(self, value):
# if hasattr(value, 'to_primitive'):
# return json.dumps(type(value).to_primitive(value))
# return Field.prepare_value(self, value)
, which may include functions, classes, or code. Output only the next line. | 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=commit))
if not commit:
self.saved_forms.append(form)
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
# object.
if self.can_delete and self._should_delete_form(form):
continue
self.new_objects.append(self.save_new(form, commit=commit))
if not commit:
self.saved_forms.append(form)
return self.new_objects
def add_fields(self, form, index):
#CONSIDER there is no parent object, more like a document/instance and a dotpath
"""Add a hidden field for the object's primary key."""
#TODO
super(BaseDocumentFormSet, self).add_fields(form, index)
<|code_end|>
, generate the next line using the imports in this file:
from django.forms.formsets import BaseFormSet, formset_factory
from django.utils.translation import ugettext_lazy as _, ugettext
from dockit.forms.forms import DocumentForm, documentform_factory
and context (functions, classes, or occasionally code) from other files:
# Path: dockit/forms/forms.py
# class DocumentForm(BaseDocumentForm):
# """ The document form object """
# __metaclass__ = DocumentFormMetaClass
#
# def documentform_factory(document, form=DocumentForm, fields=None, exclude=None,
# formfield_callback=None, schema=None, dotpath=None):
# meta = UserMeta(document=document,
# fields=fields,
# exclude=exclude,
# formfield_callback=formfield_callback,
# schema=schema,
# dotpath=dotpath,)
# class FactoryForm(form):
# Meta = meta
#
# return FactoryForm
. Output only the next line. | 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
# object.
if self.can_delete and self._should_delete_form(form):
continue
self.new_objects.append(self.save_new(form, commit=commit))
if not commit:
self.saved_forms.append(form)
return self.new_objects
def add_fields(self, form, index):
#CONSIDER there is no parent object, more like a document/instance and a dotpath
"""Add a hidden field for the object's primary key."""
#TODO
super(BaseDocumentFormSet, self).add_fields(form, index)
def documentformset_factory(document, form=DocumentForm, formfield_callback=None,
formset=BaseDocumentFormSet,
dotpath=None, schema=None,
extra=1, can_delete=False, can_order=False,
max_num=None, fields=None, exclude=None):
"""
Returns a FormSet class for the given Document class.
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.forms.formsets import BaseFormSet, formset_factory
from django.utils.translation import ugettext_lazy as _, ugettext
from dockit.forms.forms import DocumentForm, documentform_factory
and context:
# Path: dockit/forms/forms.py
# class DocumentForm(BaseDocumentForm):
# """ The document form object """
# __metaclass__ = DocumentFormMetaClass
#
# def documentform_factory(document, form=DocumentForm, fields=None, exclude=None,
# formfield_callback=None, schema=None, dotpath=None):
# meta = UserMeta(document=document,
# fields=fields,
# exclude=exclude,
# formfield_callback=formfield_callback,
# schema=schema,
# dotpath=dotpath,)
# class FactoryForm(form):
# Meta = meta
#
# return FactoryForm
which might include code, classes, or functions. Output only the next line. | 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':data,
'field':field,
'part':None,}
self.resolved_paths = [entry]
self._resolve_loop()
def _resolve_loop(self):
while not self._finished:
self._called = False
self.resolve_next()
if not self._called:
assert False, str(self.resolved_paths)
#need a better control routine, want one last resolve if end wasn't called
def resolve_next(self):
current = self.current
if current['field'] is None:
if hasattr(current['value'], 'traverse_dot_path'):
current['value'].traverse_dot_path(self)
#note the result may or may not have a field
elif self.remaining_paths:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dockit.schema.exceptions import DotPathNotFound
from dockit.schema.fields import SchemaField
from dockit.schema.fields import SchemaField
from dockit.schema.fields import DictField, SchemaField
from dockit.schema.fields import SchemaField
from dockit.schema.schema import Schema
and context:
# Path: dockit/schema/exceptions.py
# class DotPathNotFound(Exception):
# def __init__(self, message, traverser=None):
# Exception.__init__(self, message)
# self.traverser = traverser
which might include code, classes, or functions. Output only the next line. | 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_primitive(self):
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={'charfield':'charmander'})
py_obj = obj.to_python({'charfield':'charmander'})
self.assertEqual(obj._primitive_data, py_obj._primitive_data)
def test_from_portable_primitive(self):
obj = SimpleSchema(_primitive_data={'charfield':'charmander'})
assert obj.charfield, 'Failed to initialize python data'
py_obj = obj.to_python({'charfield':'charmander'})
py_obj.normalize_portable_primitives()
self.assertEqual(obj._primitive_data, py_obj._primitive_data)
def test_traverse(self):
obj = SimpleSchema(charfield='charmander')
self.assertEqual(obj.dot_notation('charfield'), 'charmander')
def test_natural_key_creation(self):
<|code_end|>
. Use current file imports:
from django.utils import unittest
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from dockit.tests.schema.common import SimpleSchema, SimpleDocument, ValidatingDocument, SimpleSchema2
and context (classes, functions, or code) from other files:
# Path: dockit/tests/schema/common.py
# class SimpleSchema(schema.Schema): #TODO make a more complex testcase
# charfield = schema.CharField()
#
# class SimpleDocument(schema.Document): #TODO make a more complex testcase
# charfield = schema.CharField()
#
# class ValidatingDocument(schema.Document):
# with_choices = schema.CharField(choices=[('a','a'), ('b', 'b')])
# not_null = schema.CharField(null=False)
# allow_blank = schema.CharField(blank=True)
# not_blank = schema.CharField(blank=False)
# subschema = schema.SchemaField(SimpleSchema, null=False)
# allow_null = schema.CharField(blank=True, null=True)
#
# class SimpleSchema2(schema.Schema):
# otherfield = schema.CharField()
. Output only the next line. | 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={'charfield':'charmander'})
py_obj = obj.to_python({'charfield':'charmander'})
self.assertEqual(obj._primitive_data, py_obj._primitive_data)
def test_from_portable_primitive(self):
obj = SimpleSchema(_primitive_data={'charfield':'charmander'})
assert obj.charfield, 'Failed to initialize python data'
py_obj = obj.to_python({'charfield':'charmander'})
py_obj.normalize_portable_primitives()
self.assertEqual(obj._primitive_data, py_obj._primitive_data)
def test_traverse(self):
obj = SimpleSchema(charfield='charmander')
self.assertEqual(obj.dot_notation('charfield'), 'charmander')
def test_natural_key_creation(self):
obj = SimpleDocument()
obj.save()
self.assertTrue('@natural_key' in obj._primitive_data)
self.assertTrue('@natural_key_hash' in obj._primitive_data)
self.assertTrue(isinstance(obj._primitive_data['@natural_key'], dict))
self.assertTrue(None not in obj._primitive_data['@natural_key'].values())
class DocumentValidationTestChase(unittest.TestCase):
def test_validation(self):
<|code_end|>
with the help of current file imports:
from django.utils import unittest
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from dockit.tests.schema.common import SimpleSchema, SimpleDocument, ValidatingDocument, SimpleSchema2
and context from other files:
# Path: dockit/tests/schema/common.py
# class SimpleSchema(schema.Schema): #TODO make a more complex testcase
# charfield = schema.CharField()
#
# class SimpleDocument(schema.Document): #TODO make a more complex testcase
# charfield = schema.CharField()
#
# class ValidatingDocument(schema.Document):
# with_choices = schema.CharField(choices=[('a','a'), ('b', 'b')])
# not_null = schema.CharField(null=False)
# allow_blank = schema.CharField(blank=True)
# not_blank = schema.CharField(blank=False)
# subschema = schema.SchemaField(SimpleSchema, null=False)
# allow_null = schema.CharField(blank=True, null=True)
#
# class SimpleSchema2(schema.Schema):
# otherfield = schema.CharField()
, which may contain function names, class names, or code. Output only the next line. | 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.allow_blank = ''
obj.not_blank = ''
try:
obj.subschema = 'Not a schema'
except ValidationError as error:
pass
else:
self.fail('Setting a subschema should evaluate immediately')
try:
obj.full_clean()
except ValidationError as error:
self.assertFalse('not_null' in error.message_dict, str(error))
self.assertFalse('allow_blank' in error.message_dict, str(error))
self.assertTrue('with_choices' in error.message_dict, str(error))
self.assertTrue('not_blank' in error.message_dict, str(error))
self.assertTrue('subschema' in error.message_dict, str(error))
else:
self.fail('Validation is broken')
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.utils import unittest
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from dockit.tests.schema.common import SimpleSchema, SimpleDocument, ValidatingDocument, SimpleSchema2
and context:
# Path: dockit/tests/schema/common.py
# class SimpleSchema(schema.Schema): #TODO make a more complex testcase
# charfield = schema.CharField()
#
# class SimpleDocument(schema.Document): #TODO make a more complex testcase
# charfield = schema.CharField()
#
# class ValidatingDocument(schema.Document):
# with_choices = schema.CharField(choices=[('a','a'), ('b', 'b')])
# not_null = schema.CharField(null=False)
# allow_blank = schema.CharField(blank=True)
# not_blank = schema.CharField(blank=False)
# subschema = schema.SchemaField(SimpleSchema, null=False)
# allow_null = schema.CharField(blank=True, null=True)
#
# class SimpleSchema2(schema.Schema):
# otherfield = schema.CharField()
which might include code, classes, or functions. Output only the next line. | 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]
documents = obj.get_document().objects.all()
for doc in documents:
self.evaluate_query_index(obj, query_index, doc.pk, doc.to_primitive(doc))
def on_save(self, collection, doc_id, data):
index_router = get_index_router()
if collection not in index_router.registered_querysets:
return #no querysets have been registered
registered_queries = self.filter(collection=collection)
for query in registered_queries:
if query.query_hash not in index_router.registered_querysets[collection]:
continue #TODO stale index, perhaps we should remove
query_index = index_router.registered_querysets[collection][query.query_hash]
self.evaluate_query_index(query, query_index, doc_id, data)
def on_delete(self, collection, doc_id):
RegisteredIndexDocument.objects.filter(index__collection=collection, doc_id=doc_id).delete()
def evaluate_query_index(self, registered_index, query_index, doc_id, data):
schema = query_index.document
#evaluate if document passes filters
for inclusion in query_index.inclusions:
dotpath = inclusion.dotpath()
<|code_end|>
. Use current file imports:
from django.db import models
from django.utils import simplejson
from django.core.serializers.json import DjangoJSONEncoder
from django.core.exceptions import ObjectDoesNotExist
from dockit.schema.common import DotPathTraverser, DotPathNotFound
from dockit.backends import get_index_router
from dockit.backends import get_index_router
from dockit.backends.djangodocument.models import RegisteredIndexDocument
from dockit.backends.djangodocument.models import RegisteredIndexDocument
from dockit.schema import Document
and context (classes, functions, or code) from other files:
# Path: dockit/schema/common.py
# class UnSet(object):
# class DotPathTraverser(object):
# class DotPathList(list):
# class DotPathDict(dict):
# class DotPathSet(set):
# class GenericDotPathObject(object):
# def __nonzero__(self):
# def __init__(self, dotpath):
# def resolve_for_schema(self, schema):
# def resolve_for_instance(self, instance):
# def resolve_for_raw_data(self, data, schema=None):
# def _resolve_loop(self):
# def resolve_next(self):
# def next_part(self):
# def current(self):
# def current_value(self):
# def current_field(self):
# def end(self, field=None, value=None):
# def next(self, field=None, value=None):
# def set_value(self, value):
# def traverse_dot_path(self, traverser):
# def set_value(self, attr, value):
# def traverse_dot_path(self, traverser):
# def set_value(self, attr, value):
# def traverse_dot_path(self, traverser):
# def set_value(self, attr, value):
# def __init__(self, value):
# def traverse_dot_path(self, traverser):
. Output only the next line. | 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 on_save(self, collection, doc_id, data):
index_router = get_index_router()
if collection not in index_router.registered_querysets:
return #no querysets have been registered
registered_queries = self.filter(collection=collection)
for query in registered_queries:
if query.query_hash not in index_router.registered_querysets[collection]:
continue #TODO stale index, perhaps we should remove
query_index = index_router.registered_querysets[collection][query.query_hash]
self.evaluate_query_index(query, query_index, doc_id, data)
def on_delete(self, collection, doc_id):
RegisteredIndexDocument.objects.filter(index__collection=collection, doc_id=doc_id).delete()
def evaluate_query_index(self, registered_index, query_index, doc_id, data):
schema = query_index.document
#evaluate if document passes filters
for inclusion in query_index.inclusions:
dotpath = inclusion.dotpath()
traverser = DotPathTraverser(dotpath)
try:
traverser.resolve_for_raw_data(data, schema=schema)
<|code_end|>
. Use current file imports:
from django.db import models
from django.utils import simplejson
from django.core.serializers.json import DjangoJSONEncoder
from django.core.exceptions import ObjectDoesNotExist
from dockit.schema.common import DotPathTraverser, DotPathNotFound
from dockit.backends import get_index_router
from dockit.backends import get_index_router
from dockit.backends.djangodocument.models import RegisteredIndexDocument
from dockit.backends.djangodocument.models import RegisteredIndexDocument
from dockit.schema import Document
and context (classes, functions, or code) from other files:
# Path: dockit/schema/common.py
# class UnSet(object):
# class DotPathTraverser(object):
# class DotPathList(list):
# class DotPathDict(dict):
# class DotPathSet(set):
# class GenericDotPathObject(object):
# def __nonzero__(self):
# def __init__(self, dotpath):
# def resolve_for_schema(self, schema):
# def resolve_for_instance(self, instance):
# def resolve_for_raw_data(self, data, schema=None):
# def _resolve_loop(self):
# def resolve_next(self):
# def next_part(self):
# def current(self):
# def current_value(self):
# def current_field(self):
# def end(self, field=None, value=None):
# def next(self, field=None, value=None):
# def set_value(self, value):
# def traverse_dot_path(self, traverser):
# def set_value(self, attr, value):
# def traverse_dot_path(self, traverser):
# def set_value(self, attr, value):
# def traverse_dot_path(self, traverser):
# def set_value(self, attr, value):
# def __init__(self, value):
# def traverse_dot_path(self, traverser):
. Output only the next line. | 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=[], exclusions=[], indexes=[]):
new_index = type(self)(self.document)
new_index.inclusions = self.inclusions + inclusions
new_index.exclusions = self.exclusions + exclusions
new_index.indexes = self.indexes + indexes
return new_index
def _clone(self):
return self._add_filter_parts()
def _pk_only(self):
for inclusion in self.inclusions:
if inclusion.key != 'pk' or inclusion.operation != 'exact':
return False
for exclusion in self.exclusions:
if exclusion.key != 'pk' or exclusion.operation != 'exact':
return False
return True
def _build_queryset(self):
if (not self._pk_only() and (self.inclusions or self.exclusions or self.indexes)):
backend = self.document._meta.get_index_backend_for_read(self)
else:
backend = self.document._meta.get_document_backend_for_read()
query = backend.get_query(self)
<|code_end|>
, predict the next line using imports from the current file:
import copy
import hashlib
import json
from dockit.backends.queryset import QuerySet
from dockit.schema import Document
from django.db.models import Model
from dockit.schema.loading import register_indexes
from dockit.backends import get_index_router
and context including class names, function names, and sometimes code from other files:
# Path: dockit/backends/queryset.py
# class QuerySet(object):
# '''
# Acts as a caching layer around an implemented `BaseDocumentQuery`
# TODO: implement actual caching
# '''
# def __init__(self, query):
# self.query = query
#
# @property
# def document(self):
# return self.query.document
#
# def __len__(self):
# #TODO cache
# return self.query.__len__()
#
# def count(self):
# return self.__len__()
#
# def delete(self):
# return self.query.delete()
#
# def values(self, *limit_to, **kwargs):
# #TODO cache
# return self.query.values(*limit_to, **kwargs)
#
# def get(self, **kwargs):
# #TODO cache
# return self.query.get(**kwargs)
#
# def exists(self):
# return self.query.exists()
#
# def __getitem__(self, val):
# #TODO cache
# return self.query.__getitem__(val)
#
# def __nonzero__(self):
# #TODO cache
# return self.query.__nonzero__()
#
# def __iter__(self):
# return iter(self.query)
. Output only the next line. | 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=None, exclude=None, dotpath=None):
"""
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``properties`` is an optional list of properties names. If provided,
only the named properties will be included in the returned dict.
``exclude`` is an optional list of properties names. If provided, the named
properties will be excluded from the returned dict, even if they are listed
in the ``properties`` argument.
"""
# avoid a circular import
data = {}
if dotpath:
try:
src_data = instance.dot_notation(dotpath)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.utils.datastructures import SortedDict
from django.forms.util import ErrorList
from django.forms.forms import BaseForm, get_declared_fields, ValidationError
from django.forms.widgets import media_property
from dockit.schema.exceptions import DotPathNotFound
import inspect
and context (classes, functions, sometimes code) from other files:
# Path: dockit/schema/exceptions.py
# class DotPathNotFound(Exception):
# def __init__(self, message, traverser=None):
# Exception.__init__(self, message)
# self.traverser = traverser
. Output only the next line. | 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 None:
# If a document has been explicitly provided, use it
document = self.document
elif hasattr(self, 'object') and self.object is not None:
# If this view is operating on a single object, use
# the class of that object
document = self.object.__class__
else:
# Try to get a queryset and extract the document class
# from that
document = self.get_queryset().document
#fields = fields_for_document(document)
<|code_end|>
. Use current file imports:
(from django.core.exceptions import ImproperlyConfigured
from django.views.generic import edit as editview
from detail import SingleObjectMixin, SingleObjectTemplateResponseMixin, BaseDetailView
from dockit.forms import DocumentForm)
and context including class names, function names, or small code snippets from other files:
# Path: dockit/forms/forms.py
# class DocumentForm(BaseDocumentForm):
# """ The document form object """
# __metaclass__ = DocumentFormMetaClass
. Output only the next line. | 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
update = views.UpdateView
delete = views.DeleteView
history = views.HistoryView
select_schema = views.SchemaTypeSelectionView
field_list_index = views.ListFieldIndexView
raw_id_fields = ()
fields = None
exclude = []
fieldsets = None
form = forms.ModelForm #only for legacy purposes, remove this and django admin complains
form_class = None
filter_vertical = ()
filter_horizontal = ()
radio_fields = {}
prepopulated_fields = {}
formfield_overrides = {}
readonly_fields = ()
declared_fieldsets = None
save_as = False
save_on_top = False
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls.defaults import patterns, url
from django.utils.functional import update_wrapper
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.contrib.admin import widgets
from django.contrib.admin.options import get_ul_class
from django.contrib.contenttypes.models import ContentType
from django import forms
from dockit.paginator import Paginator
from dockit.forms import DocumentForm
from dockit.forms.fields import PrimitiveListField, HiddenJSONField
from dockit.models import DockitPermission
from widgets import AdminPrimitiveListWidget
from breadcrumbs import Breadcrumb
from objecttools import LinkObjectTool
from django.conf import settings
from django import forms
from inlines import StackedInline
from dockit import schema
from fields import TypedSchemaField
from fields import DotPathField
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from dockit.schema.common import DotPathTraverser
from changelist import ChangeList
from django.core.urlresolvers import get_urlconf, get_resolver
from django.contrib.admin.models import LogEntry, ADDITION
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.admin.models import LogEntry, DELETION
import views
and context from other files:
# Path: dockit/paginator.py
#
# Path: dockit/forms/forms.py
# class DocumentForm(BaseDocumentForm):
# """ The document form object """
# __metaclass__ = DocumentFormMetaClass
#
# Path: dockit/forms/fields.py
# class PrimitiveListField(Field):
# '''
# Wraps around a subfield
# The widget receives the subfield and is responsible for rendering multiple iterations of the subfield and collecting of data
# '''
# widget = PrimitiveListWidget
#
# def __init__(self, subfield, *args, **kwargs):
# self.subfield = subfield
# widget = kwargs.get('widget', self.widget)
# if isinstance(widget, type):
# widget = widget(subfield)
# kwargs['widget'] = widget
# super(PrimitiveListField, self).__init__(*args, **kwargs)
#
# def prepare_value(self, value):
# if value is None:
# return
# ret = list()
# for val in value:
# ret.append(self.subfield.prepare_value(val))
# return ret
#
# def bound_data(self, data, initial):
# ret = list()
# for data_item, initial_item in zip(data, initial):
# ret.append(self.subfield.bound_data(data_item, initial_item))
# return ret
#
# def clean(self, data, initial=None):
# ret = list()
# for i, data_item in enumerate(data):
# if data_item.get('DELETE', False):
# continue
# if initial and len(initial) > i:
# initial_item = initial[i]
# else:
# initial_item = None
# val = self.subfield.bound_data(data_item['value'], initial_item)
#
# arg_spec = inspect.getargspec(self.subfield.clean)
# try:
# if len(arg_spec.args) > 2:
# val = self.subfield.clean(val, initial_item)
# else:
# val = self.subfield.clean(val)
# except ValidationError:
# if val:
# raise
# else:
# if val:
# ret.append((val, data_item.get('ORDER', None)))
#
# def compare_ordering_key(k):
# if k[1] is None:
# return (1, 0) # +infinity, larger than any number
# return (0, k[1])
#
# ret.sort(key=compare_ordering_key)
# return [item[0] for item in ret]
#
# class HiddenJSONField(Field):
# widget = HiddenInput
#
# 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?
# return None
#
# def validate(self, value):
# return Field.validate(self, value)
#
# def prepare_value(self, value):
# if hasattr(value, 'to_primitive'):
# return json.dumps(type(value).to_primitive(value))
# return Field.prepare_value(self, value)
#
# Path: dockit/models.py
# class DockitPermission(models.Model):
# pass #a content type is required for creating permissions
, which may include functions, classes, or code. Output only the next line. | 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))
def get_field_list_index_view(self, **kwargs):
params = self.get_view_kwargs()
params.update(kwargs)
return self.as_view(self.field_list_index.as_view(**params))
def get_model_perms(self, request):
return {
'add': self.has_add_permission(request),
'change': self.has_change_permission(request),
'delete': self.has_delete_permission(request),
}
def queryset(self, request):
return self.model.objects.all()
def get_form_class(self, request, obj=None):
"""
Returns the form class to use in this view
"""
if self.form_class:
return self.form_class
else:
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls.defaults import patterns, url
from django.utils.functional import update_wrapper
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.contrib.admin import widgets
from django.contrib.admin.options import get_ul_class
from django.contrib.contenttypes.models import ContentType
from django import forms
from dockit.paginator import Paginator
from dockit.forms import DocumentForm
from dockit.forms.fields import PrimitiveListField, HiddenJSONField
from dockit.models import DockitPermission
from widgets import AdminPrimitiveListWidget
from breadcrumbs import Breadcrumb
from objecttools import LinkObjectTool
from django.conf import settings
from django import forms
from inlines import StackedInline
from dockit import schema
from fields import TypedSchemaField
from fields import DotPathField
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from dockit.schema.common import DotPathTraverser
from changelist import ChangeList
from django.core.urlresolvers import get_urlconf, get_resolver
from django.contrib.admin.models import LogEntry, ADDITION
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.admin.models import LogEntry, DELETION
import views
and context from other files:
# Path: dockit/paginator.py
#
# Path: dockit/forms/forms.py
# class DocumentForm(BaseDocumentForm):
# """ The document form object """
# __metaclass__ = DocumentFormMetaClass
#
# Path: dockit/forms/fields.py
# class PrimitiveListField(Field):
# '''
# Wraps around a subfield
# The widget receives the subfield and is responsible for rendering multiple iterations of the subfield and collecting of data
# '''
# widget = PrimitiveListWidget
#
# def __init__(self, subfield, *args, **kwargs):
# self.subfield = subfield
# widget = kwargs.get('widget', self.widget)
# if isinstance(widget, type):
# widget = widget(subfield)
# kwargs['widget'] = widget
# super(PrimitiveListField, self).__init__(*args, **kwargs)
#
# def prepare_value(self, value):
# if value is None:
# return
# ret = list()
# for val in value:
# ret.append(self.subfield.prepare_value(val))
# return ret
#
# def bound_data(self, data, initial):
# ret = list()
# for data_item, initial_item in zip(data, initial):
# ret.append(self.subfield.bound_data(data_item, initial_item))
# return ret
#
# def clean(self, data, initial=None):
# ret = list()
# for i, data_item in enumerate(data):
# if data_item.get('DELETE', False):
# continue
# if initial and len(initial) > i:
# initial_item = initial[i]
# else:
# initial_item = None
# val = self.subfield.bound_data(data_item['value'], initial_item)
#
# arg_spec = inspect.getargspec(self.subfield.clean)
# try:
# if len(arg_spec.args) > 2:
# val = self.subfield.clean(val, initial_item)
# else:
# val = self.subfield.clean(val)
# except ValidationError:
# if val:
# raise
# else:
# if val:
# ret.append((val, data_item.get('ORDER', None)))
#
# def compare_ordering_key(k):
# if k[1] is None:
# return (1, 0) # +infinity, larger than any number
# return (0, k[1])
#
# ret.sort(key=compare_ordering_key)
# return [item[0] for item in ret]
#
# class HiddenJSONField(Field):
# widget = HiddenInput
#
# 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?
# return None
#
# def validate(self, value):
# return Field.validate(self, value)
#
# def prepare_value(self, value):
# if hasattr(value, 'to_primitive'):
# return json.dumps(type(value).to_primitive(value))
# return Field.prepare_value(self, value)
#
# Path: dockit/models.py
# class DockitPermission(models.Model):
# pass #a content type is required for creating permissions
, which may include functions, classes, or code. Output only the next line. | 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
#TODO self.raw_id_fields
#TODO ForeignKeyRawIdWidget => DocumentReferenceRawIdWidget
if prop.name in self.raw_id_fields:
if isinstance(prop, schema.ReferenceField):
pass
elif isinstance(prop, schema.ModelReferenceField):
pass
if (isinstance(base_property, schema.TypedSchemaField) or
(isinstance(base_property, schema.SchemaField) and base_property.schema._meta.typed_field)):
field = TypedSchemaField
kwargs['dotpath'] = view.dotpath()
kwargs['params'] = request.GET.copy()
if isinstance(base_property, schema.SchemaField):
type_selector = base_property.schema._meta.fields[base_property.schema._meta.typed_field]
else:
type_selector = base_property
kwargs['schema_property'] = type_selector
if view.next_dotpath():
kwargs['required'] = False
return field(**kwargs)
if issubclass(field, HiddenJSONField):
return self.formfield_for_jsonfield(prop, field, view, request=request, **kwargs)
<|code_end|>
using the current file's imports:
from django.conf.urls.defaults import patterns, url
from django.utils.functional import update_wrapper
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.contrib.admin import widgets
from django.contrib.admin.options import get_ul_class
from django.contrib.contenttypes.models import ContentType
from django import forms
from dockit.paginator import Paginator
from dockit.forms import DocumentForm
from dockit.forms.fields import PrimitiveListField, HiddenJSONField
from dockit.models import DockitPermission
from widgets import AdminPrimitiveListWidget
from breadcrumbs import Breadcrumb
from objecttools import LinkObjectTool
from django.conf import settings
from django import forms
from inlines import StackedInline
from dockit import schema
from fields import TypedSchemaField
from fields import DotPathField
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from dockit.schema.common import DotPathTraverser
from changelist import ChangeList
from django.core.urlresolvers import get_urlconf, get_resolver
from django.contrib.admin.models import LogEntry, ADDITION
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.admin.models import LogEntry, DELETION
import views
and any relevant context from other files:
# Path: dockit/paginator.py
#
# Path: dockit/forms/forms.py
# class DocumentForm(BaseDocumentForm):
# """ The document form object """
# __metaclass__ = DocumentFormMetaClass
#
# Path: dockit/forms/fields.py
# class PrimitiveListField(Field):
# '''
# Wraps around a subfield
# The widget receives the subfield and is responsible for rendering multiple iterations of the subfield and collecting of data
# '''
# widget = PrimitiveListWidget
#
# def __init__(self, subfield, *args, **kwargs):
# self.subfield = subfield
# widget = kwargs.get('widget', self.widget)
# if isinstance(widget, type):
# widget = widget(subfield)
# kwargs['widget'] = widget
# super(PrimitiveListField, self).__init__(*args, **kwargs)
#
# def prepare_value(self, value):
# if value is None:
# return
# ret = list()
# for val in value:
# ret.append(self.subfield.prepare_value(val))
# return ret
#
# def bound_data(self, data, initial):
# ret = list()
# for data_item, initial_item in zip(data, initial):
# ret.append(self.subfield.bound_data(data_item, initial_item))
# return ret
#
# def clean(self, data, initial=None):
# ret = list()
# for i, data_item in enumerate(data):
# if data_item.get('DELETE', False):
# continue
# if initial and len(initial) > i:
# initial_item = initial[i]
# else:
# initial_item = None
# val = self.subfield.bound_data(data_item['value'], initial_item)
#
# arg_spec = inspect.getargspec(self.subfield.clean)
# try:
# if len(arg_spec.args) > 2:
# val = self.subfield.clean(val, initial_item)
# else:
# val = self.subfield.clean(val)
# except ValidationError:
# if val:
# raise
# else:
# if val:
# ret.append((val, data_item.get('ORDER', None)))
#
# def compare_ordering_key(k):
# if k[1] is None:
# return (1, 0) # +infinity, larger than any number
# return (0, k[1])
#
# ret.sort(key=compare_ordering_key)
# return [item[0] for item in ret]
#
# class HiddenJSONField(Field):
# widget = HiddenInput
#
# 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?
# return None
#
# def validate(self, value):
# return Field.validate(self, value)
#
# def prepare_value(self, value):
# if hasattr(value, 'to_primitive'):
# return json.dumps(type(value).to_primitive(value))
# return Field.prepare_value(self, value)
#
# Path: dockit/models.py
# class DockitPermission(models.Model):
# pass #a content type is required for creating permissions
. Output only the next line. | 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_property = prop
if isinstance(prop, schema.ListField):
base_property = prop.subfield
#TODO self.raw_id_fields
#TODO ForeignKeyRawIdWidget => DocumentReferenceRawIdWidget
if prop.name in self.raw_id_fields:
if isinstance(prop, schema.ReferenceField):
pass
elif isinstance(prop, schema.ModelReferenceField):
pass
if (isinstance(base_property, schema.TypedSchemaField) or
(isinstance(base_property, schema.SchemaField) and base_property.schema._meta.typed_field)):
field = TypedSchemaField
kwargs['dotpath'] = view.dotpath()
kwargs['params'] = request.GET.copy()
if isinstance(base_property, schema.SchemaField):
type_selector = base_property.schema._meta.fields[base_property.schema._meta.typed_field]
else:
type_selector = base_property
kwargs['schema_property'] = type_selector
if view.next_dotpath():
kwargs['required'] = False
return field(**kwargs)
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls.defaults import patterns, url
from django.utils.functional import update_wrapper
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.contrib.admin import widgets
from django.contrib.admin.options import get_ul_class
from django.contrib.contenttypes.models import ContentType
from django import forms
from dockit.paginator import Paginator
from dockit.forms import DocumentForm
from dockit.forms.fields import PrimitiveListField, HiddenJSONField
from dockit.models import DockitPermission
from widgets import AdminPrimitiveListWidget
from breadcrumbs import Breadcrumb
from objecttools import LinkObjectTool
from django.conf import settings
from django import forms
from inlines import StackedInline
from dockit import schema
from fields import TypedSchemaField
from fields import DotPathField
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from dockit.schema.common import DotPathTraverser
from changelist import ChangeList
from django.core.urlresolvers import get_urlconf, get_resolver
from django.contrib.admin.models import LogEntry, ADDITION
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.admin.models import LogEntry, DELETION
import views
and context (functions, classes, or occasionally code) from other files:
# Path: dockit/paginator.py
#
# Path: dockit/forms/forms.py
# class DocumentForm(BaseDocumentForm):
# """ The document form object """
# __metaclass__ = DocumentFormMetaClass
#
# Path: dockit/forms/fields.py
# class PrimitiveListField(Field):
# '''
# Wraps around a subfield
# The widget receives the subfield and is responsible for rendering multiple iterations of the subfield and collecting of data
# '''
# widget = PrimitiveListWidget
#
# def __init__(self, subfield, *args, **kwargs):
# self.subfield = subfield
# widget = kwargs.get('widget', self.widget)
# if isinstance(widget, type):
# widget = widget(subfield)
# kwargs['widget'] = widget
# super(PrimitiveListField, self).__init__(*args, **kwargs)
#
# def prepare_value(self, value):
# if value is None:
# return
# ret = list()
# for val in value:
# ret.append(self.subfield.prepare_value(val))
# return ret
#
# def bound_data(self, data, initial):
# ret = list()
# for data_item, initial_item in zip(data, initial):
# ret.append(self.subfield.bound_data(data_item, initial_item))
# return ret
#
# def clean(self, data, initial=None):
# ret = list()
# for i, data_item in enumerate(data):
# if data_item.get('DELETE', False):
# continue
# if initial and len(initial) > i:
# initial_item = initial[i]
# else:
# initial_item = None
# val = self.subfield.bound_data(data_item['value'], initial_item)
#
# arg_spec = inspect.getargspec(self.subfield.clean)
# try:
# if len(arg_spec.args) > 2:
# val = self.subfield.clean(val, initial_item)
# else:
# val = self.subfield.clean(val)
# except ValidationError:
# if val:
# raise
# else:
# if val:
# ret.append((val, data_item.get('ORDER', None)))
#
# def compare_ordering_key(k):
# if k[1] is None:
# return (1, 0) # +infinity, larger than any number
# return (0, k[1])
#
# ret.sort(key=compare_ordering_key)
# return [item[0] for item in ret]
#
# class HiddenJSONField(Field):
# widget = HiddenInput
#
# 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?
# return None
#
# def validate(self, value):
# return Field.validate(self, value)
#
# def prepare_value(self, value):
# if hasattr(value, 'to_primitive'):
# return json.dumps(type(value).to_primitive(value))
# return Field.prepare_value(self, value)
#
# Path: dockit/models.py
# class DockitPermission(models.Model):
# pass #a content type is required for creating permissions
. Output only the next line. | 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 = ()
list_select_related = False
list_per_page = 100
list_max_show_all = 200
list_editable = ()
search_fields = ()
date_hierarchy = None
ordering = None
# Custom templates (designed to be over-ridden in subclasses)
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None
schema = None
<|code_end|>
with the help of current file imports:
from django.conf.urls.defaults import patterns, url
from django.utils.functional import update_wrapper
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.contrib.admin import widgets
from django.contrib.admin.options import get_ul_class
from django.contrib.contenttypes.models import ContentType
from django import forms
from dockit.paginator import Paginator
from dockit.forms import DocumentForm
from dockit.forms.fields import PrimitiveListField, HiddenJSONField
from dockit.models import DockitPermission
from widgets import AdminPrimitiveListWidget
from breadcrumbs import Breadcrumb
from objecttools import LinkObjectTool
from django.conf import settings
from django import forms
from inlines import StackedInline
from dockit import schema
from fields import TypedSchemaField
from fields import DotPathField
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from dockit.schema.common import DotPathTraverser
from changelist import ChangeList
from django.core.urlresolvers import get_urlconf, get_resolver
from django.contrib.admin.models import LogEntry, ADDITION
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.admin.models import LogEntry, DELETION
import views
and context from other files:
# Path: dockit/paginator.py
#
# Path: dockit/forms/forms.py
# class DocumentForm(BaseDocumentForm):
# """ The document form object """
# __metaclass__ = DocumentFormMetaClass
#
# Path: dockit/forms/fields.py
# class PrimitiveListField(Field):
# '''
# Wraps around a subfield
# The widget receives the subfield and is responsible for rendering multiple iterations of the subfield and collecting of data
# '''
# widget = PrimitiveListWidget
#
# def __init__(self, subfield, *args, **kwargs):
# self.subfield = subfield
# widget = kwargs.get('widget', self.widget)
# if isinstance(widget, type):
# widget = widget(subfield)
# kwargs['widget'] = widget
# super(PrimitiveListField, self).__init__(*args, **kwargs)
#
# def prepare_value(self, value):
# if value is None:
# return
# ret = list()
# for val in value:
# ret.append(self.subfield.prepare_value(val))
# return ret
#
# def bound_data(self, data, initial):
# ret = list()
# for data_item, initial_item in zip(data, initial):
# ret.append(self.subfield.bound_data(data_item, initial_item))
# return ret
#
# def clean(self, data, initial=None):
# ret = list()
# for i, data_item in enumerate(data):
# if data_item.get('DELETE', False):
# continue
# if initial and len(initial) > i:
# initial_item = initial[i]
# else:
# initial_item = None
# val = self.subfield.bound_data(data_item['value'], initial_item)
#
# arg_spec = inspect.getargspec(self.subfield.clean)
# try:
# if len(arg_spec.args) > 2:
# val = self.subfield.clean(val, initial_item)
# else:
# val = self.subfield.clean(val)
# except ValidationError:
# if val:
# raise
# else:
# if val:
# ret.append((val, data_item.get('ORDER', None)))
#
# def compare_ordering_key(k):
# if k[1] is None:
# return (1, 0) # +infinity, larger than any number
# return (0, k[1])
#
# ret.sort(key=compare_ordering_key)
# return [item[0] for item in ret]
#
# class HiddenJSONField(Field):
# widget = HiddenInput
#
# 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?
# return None
#
# def validate(self, value):
# return Field.validate(self, value)
#
# def prepare_value(self, value):
# if hasattr(value, 'to_primitive'):
# return json.dumps(type(value).to_primitive(value))
# return Field.prepare_value(self, value)
#
# Path: dockit/models.py
# class DockitPermission(models.Model):
# pass #a content type is required for creating permissions
, which may contain function names, class names, or code. Output only the next line. | 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(title='foo', subdocument=child, subschema=ChildSchema(ct=ContentType.objects.all()[0]))
assert parent.natural_key
assert '@natural_key' in parent._primitive_data
data = parent.to_portable_primitive(parent)
self.assertTrue(isinstance(data['subschema']['ct'], tuple), str(data))
self.assertTrue(isinstance(data['subdocument'], dict), "Did not give a natural key: %s" % data['subdocument'])
self.assertTrue('@natural_key' in data, str(data))
result = self.serializer.serialize([child, parent])
self.assertEqual(len(result), 2)
entry = result[1]
self.assertTrue('fields' in entry)
self.assertEqual(len(entry['fields']), 3, str(entry))
del data['@natural_key']
del data['@natural_key_hash']
self.assertEqual(entry['fields'], data)
def test_deserialize(self):
payload = [{'natural_key': {'charfield': 'bar'}, 'collection': ChildDocument._meta.collection, 'fields': {'charfield': u'bar'}},
{'natural_key': {'uuid': 'DEADBEEF'}, 'collection': ParentDocument._meta.collection, 'fields': {'subdocument': {'charfield': 'bar'}, 'title': u'foo'}}]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dockit.core.serializers.python import Serializer, Deserializer
from django.utils import unittest
from django.contrib.contenttypes.models import ContentType
from dockit.tests.serializers.common import ParentDocument, ChildDocument, ChildSchema
and context:
# Path: dockit/core/serializers/python.py
# class Serializer(base.Serializer):
# """
# Serializes a QuerySet to basic Python objects.
# """
#
# internal_use_only = True
#
# def start_serialization(self):
# self._current = None
# self.objects = []
#
# def end_serialization(self):
# pass
#
# def start_object(self, obj):
# self._current = obj.to_portable_primitive(obj)
# pk_field = obj._meta.get_id_field_name()
# 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.collection),
# "pk" : smart_unicode(obj._get_pk_val(), strings_only=True),
# "natural_key": obj.natural_key,
# "natural_key_hash": obj.natural_key_hash,
# "fields" : self._current,
# }
# self.objects.append(entry)
# self._current = None
#
# def getvalue(self):
# return self.objects
#
# def Deserializer(object_list, **options):
# """
# Deserialize simple Python objects back into Django ORM instances.
#
# It's expected that you pass the Python objects themselves (instead of a
# stream or a string) to the constructor
# """
# #models.get_apps()
# use_natural_keys = options.get('use_natural_keys', True)
# for d in object_list:
# # Look up the model and starting build a dict of data for it.
# doc_cls = get_base_document(d["collection"])
# data = d['fields']
# if use_natural_keys and 'natural_key' in d:
# data['@natural_key'] = d['natural_key']
# elif 'pk' in d:
# data[doc_cls._meta.pk.attname] = doc_cls._meta.pk.to_python(d["pk"])
#
# if 'natural_key' in d:
# yield base.DeserializedObject(doc_cls.to_python(data), natural_key=d['natural_key'])
# else:
# yield base.DeserializedObject(doc_cls.to_python(data))
#
# Path: dockit/tests/serializers/common.py
# class ParentDocument(schema.Document):
# title = schema.CharField()
# subdocument = schema.ReferenceField(ChildDocument)
# subschema = schema.SchemaField(ChildSchema)
#
# class ChildDocument(schema.Document):
# charfield = schema.CharField()
#
# def create_natural_key(self):
# return {'charfield': self.charfield}
#
# class ChildSchema(schema.Schema):
# ct = schema.ModelReferenceField(ContentType)
which might include code, classes, or functions. Output only the next line. | 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 line using the current file imports:
from dockit.core.serializers.python import Serializer, Deserializer
from django.utils import unittest
from django.contrib.contenttypes.models import ContentType
from dockit.tests.serializers.common import ParentDocument, ChildDocument, ChildSchema
and context from other files:
# Path: dockit/core/serializers/python.py
# class Serializer(base.Serializer):
# """
# Serializes a QuerySet to basic Python objects.
# """
#
# internal_use_only = True
#
# def start_serialization(self):
# self._current = None
# self.objects = []
#
# def end_serialization(self):
# pass
#
# def start_object(self, obj):
# self._current = obj.to_portable_primitive(obj)
# pk_field = obj._meta.get_id_field_name()
# 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.collection),
# "pk" : smart_unicode(obj._get_pk_val(), strings_only=True),
# "natural_key": obj.natural_key,
# "natural_key_hash": obj.natural_key_hash,
# "fields" : self._current,
# }
# self.objects.append(entry)
# self._current = None
#
# def getvalue(self):
# return self.objects
#
# def Deserializer(object_list, **options):
# """
# Deserialize simple Python objects back into Django ORM instances.
#
# It's expected that you pass the Python objects themselves (instead of a
# stream or a string) to the constructor
# """
# #models.get_apps()
# use_natural_keys = options.get('use_natural_keys', True)
# for d in object_list:
# # Look up the model and starting build a dict of data for it.
# doc_cls = get_base_document(d["collection"])
# data = d['fields']
# if use_natural_keys and 'natural_key' in d:
# data['@natural_key'] = d['natural_key']
# elif 'pk' in d:
# data[doc_cls._meta.pk.attname] = doc_cls._meta.pk.to_python(d["pk"])
#
# if 'natural_key' in d:
# yield base.DeserializedObject(doc_cls.to_python(data), natural_key=d['natural_key'])
# else:
# yield base.DeserializedObject(doc_cls.to_python(data))
#
# Path: dockit/tests/serializers/common.py
# class ParentDocument(schema.Document):
# title = schema.CharField()
# subdocument = schema.ReferenceField(ChildDocument)
# subschema = schema.SchemaField(ChildSchema)
#
# class ChildDocument(schema.Document):
# charfield = schema.CharField()
#
# def create_natural_key(self):
# return {'charfield': self.charfield}
#
# class ChildSchema(schema.Schema):
# ct = schema.ModelReferenceField(ContentType)
, which may include functions, classes, or code. Output only the next line. | 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 current file:
from dockit.core.serializers.python import Serializer, Deserializer
from django.utils import unittest
from django.contrib.contenttypes.models import ContentType
from dockit.tests.serializers.common import ParentDocument, ChildDocument, ChildSchema
and context including class names, function names, and sometimes code from other files:
# Path: dockit/core/serializers/python.py
# class Serializer(base.Serializer):
# """
# Serializes a QuerySet to basic Python objects.
# """
#
# internal_use_only = True
#
# def start_serialization(self):
# self._current = None
# self.objects = []
#
# def end_serialization(self):
# pass
#
# def start_object(self, obj):
# self._current = obj.to_portable_primitive(obj)
# pk_field = obj._meta.get_id_field_name()
# 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.collection),
# "pk" : smart_unicode(obj._get_pk_val(), strings_only=True),
# "natural_key": obj.natural_key,
# "natural_key_hash": obj.natural_key_hash,
# "fields" : self._current,
# }
# self.objects.append(entry)
# self._current = None
#
# def getvalue(self):
# return self.objects
#
# def Deserializer(object_list, **options):
# """
# Deserialize simple Python objects back into Django ORM instances.
#
# It's expected that you pass the Python objects themselves (instead of a
# stream or a string) to the constructor
# """
# #models.get_apps()
# use_natural_keys = options.get('use_natural_keys', True)
# for d in object_list:
# # Look up the model and starting build a dict of data for it.
# doc_cls = get_base_document(d["collection"])
# data = d['fields']
# if use_natural_keys and 'natural_key' in d:
# data['@natural_key'] = d['natural_key']
# elif 'pk' in d:
# data[doc_cls._meta.pk.attname] = doc_cls._meta.pk.to_python(d["pk"])
#
# if 'natural_key' in d:
# yield base.DeserializedObject(doc_cls.to_python(data), natural_key=d['natural_key'])
# else:
# yield base.DeserializedObject(doc_cls.to_python(data))
#
# Path: dockit/tests/serializers/common.py
# class ParentDocument(schema.Document):
# title = schema.CharField()
# subdocument = schema.ReferenceField(ChildDocument)
# subschema = schema.SchemaField(ChildSchema)
#
# class ChildDocument(schema.Document):
# charfield = schema.CharField()
#
# def create_natural_key(self):
# return {'charfield': self.charfield}
#
# class ChildSchema(schema.Schema):
# ct = schema.ModelReferenceField(ContentType)
. Output only the next line. | 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 predicting the next line. Consider current file imports:
from dockit.core.serializers.python import Serializer, Deserializer
from django.utils import unittest
from django.contrib.contenttypes.models import ContentType
from dockit.tests.serializers.common import ParentDocument, ChildDocument, ChildSchema
and context:
# Path: dockit/core/serializers/python.py
# class Serializer(base.Serializer):
# """
# Serializes a QuerySet to basic Python objects.
# """
#
# internal_use_only = True
#
# def start_serialization(self):
# self._current = None
# self.objects = []
#
# def end_serialization(self):
# pass
#
# def start_object(self, obj):
# self._current = obj.to_portable_primitive(obj)
# pk_field = obj._meta.get_id_field_name()
# 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.collection),
# "pk" : smart_unicode(obj._get_pk_val(), strings_only=True),
# "natural_key": obj.natural_key,
# "natural_key_hash": obj.natural_key_hash,
# "fields" : self._current,
# }
# self.objects.append(entry)
# self._current = None
#
# def getvalue(self):
# return self.objects
#
# def Deserializer(object_list, **options):
# """
# Deserialize simple Python objects back into Django ORM instances.
#
# It's expected that you pass the Python objects themselves (instead of a
# stream or a string) to the constructor
# """
# #models.get_apps()
# use_natural_keys = options.get('use_natural_keys', True)
# for d in object_list:
# # Look up the model and starting build a dict of data for it.
# doc_cls = get_base_document(d["collection"])
# data = d['fields']
# if use_natural_keys and 'natural_key' in d:
# data['@natural_key'] = d['natural_key']
# elif 'pk' in d:
# data[doc_cls._meta.pk.attname] = doc_cls._meta.pk.to_python(d["pk"])
#
# if 'natural_key' in d:
# yield base.DeserializedObject(doc_cls.to_python(data), natural_key=d['natural_key'])
# else:
# yield base.DeserializedObject(doc_cls.to_python(data))
#
# Path: dockit/tests/serializers/common.py
# class ParentDocument(schema.Document):
# title = schema.CharField()
# subdocument = schema.ReferenceField(ChildDocument)
# subschema = schema.SchemaField(ChildSchema)
#
# class ChildDocument(schema.Document):
# charfield = schema.CharField()
#
# def create_natural_key(self):
# return {'charfield': self.charfield}
#
# class ChildSchema(schema.Schema):
# ct = schema.ModelReferenceField(ContentType)
which might include code, classes, or functions. Output only the next line. | 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?
return None
def validate(self, value):
return Field.validate(self, value)
def prepare_value(self, value):
if hasattr(value, 'to_primitive'):
return json.dumps(type(value).to_primitive(value))
return Field.prepare_value(self, value)
class HiddenSchemaField(HiddenJSONField):
pass
class HiddenListField(HiddenJSONField):
pass
class HiddenDictField(HiddenJSONField):
pass
class PrimitiveListField(Field):
'''
Wraps around a subfield
The widget receives the subfield and is responsible for rendering multiple iterations of the subfield and collecting of data
'''
<|code_end|>
using the current file's imports:
from django.forms.fields import ChoiceField, Field, EMPTY_VALUES
from django.forms.widgets import HiddenInput, SelectMultiple, MultipleHiddenInput
from django.forms import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_unicode, smart_unicode
from django.utils import simplejson as json
from dockit.forms.widgets import PrimitiveListWidget
import inspect
and any relevant context from other files:
# Path: dockit/forms/widgets.py
# class PrimitiveListWidget(Widget):
# '''
# Wraps around a subfield
# The widget receives the subfield and is responsible for rendering multiple iterations of the subfield and collecting of data
# '''
# def __init__(self, subfield, attrs=None):
# self.subfield = subfield
# super(PrimitiveListWidget, self).__init__(attrs)
#
# def render(self, name, value, attrs=None):
# if not isinstance(value, list):
# value = self.decompress(value)
#
# field_count = len(value)
# final_attrs = self.build_attrs(attrs)
#
# field = self.subfield
# widget = field.widget
#
# parts = ['<div class="list-row form-row"></div>' % widget.render(name, value[i], None) for i in range(field_count)]
# output = u'<fieldset%s style="float: left;" class="primitivelistfield" name="%s">%s</fieldset>' % (flatatt(final_attrs), name, u''.join(parts))
# return mark_safe(output)
#
# def value_from_datadict(self, data, files, name):
# value = list()
# if hasattr(data, 'getlist'):
# source = data.getlist(name)
# else:
# source = data.get(name, [])
# for i, entry in enumerate(source):
# val = dict()
# val['value'] = entry
# val['ORDER'] = i
# value.append(val)
# return value
#
# def _has_changed(self, initial, data):
# if initial is None:
# initial = [u'' for x in range(0, len(data))]
# else:
# if not isinstance(initial, list):
# initial = self.decompress(initial)
# #for widget, initial, data in zip(self.widgets, initial, data):
# # if widget._has_changed(initial, data):
# # return True
# return True #CONSIDER where is my name?
# return False
#
# def decompress(self, value):
# """
# Returns a list of decompressed values for the given compressed value.
# The given value can be assumed to be valid, but not necessarily
# non-empty.
# """
# raise NotImplementedError('Subclasses must implement this method.')
#
# def _get_media(self):
# "Media for a multiwidget is the combination of all media of the subwidgets"
# media = Media()
# media += self.subfield.media
# definition = getattr(self, 'Media', None)
# if definition:
# media += Media(definition)
# return media
# media = property(_get_media)
#
# def __deepcopy__(self, memo):
# obj = super(PrimitiveListWidget, self).__deepcopy__(memo)
# obj.subfield = copy.deepcopy(self.subfield)
# return obj
. Output only the next line. | 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)
for key in params.keys(): #TODO this is a hack
params[key] = 1
if params:
collection = query_index.document._meta.collection
try:
self.get_collection(collection).ensure_index(params, background=True)
except TypeError:
self.get_collection(collection).ensure_index(params.items(), background=True)
def destroy_index(self, query_index):
pass #TODO
def get_query(self, query_index):
return DocumentQuery(query_index, backend=self)
def on_save(self, doc_class, collection, data, doc_id):
#CONSIDER supporting standalone mongo indexes
pass #no operation needed
def on_delete(self, doc_class, collection, doc_id):
pass #no operation needed
<|code_end|>
, determine the next line of code. You have imports:
from pymongo import Connection
from bson.objectid import ObjectId
from pymongo.objectid import ObjectId
from dockit.backends.base import BaseDocumentStorage, BaseIndexStorage
from dockit.backends.queryset import BaseDocumentQuery
and context (class names, function names, or code) available:
# Path: dockit/backends/base.py
# class BaseDocumentStorage(BaseStorage):
# """
# The :class:`~dockit.backends.base.BaseDocumentStorage` class provides an interface
# for implementing document storage backends.
# """
#
# _connections = DOCUMENT_BACKEND_CONNECTIONS
# _threaded_connections = THREADED_DOCUMENT_BACKEND_CONNECTIONS
#
# def get_query(self, query_index):
# """
# return an implemented `BaseDocumentQuerySet` that contains all the documents
# """
# raise NotImplementedError
#
# def register_document(self, document):
# """
# is called for every document registered in the system
# """
# pass
#
# def save(self, doc_class, collection, data):
# """
# stores the given primitive data in the specified collection
# """
# raise NotImplementedError
#
# def get(self, doc_class, collection, doc_id):
# """
# returns the primitive data for the document belonging in the specified collection
# """
# raise NotImplementedError
#
# def delete(self, doc_class, collection, doc_id):
# """
# deletes the given document from the specified collection
# """
# raise NotImplementedError
#
# def get_id(self, data):
# """
# returns the id from the primitive data
# """
# return data.get(self.get_id_field_name())
#
# def get_id_field_name(self):
# """
# returns a string representing the primary key field name
# """
# raise NotImplementedError
#
# class BaseIndexStorage(BaseStorage):
# """
# The :class:`~dockit.backends.base.BaseIndexStorage` class provides an interface
# for implementing index storage backends.
# """
#
# _connections = INDEX_BACKEND_CONNECTIONS
# _threaded_connections = THREADED_INDEX_BACKEND_CONNECTIONS
#
# _indexers = dict()
#
# @classmethod
# def register_indexer(cls, index_cls, *names):
# for name in names:
# cls._indexers[name] = index_cls
#
# @classmethod
# def get_indexer(cls, name):
# return cls._indexers[name]
#
# def _get_indexer_for_operation(self, document, op):
# indexer = self.get_indexer(op.operation)
# return indexer(document, op)
#
# def register_index(self, query_index):
# """
# register the query index with this backend
# """
# raise NotImplementedError
#
# def destroy_index(self, query_index):
# """
# release the query index with this backend
# """
# raise NotImplementedError
#
# def get_query(self, query_index):
# """
# returns an implemented `BaseDocumentQuerySet` representing the query index
# """
# raise NotImplementedError
#
# def register_document(self, document):
# """
# is called for every document registered in the system
# """
# pass
#
# def on_save(self, doc_class, collection, doc_id, data):
# """
# is called for every document save
# """
# raise NotImplementedError
#
# def on_delete(self, doc_class, collection, doc_id):
# """
# is called for every document delete
# """
# raise NotImplementedError
#
# Path: dockit/backends/queryset.py
# class BaseDocumentQuery(object):
# """
# Implemented by the backend to execute a certain index
# """
# def __init__(self, query_index, backend=None):
# self.query_index = query_index
# self._backend = backend
#
# @property
# def document(self):
# return self.query_index.document
#
# @property
# def backend(self):
# if self._backend:
# return self._backend
# return self.document._meta.get_index_backend_for_read(self.query_index)
#
# def _get_indexer_for_operation(self, document, op):
# return self.backend._get_indexer_for_operation(document, op)
#
# def __len__(self):
# raise NotImplementedError
#
# def count(self):
# return self.__len__()
#
# def exists(self):
# return bool(self.__len__())
#
# def delete(self):
# raise NotImplementedError
#
# def get(self, **kwargs):
# filter_operations = self.query_index._parse_kwargs(kwargs)
# return self.get_from_filter_operations(filter_operations)
#
# def get_from_filter_operations(self, filter_operations):
# raise NotImplementedError
#
# def values(self, *limit_to, **kwargs):
# raise NotImplementedError
#
# def __getitem__(self, val):
# raise NotImplementedError
#
# def __nonzero__(self):
# raise NotImplementedError
. Output only the next line. | 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()
def __nonzero__(self):
return bool(self.queryset)
def __getitem__(self, val):
if isinstance(val, slice):
results = list()
#TODO i don't think mongo supports passing a slice
for entry in self.queryset[val]:
results.append(self.wrap(entry))
return results
else:
return self.wrap(self.queryset[val])
class MongoStorageMixin(object):
def __init__(self, username=None, password=None, host=None, port=None, db=None, **kwargs):
self.connection = Connection(kwargs.get('HOST', host), kwargs.get('PORT', port))
self.db = self.connection[kwargs.get('DB', db)]
if username:
self.db.authenticate(kwargs.get('USER', username), kwargs.get('PASSWORD', password))
def get_collection(self, collection):
return self.db[collection]
<|code_end|>
using the current file's imports:
from pymongo import Connection
from bson.objectid import ObjectId
from pymongo.objectid import ObjectId
from dockit.backends.base import BaseDocumentStorage, BaseIndexStorage
from dockit.backends.queryset import BaseDocumentQuery
and any relevant context from other files:
# Path: dockit/backends/base.py
# class BaseDocumentStorage(BaseStorage):
# """
# The :class:`~dockit.backends.base.BaseDocumentStorage` class provides an interface
# for implementing document storage backends.
# """
#
# _connections = DOCUMENT_BACKEND_CONNECTIONS
# _threaded_connections = THREADED_DOCUMENT_BACKEND_CONNECTIONS
#
# def get_query(self, query_index):
# """
# return an implemented `BaseDocumentQuerySet` that contains all the documents
# """
# raise NotImplementedError
#
# def register_document(self, document):
# """
# is called for every document registered in the system
# """
# pass
#
# def save(self, doc_class, collection, data):
# """
# stores the given primitive data in the specified collection
# """
# raise NotImplementedError
#
# def get(self, doc_class, collection, doc_id):
# """
# returns the primitive data for the document belonging in the specified collection
# """
# raise NotImplementedError
#
# def delete(self, doc_class, collection, doc_id):
# """
# deletes the given document from the specified collection
# """
# raise NotImplementedError
#
# def get_id(self, data):
# """
# returns the id from the primitive data
# """
# return data.get(self.get_id_field_name())
#
# def get_id_field_name(self):
# """
# returns a string representing the primary key field name
# """
# raise NotImplementedError
#
# class BaseIndexStorage(BaseStorage):
# """
# The :class:`~dockit.backends.base.BaseIndexStorage` class provides an interface
# for implementing index storage backends.
# """
#
# _connections = INDEX_BACKEND_CONNECTIONS
# _threaded_connections = THREADED_INDEX_BACKEND_CONNECTIONS
#
# _indexers = dict()
#
# @classmethod
# def register_indexer(cls, index_cls, *names):
# for name in names:
# cls._indexers[name] = index_cls
#
# @classmethod
# def get_indexer(cls, name):
# return cls._indexers[name]
#
# def _get_indexer_for_operation(self, document, op):
# indexer = self.get_indexer(op.operation)
# return indexer(document, op)
#
# def register_index(self, query_index):
# """
# register the query index with this backend
# """
# raise NotImplementedError
#
# def destroy_index(self, query_index):
# """
# release the query index with this backend
# """
# raise NotImplementedError
#
# def get_query(self, query_index):
# """
# returns an implemented `BaseDocumentQuerySet` representing the query index
# """
# raise NotImplementedError
#
# def register_document(self, document):
# """
# is called for every document registered in the system
# """
# pass
#
# def on_save(self, doc_class, collection, doc_id, data):
# """
# is called for every document save
# """
# raise NotImplementedError
#
# def on_delete(self, doc_class, collection, doc_id):
# """
# is called for every document delete
# """
# raise NotImplementedError
#
# Path: dockit/backends/queryset.py
# class BaseDocumentQuery(object):
# """
# Implemented by the backend to execute a certain index
# """
# def __init__(self, query_index, backend=None):
# self.query_index = query_index
# self._backend = backend
#
# @property
# def document(self):
# return self.query_index.document
#
# @property
# def backend(self):
# if self._backend:
# return self._backend
# return self.document._meta.get_index_backend_for_read(self.query_index)
#
# def _get_indexer_for_operation(self, document, op):
# return self.backend._get_indexer_for_operation(document, op)
#
# def __len__(self):
# raise NotImplementedError
#
# def count(self):
# return self.__len__()
#
# def exists(self):
# return bool(self.__len__())
#
# def delete(self):
# raise NotImplementedError
#
# def get(self, **kwargs):
# filter_operations = self.query_index._parse_kwargs(kwargs)
# return self.get_from_filter_operations(filter_operations)
#
# def get_from_filter_operations(self, filter_operations):
# raise NotImplementedError
#
# def values(self, *limit_to, **kwargs):
# raise NotImplementedError
#
# def __getitem__(self, val):
# raise NotImplementedError
#
# def __nonzero__(self):
# raise NotImplementedError
. Output only the next line. | 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_end|>
. Use current file imports:
(from pymongo import Connection
from bson.objectid import ObjectId
from pymongo.objectid import ObjectId
from dockit.backends.base import BaseDocumentStorage, BaseIndexStorage
from dockit.backends.queryset import BaseDocumentQuery)
and context including class names, function names, or small code snippets from other files:
# Path: dockit/backends/base.py
# class BaseDocumentStorage(BaseStorage):
# """
# The :class:`~dockit.backends.base.BaseDocumentStorage` class provides an interface
# for implementing document storage backends.
# """
#
# _connections = DOCUMENT_BACKEND_CONNECTIONS
# _threaded_connections = THREADED_DOCUMENT_BACKEND_CONNECTIONS
#
# def get_query(self, query_index):
# """
# return an implemented `BaseDocumentQuerySet` that contains all the documents
# """
# raise NotImplementedError
#
# def register_document(self, document):
# """
# is called for every document registered in the system
# """
# pass
#
# def save(self, doc_class, collection, data):
# """
# stores the given primitive data in the specified collection
# """
# raise NotImplementedError
#
# def get(self, doc_class, collection, doc_id):
# """
# returns the primitive data for the document belonging in the specified collection
# """
# raise NotImplementedError
#
# def delete(self, doc_class, collection, doc_id):
# """
# deletes the given document from the specified collection
# """
# raise NotImplementedError
#
# def get_id(self, data):
# """
# returns the id from the primitive data
# """
# return data.get(self.get_id_field_name())
#
# def get_id_field_name(self):
# """
# returns a string representing the primary key field name
# """
# raise NotImplementedError
#
# class BaseIndexStorage(BaseStorage):
# """
# The :class:`~dockit.backends.base.BaseIndexStorage` class provides an interface
# for implementing index storage backends.
# """
#
# _connections = INDEX_BACKEND_CONNECTIONS
# _threaded_connections = THREADED_INDEX_BACKEND_CONNECTIONS
#
# _indexers = dict()
#
# @classmethod
# def register_indexer(cls, index_cls, *names):
# for name in names:
# cls._indexers[name] = index_cls
#
# @classmethod
# def get_indexer(cls, name):
# return cls._indexers[name]
#
# def _get_indexer_for_operation(self, document, op):
# indexer = self.get_indexer(op.operation)
# return indexer(document, op)
#
# def register_index(self, query_index):
# """
# register the query index with this backend
# """
# raise NotImplementedError
#
# def destroy_index(self, query_index):
# """
# release the query index with this backend
# """
# raise NotImplementedError
#
# def get_query(self, query_index):
# """
# returns an implemented `BaseDocumentQuerySet` representing the query index
# """
# raise NotImplementedError
#
# def register_document(self, document):
# """
# is called for every document registered in the system
# """
# pass
#
# def on_save(self, doc_class, collection, doc_id, data):
# """
# is called for every document save
# """
# raise NotImplementedError
#
# def on_delete(self, doc_class, collection, doc_id):
# """
# is called for every document delete
# """
# raise NotImplementedError
#
# Path: dockit/backends/queryset.py
# class BaseDocumentQuery(object):
# """
# Implemented by the backend to execute a certain index
# """
# def __init__(self, query_index, backend=None):
# self.query_index = query_index
# self._backend = backend
#
# @property
# def document(self):
# return self.query_index.document
#
# @property
# def backend(self):
# if self._backend:
# return self._backend
# return self.document._meta.get_index_backend_for_read(self.query_index)
#
# def _get_indexer_for_operation(self, document, op):
# return self.backend._get_indexer_for_operation(document, op)
#
# def __len__(self):
# raise NotImplementedError
#
# def count(self):
# return self.__len__()
#
# def exists(self):
# return bool(self.__len__())
#
# def delete(self):
# raise NotImplementedError
#
# def get(self, **kwargs):
# filter_operations = self.query_index._parse_kwargs(kwargs)
# return self.get_from_filter_operations(filter_operations)
#
# def get_from_filter_operations(self, filter_operations):
# raise NotImplementedError
#
# def values(self, *limit_to, **kwargs):
# raise NotImplementedError
#
# def __getitem__(self, val):
# raise NotImplementedError
#
# def __nonzero__(self):
# raise NotImplementedError
. Output only the next line. | 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((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))
return perms + opts.permissions
#code => <collection>.code
#lookup code => dockit.<collection>.code
#content type = DockitPermission
#user.has_perm(dockit.somecollection.code)
def create_permissions(documents, verbosity, **kwargs):
# This will hold the permissions we're looking for as
# (content_type, (codename, name))
searched_perms = list()
<|code_end|>
, generate the next line using the imports in this file:
from dockit.models import DockitPermission
from dockit.schema.signals import document_registered
from dockit.schema.loading import get_documents
from django.contrib.auth import models as auth_app
from django.contrib.contenttypes.models import ContentType
from django.db.utils import DatabaseError
from django.db.transaction import commit_on_success
and context (functions, classes, or occasionally code) from other files:
# Path: dockit/models.py
# class DockitPermission(models.Model):
# pass #a content type is required for creating permissions
#
# Path: dockit/schema/signals.py
#
# Path: dockit/schema/loading.py
# def get_documents(self, app_label=None):
# if self.pending_documents and self.app_cache_ready():
# self.post_app_ready()
# if app_label:
# return self.app_documents[app_label].values()
# return self.documents.values()
. Output only the next line. | 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 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 to create.
all_perms = set(auth_app.Permission.objects.filter(
content_type=ctype,
).values_list(
"codename", flat=True
))
for codename, name in searched_perms:
# If the permissions exists, move on.
if codename in all_perms:
continue
p = auth_app.Permission.objects.create(
codename=codename,
name=name,
content_type=ctype
)
if verbosity >= 2:
print "Adding permission '%s'" % p
def on_document_registered(document, **kwargs):
create_permissions([document], 1)
<|code_end|>
, determine the next line of code. You have imports:
from dockit.models import DockitPermission
from dockit.schema.signals import document_registered
from dockit.schema.loading import get_documents
from django.contrib.auth import models as auth_app
from django.contrib.contenttypes.models import ContentType
from django.db.utils import DatabaseError
from django.db.transaction import commit_on_success
and context (class names, function names, or code) available:
# Path: dockit/models.py
# class DockitPermission(models.Model):
# pass #a content type is required for creating permissions
#
# Path: dockit/schema/signals.py
#
# Path: dockit/schema/loading.py
# def get_documents(self, app_label=None):
# if self.pending_documents and self.app_cache_ready():
# self.post_app_ready()
# if app_label:
# return self.app_documents[app_label].values()
# return self.documents.values()
. Output only the next line. | 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 to create.
all_perms = set(auth_app.Permission.objects.filter(
content_type=ctype,
).values_list(
"codename", flat=True
))
for codename, name in searched_perms:
# If the permissions exists, move on.
if codename in all_perms:
continue
p = auth_app.Permission.objects.create(
codename=codename,
name=name,
content_type=ctype
)
if verbosity >= 2:
print "Adding permission '%s'" % p
def on_document_registered(document, **kwargs):
create_permissions([document], 1)
document_registered.connect(on_document_registered)
try:
#wrap with commit_on_success as to try to not poison a higher transaction
<|code_end|>
. Write the next line using the current file imports:
from dockit.models import DockitPermission
from dockit.schema.signals import document_registered
from dockit.schema.loading import get_documents
from django.contrib.auth import models as auth_app
from django.contrib.contenttypes.models import ContentType
from django.db.utils import DatabaseError
from django.db.transaction import commit_on_success
and context from other files:
# Path: dockit/models.py
# class DockitPermission(models.Model):
# pass #a content type is required for creating permissions
#
# Path: dockit/schema/signals.py
#
# Path: dockit/schema/loading.py
# def get_documents(self, app_label=None):
# if self.pending_documents and self.app_cache_ready():
# self.post_app_ready()
# if app_label:
# return self.app_documents[app_label].values()
# return self.documents.values()
, which may include functions, classes, or code. Output only the next line. | 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 = handlers
self.handlers_by_key = dict([(handler.key, handler) for handler in self.handlers])
def to_primitive(self, obj):
if isinstance(obj, (QuerySet, list)):
return map(self.to_primitive, obj)
for handler in self.handlers:
if isinstance(obj, handler.instancetype):
return handler.encode(obj)
if isinstance(obj, dict):
for key, value in obj.items():
obj[self.to_primitive(key)] = self.to_primitive(value)
elif isinstance(obj, list):
return map(self.to_primtive, obj)
return obj
def to_python(self, obj):
if isinstance(obj, dict):
if '__type__' in obj:
return self.handlers_by_key[obj['__type__']].decode(obj)
for key, value in obj.items():
obj[self.to_python(key)] = self.to_python(value)
obj = DotPathDict(obj)
elif isinstance(obj, list):
<|code_end|>
. Use current file imports:
from django.contrib.contenttypes.models import ContentType
from django.core.serializers.json import DjangoJSONEncoder
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.query import QuerySet
from django.db import models
from django.utils import simplejson
from decimal import Decimal
from dockit.schema.common import DotPathList, DotPathDict
and context (classes, functions, or code) from other files:
# Path: dockit/schema/common.py
# class DotPathList(list):
# def traverse_dot_path(self, traverser):
# if traverser.remaining_paths:
# new_value = None
# name = traverser.next_part
# try:
# new_value = self[int(name)]
# except ValueError:
# raise DotPathNotFound("Invalid index given, must be an integer")
# except IndexError:
# pass
# traverser.next(value=new_value)
# else:
# traverser.end(value=self)
#
# def set_value(self, attr, value):
# index = int(attr)
# if value is UnSet:
# self.pop(index)
# elif index == len(self):
# self.append(value)
# else:
# self[index] = value
#
# class DotPathDict(dict):
# def traverse_dot_path(self, traverser):
# if traverser.remaining_paths:
# new_value = None
# name = traverser.next_part
# try:
# new_value = self[name]
# except KeyError:
# pass
# traverser.next(value=new_value)
# else:
# traverser.end(value=self)
#
# def set_value(self, attr, value):
# if value is UnSet:
# del self[attr]
# else:
# self[attr] = value
. Output only the next line. | 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),}
class PrimitiveProcessor(object):
def __init__(self, handlers):
self.handlers = handlers
self.handlers_by_key = dict([(handler.key, handler) for handler in self.handlers])
def to_primitive(self, obj):
if isinstance(obj, (QuerySet, list)):
return map(self.to_primitive, obj)
for handler in self.handlers:
if isinstance(obj, handler.instancetype):
return handler.encode(obj)
if isinstance(obj, dict):
for key, value in obj.items():
obj[self.to_primitive(key)] = self.to_primitive(value)
elif isinstance(obj, list):
return map(self.to_primtive, obj)
return obj
def to_python(self, obj):
if isinstance(obj, dict):
if '__type__' in obj:
return self.handlers_by_key[obj['__type__']].decode(obj)
for key, value in obj.items():
obj[self.to_python(key)] = self.to_python(value)
<|code_end|>
with the help of current file imports:
from django.contrib.contenttypes.models import ContentType
from django.core.serializers.json import DjangoJSONEncoder
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.query import QuerySet
from django.db import models
from django.utils import simplejson
from decimal import Decimal
from dockit.schema.common import DotPathList, DotPathDict
and context from other files:
# Path: dockit/schema/common.py
# class DotPathList(list):
# def traverse_dot_path(self, traverser):
# if traverser.remaining_paths:
# new_value = None
# name = traverser.next_part
# try:
# new_value = self[int(name)]
# except ValueError:
# raise DotPathNotFound("Invalid index given, must be an integer")
# except IndexError:
# pass
# traverser.next(value=new_value)
# else:
# traverser.end(value=self)
#
# def set_value(self, attr, value):
# index = int(attr)
# if value is UnSet:
# self.pop(index)
# elif index == len(self):
# self.append(value)
# else:
# self[index] = value
#
# class DotPathDict(dict):
# def traverse_dot_path(self, traverser):
# if traverser.remaining_paths:
# new_value = None
# name = traverser.next_part
# try:
# new_value = self[name]
# except KeyError:
# pass
# traverser.next(value=new_value)
# else:
# traverser.end(value=self)
#
# def set_value(self, attr, value):
# if value is UnSet:
# del self[attr]
# else:
# self[attr] = value
, which may contain function names, class names, or code. Output only the next line. | 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
self.documents[document._meta.collection] = document
if self.app_cache_ready():
self.register_documents_with_backend(documents)
self.post_app_ready() #TODO find a better solution, like on_app_ready
else:
self.pending_documents.extend(documents)
def force_register_documents(self, app_label, *documents):
document_dict = self.app_documents.setdefault(app_label, SortedDict())
for document in documents:
doc_name = document._meta.object_name.lower()
#TODO detect if any other documents use this as a base document
document_dict[doc_name] = document
self.documents[document._meta.collection] = document
if self.app_cache_ready():
self.register_documents_with_backend(documents)
self.post_app_ready() #TODO find a better solution, like on_app_ready
else:
self.pending_documents.extend(documents)
def register_documents_with_backend(self, documents):
router = get_document_router()
for document in documents:
router.register_document(document)
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import imp
from django.db.models.loading import AppCache
from django.utils.datastructures import SortedDict
from dockit.schema.signals import document_registered
from dockit.backends import get_document_router
from dockit.backends import get_index_router
and context (functions, classes, or occasionally code) from other files:
# Path: dockit/schema/signals.py
. Output only the next line. | 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 list of strings which represent names of input variables and
sets properties of the same name on the current object if the value of
the argument is not None.
* argumentNames -- The list of argument names to set
* localVars -- The local variables
'''
for argName in argumentNames:
# Get the value of the local argument
argValue = localVars.get(argName)
# Only set the argument if its value is not None
if argValue is not None:
setattr(self, argName, argValue)
def toDict(self):
'''Convert this object into a Python dictionary.'''
dictionary = {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from uuid import uuid4
from pysiriproxy.constants import Keys
and context:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
which might include code, classes, or functions. Output only the next line. | 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 to encapsulate a plist object, and be able
to convert a standard plist into a binary formatted plist.
'''
class BinaryPlist:
'''The BinaryPlist class takes in a dictionary containing data and
provides the ability to convert the dictionary into a binary plist.
.. note:: This class uses the :mod:`biplist` module to convert a Python
dictionary into a binary plist.
'''
TtsRegex = "@{tts#.*?}"
'''The tag that indicates the start of a tts tag. This is a non-greedy
regular expression so that it matches to only the first end curly brace.
'''
DateKeys = [
<|code_end|>
, generate the next line using the imports in this file:
import re
import biplist
from string import printable
from StringIO import StringIO
from datetime import datetime, timedelta
from CFPropertyList import CFPropertyList, native_types
from pysiriproxy.constants import Keys
from pyamp.util import getStackTrace
and context (functions, classes, or occasionally code) from other files:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
. Output only the next line. | 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 direction to be connected to an opposite
connection direction which allows data to be forwarded from the
direction to the connected direction.
'''
# Implement the borg pattern
__shared_state = {}
def __init__(self, logger=None):
'''
* logger -- The logger
'''
self.__dict__ = self.__shared_state
# If the manager has not been initialized, then initialize it
if getattr(self, "_initialized", False) == False:
# Create a map of directions to connection objects
self._connections = {
<|code_end|>
, determine the next line of code. You have imports:
from pysiriproxy.constants import Directions
from pyamp.logging import LogData, Colors
and context (class names, function names, or code) available:
# Path: pysiriproxy/constants.py
# class Directions:
# '''The Directions class contains several properties which are used to
# indicate which direction data is entering the system.
#
# '''
#
# From_Server = "From_Server"
# '''The From_Server property indicates that data was received from Apple's
# server.
#
# '''
#
# From_iPhone = "From_iPhone"
# '''The From_iPhone property indicates that data was received from the
# iPhone.
#
# '''
. Output only the next line. | 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 given protocol class using the same interface used
to handle connections to the server. This allows us to save incoming
data to the server and replay it for testing purposes.
'''
def __init__(self, protocol, filename, logger):
'''
* protocol -- The server protocol class
* filename -- The filename containing to data to replay
* logger -- The logger
'''
Thread.__init__(self)
self.__log = logger.get("PacketPlayer")
self.__protocol = protocol(logger=logger)
self.__content = file(filename).read()
self.__lines = self.__content.split("-END_OF_DATA-")
self.__index = 0
# Start in Line mode
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pysiriproxy.utils import toHex
from pysiriproxy.constants import Modes
from pyamp.processes.threading import Thread
and context:
# Path: pysiriproxy/utils.py
# def toHex(string, separator=" "):
# '''Convert a string to hexadecimal.
#
# * string -- The string to convert to hexadecimal
# * seperator -- The seperator to use between each character
#
# '''
# return separator.join(map(characterToHex, string))
#
# Path: pysiriproxy/constants.py
# class Modes:
# '''The Modes class contains properties which define different types of
# data receiving modes.
#
# '''
#
# Line = "line"
# '''The Line property indicates the mode in which lines of data is
# sent and received.
#
# '''
#
# Raw = "raw"
# '''The Raw property indicates the mode in which raw data is sent
# and received.
#
# '''
which might include code, classes, or functions. Output only the next line. | 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 = obj.get('class')
return directionsMatch(function, direction) and \
objectClassesMatch(function, objectClass)
def __speechRuleApplies(self, function, text):
'''Determine if the given speech rule function applies to
the recognized text.
* function -- The speech rule function
* text -- The recognized text
'''
return speechRuleMatches(function, text)
def __getStartRequestCommand(self, obj):
'''Get the command name from the start request object.
* obj -- The start request object
'''
utterance = None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from types import GeneratorType
from pysiriproxy.constants import Keys
from pysiriproxy.plugins.speechRules import isSpeechRule, speechRuleMatches, \
matches
from pysiriproxy.plugins.directions import isDirectionFilter, \
directionsMatch, From_iPhone, From_Server
from pysiriproxy.plugins.objectClasses import isObjectClassFilter, \
objectClassesMatch, SpeechPacket, SpeechRecognized, StartRequest
from pyamp.logging import Colors
from pyamp.util import getStackTrace
and context:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
#
# Path: pysiriproxy/plugins/speechRules.py
# _SPEECH_RULES_PROP = "SpeechRules"
# def getSpeechRules(function):
# def isSpeechRule(function):
# def speechRuleMatches(function, text):
# def createSpeechRule(ruleClass):
# def wrapper(text, *args, **kwargs):
# def __init__(self, text, *args, **kwargs):
# def text(self):
# def test(self, text):
# def test(self, text):
# def __init__(self, regex, ignoreCase=True):
# def test(self, text):
# class SpeechRule:
# class MatchSpeechRule(SpeechRule):
# class RegexSpeechRule(SpeechRule):
#
# Path: pysiriproxy/plugins/directions.py
# _DIRECTIONS_PROP = "Directions"
# def _addDirection(direction):
# def getDirections(function):
# def isDirectionFilter(function):
# def directionsMatch(function, direction):
#
# Path: pysiriproxy/plugins/objectClasses.py
# _CLASSES_PROP = "Classes"
# def createClassFilter(className):
# def isObjectClassFilter(function):
# def getObjectClasses(function):
# def objectClassesMatch(function, objectClass):
which might include code, classes, or functions. Output only the next line. | 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 filters #####
def __clearFilters(self):
'''Clear the filters for this plugin.'''
self.__filters = []
def __clearSpeechRules(self):
'''Clear the speech rules for this plugin.'''
self.__speechRules = []
def __loadFiltersAndRules(self):
'''Load all of the filters and speech rules for this Plugin.'''
self.__clearFilters()
self.__clearSpeechRules()
# Traverse all of our functions
for function in self.__getFunctions():
# Handle a filter, or speech rule function accordingly
if isDirectionFilter(function) or isObjectClassFilter(function):
self.log.debug("Added filter [%s]" % function.__name__,
level=10)
self.__filters.append(function)
<|code_end|>
using the current file's imports:
from types import GeneratorType
from pysiriproxy.constants import Keys
from pysiriproxy.plugins.speechRules import isSpeechRule, speechRuleMatches, \
matches
from pysiriproxy.plugins.directions import isDirectionFilter, \
directionsMatch, From_iPhone, From_Server
from pysiriproxy.plugins.objectClasses import isObjectClassFilter, \
objectClassesMatch, SpeechPacket, SpeechRecognized, StartRequest
from pyamp.logging import Colors
from pyamp.util import getStackTrace
and any relevant context from other files:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
#
# Path: pysiriproxy/plugins/speechRules.py
# _SPEECH_RULES_PROP = "SpeechRules"
# def getSpeechRules(function):
# def isSpeechRule(function):
# def speechRuleMatches(function, text):
# def createSpeechRule(ruleClass):
# def wrapper(text, *args, **kwargs):
# def __init__(self, text, *args, **kwargs):
# def text(self):
# def test(self, text):
# def test(self, text):
# def __init__(self, regex, ignoreCase=True):
# def test(self, text):
# class SpeechRule:
# class MatchSpeechRule(SpeechRule):
# class RegexSpeechRule(SpeechRule):
#
# Path: pysiriproxy/plugins/directions.py
# _DIRECTIONS_PROP = "Directions"
# def _addDirection(direction):
# def getDirections(function):
# def isDirectionFilter(function):
# def directionsMatch(function, direction):
#
# Path: pysiriproxy/plugins/objectClasses.py
# _CLASSES_PROP = "Classes"
# def createClassFilter(className):
# def isObjectClassFilter(function):
# def getObjectClasses(function):
# def objectClassesMatch(function, objectClass):
. Output only the next line. | 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(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 = obj.get('class')
return directionsMatch(function, direction) and \
objectClassesMatch(function, objectClass)
def __speechRuleApplies(self, function, text):
'''Determine if the given speech rule function applies to
the recognized text.
* function -- The speech rule function
* text -- The recognized text
'''
<|code_end|>
using the current file's imports:
from types import GeneratorType
from pysiriproxy.constants import Keys
from pysiriproxy.plugins.speechRules import isSpeechRule, speechRuleMatches, \
matches
from pysiriproxy.plugins.directions import isDirectionFilter, \
directionsMatch, From_iPhone, From_Server
from pysiriproxy.plugins.objectClasses import isObjectClassFilter, \
objectClassesMatch, SpeechPacket, SpeechRecognized, StartRequest
from pyamp.logging import Colors
from pyamp.util import getStackTrace
and any relevant context from other files:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
#
# Path: pysiriproxy/plugins/speechRules.py
# _SPEECH_RULES_PROP = "SpeechRules"
# def getSpeechRules(function):
# def isSpeechRule(function):
# def speechRuleMatches(function, text):
# def createSpeechRule(ruleClass):
# def wrapper(text, *args, **kwargs):
# def __init__(self, text, *args, **kwargs):
# def text(self):
# def test(self, text):
# def test(self, text):
# def __init__(self, regex, ignoreCase=True):
# def test(self, text):
# class SpeechRule:
# class MatchSpeechRule(SpeechRule):
# class RegexSpeechRule(SpeechRule):
#
# Path: pysiriproxy/plugins/directions.py
# _DIRECTIONS_PROP = "Directions"
# def _addDirection(direction):
# def getDirections(function):
# def isDirectionFilter(function):
# def directionsMatch(function, direction):
#
# Path: pysiriproxy/plugins/objectClasses.py
# _CLASSES_PROP = "Classes"
# def createClassFilter(className):
# def isObjectClassFilter(function):
# def getObjectClasses(function):
# def objectClassesMatch(function, objectClass):
. Output only the next line. | 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.__manager.completeRequest()
##### Private functions for loading filters #####
def __clearFilters(self):
'''Clear the filters for this plugin.'''
self.__filters = []
def __clearSpeechRules(self):
'''Clear the speech rules for this plugin.'''
self.__speechRules = []
def __loadFiltersAndRules(self):
'''Load all of the filters and speech rules for this Plugin.'''
self.__clearFilters()
self.__clearSpeechRules()
# Traverse all of our functions
for function in self.__getFunctions():
# Handle a filter, or speech rule function accordingly
<|code_end|>
, determine the next line of code. You have imports:
from types import GeneratorType
from pysiriproxy.constants import Keys
from pysiriproxy.plugins.speechRules import isSpeechRule, speechRuleMatches, \
matches
from pysiriproxy.plugins.directions import isDirectionFilter, \
directionsMatch, From_iPhone, From_Server
from pysiriproxy.plugins.objectClasses import isObjectClassFilter, \
objectClassesMatch, SpeechPacket, SpeechRecognized, StartRequest
from pyamp.logging import Colors
from pyamp.util import getStackTrace
and context (class names, function names, or code) available:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
#
# Path: pysiriproxy/plugins/speechRules.py
# _SPEECH_RULES_PROP = "SpeechRules"
# def getSpeechRules(function):
# def isSpeechRule(function):
# def speechRuleMatches(function, text):
# def createSpeechRule(ruleClass):
# def wrapper(text, *args, **kwargs):
# def __init__(self, text, *args, **kwargs):
# def text(self):
# def test(self, text):
# def test(self, text):
# def __init__(self, regex, ignoreCase=True):
# def test(self, text):
# class SpeechRule:
# class MatchSpeechRule(SpeechRule):
# class RegexSpeechRule(SpeechRule):
#
# Path: pysiriproxy/plugins/directions.py
# _DIRECTIONS_PROP = "Directions"
# def _addDirection(direction):
# def getDirections(function):
# def isDirectionFilter(function):
# def directionsMatch(function, direction):
#
# Path: pysiriproxy/plugins/objectClasses.py
# _CLASSES_PROP = "Classes"
# def createClassFilter(className):
# def isObjectClassFilter(function):
# def getObjectClasses(function):
# def objectClassesMatch(function, objectClass):
. Output only the next line. | 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:
raise Exception("Plugins must have a '%s' property!" % propName)
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(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 = obj.get('class')
<|code_end|>
, predict the next line using imports from the current file:
from types import GeneratorType
from pysiriproxy.constants import Keys
from pysiriproxy.plugins.speechRules import isSpeechRule, speechRuleMatches, \
matches
from pysiriproxy.plugins.directions import isDirectionFilter, \
directionsMatch, From_iPhone, From_Server
from pysiriproxy.plugins.objectClasses import isObjectClassFilter, \
objectClassesMatch, SpeechPacket, SpeechRecognized, StartRequest
from pyamp.logging import Colors
from pyamp.util import getStackTrace
and context including class names, function names, and sometimes code from other files:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
#
# Path: pysiriproxy/plugins/speechRules.py
# _SPEECH_RULES_PROP = "SpeechRules"
# def getSpeechRules(function):
# def isSpeechRule(function):
# def speechRuleMatches(function, text):
# def createSpeechRule(ruleClass):
# def wrapper(text, *args, **kwargs):
# def __init__(self, text, *args, **kwargs):
# def text(self):
# def test(self, text):
# def test(self, text):
# def __init__(self, regex, ignoreCase=True):
# def test(self, text):
# class SpeechRule:
# class MatchSpeechRule(SpeechRule):
# class RegexSpeechRule(SpeechRule):
#
# Path: pysiriproxy/plugins/directions.py
# _DIRECTIONS_PROP = "Directions"
# def _addDirection(direction):
# def getDirections(function):
# def isDirectionFilter(function):
# def directionsMatch(function, direction):
#
# Path: pysiriproxy/plugins/objectClasses.py
# _CLASSES_PROP = "Classes"
# def createClassFilter(className):
# def isObjectClassFilter(function):
# def getObjectClasses(function):
# def objectClassesMatch(function, objectClass):
. Output only the next line. | 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 plugin
for filterFunction in self.__filters:
# Determine if this filter function applies to the current
# object or direction
if self.__filterApplies(filterFunction, direction, obj):
# Filters return None when they ignore the object, otherwise
# they have some effect on the current object
try:
filterName = filterFunction.__name__
self.log.debug("Processing filter: %s" % filterName,
level=10)
response = filterFunction(obj, direction)
if response is not None:
return response
except:
self.log.error("Error in filter [%s]" % \
filterFunction.__name__)
self.log.error(getStackTrace())
# Object is ignored by this plugin
return None
<|code_end|>
with the help of current file imports:
from types import GeneratorType
from pysiriproxy.constants import Keys
from pysiriproxy.plugins.speechRules import isSpeechRule, speechRuleMatches, \
matches
from pysiriproxy.plugins.directions import isDirectionFilter, \
directionsMatch, From_iPhone, From_Server
from pysiriproxy.plugins.objectClasses import isObjectClassFilter, \
objectClassesMatch, SpeechPacket, SpeechRecognized, StartRequest
from pyamp.logging import Colors
from pyamp.util import getStackTrace
and context from other files:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
#
# Path: pysiriproxy/plugins/speechRules.py
# _SPEECH_RULES_PROP = "SpeechRules"
# def getSpeechRules(function):
# def isSpeechRule(function):
# def speechRuleMatches(function, text):
# def createSpeechRule(ruleClass):
# def wrapper(text, *args, **kwargs):
# def __init__(self, text, *args, **kwargs):
# def text(self):
# def test(self, text):
# def test(self, text):
# def __init__(self, regex, ignoreCase=True):
# def test(self, text):
# class SpeechRule:
# class MatchSpeechRule(SpeechRule):
# class RegexSpeechRule(SpeechRule):
#
# Path: pysiriproxy/plugins/directions.py
# _DIRECTIONS_PROP = "Directions"
# def _addDirection(direction):
# def getDirections(function):
# def isDirectionFilter(function):
# def directionsMatch(function, direction):
#
# Path: pysiriproxy/plugins/objectClasses.py
# _CLASSES_PROP = "Classes"
# def createClassFilter(className):
# def isObjectClassFilter(function):
# def getObjectClasses(function):
# def objectClassesMatch(function, objectClass):
, which may contain function names, class names, or code. Output only the next line. | @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.__manager.completeRequest()
##### Private functions for loading filters #####
def __clearFilters(self):
'''Clear the filters for this plugin.'''
self.__filters = []
def __clearSpeechRules(self):
'''Clear the speech rules for this plugin.'''
self.__speechRules = []
def __loadFiltersAndRules(self):
'''Load all of the filters and speech rules for this Plugin.'''
self.__clearFilters()
self.__clearSpeechRules()
# Traverse all of our functions
for function in self.__getFunctions():
# Handle a filter, or speech rule function accordingly
<|code_end|>
, determine the next line of code. You have imports:
from types import GeneratorType
from pysiriproxy.constants import Keys
from pysiriproxy.plugins.speechRules import isSpeechRule, speechRuleMatches, \
matches
from pysiriproxy.plugins.directions import isDirectionFilter, \
directionsMatch, From_iPhone, From_Server
from pysiriproxy.plugins.objectClasses import isObjectClassFilter, \
objectClassesMatch, SpeechPacket, SpeechRecognized, StartRequest
from pyamp.logging import Colors
from pyamp.util import getStackTrace
and context (class names, function names, or code) available:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
#
# Path: pysiriproxy/plugins/speechRules.py
# _SPEECH_RULES_PROP = "SpeechRules"
# def getSpeechRules(function):
# def isSpeechRule(function):
# def speechRuleMatches(function, text):
# def createSpeechRule(ruleClass):
# def wrapper(text, *args, **kwargs):
# def __init__(self, text, *args, **kwargs):
# def text(self):
# def test(self, text):
# def test(self, text):
# def __init__(self, regex, ignoreCase=True):
# def test(self, text):
# class SpeechRule:
# class MatchSpeechRule(SpeechRule):
# class RegexSpeechRule(SpeechRule):
#
# Path: pysiriproxy/plugins/directions.py
# _DIRECTIONS_PROP = "Directions"
# def _addDirection(direction):
# def getDirections(function):
# def isDirectionFilter(function):
# def directionsMatch(function, direction):
#
# Path: pysiriproxy/plugins/objectClasses.py
# _CLASSES_PROP = "Classes"
# def createClassFilter(className):
# def isObjectClassFilter(function):
# def getObjectClasses(function):
# def objectClassesMatch(function, objectClass):
. Output only the next line. | 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 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(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 = obj.get('class')
return directionsMatch(function, direction) and \
<|code_end|>
. Write the next line using the current file imports:
from types import GeneratorType
from pysiriproxy.constants import Keys
from pysiriproxy.plugins.speechRules import isSpeechRule, speechRuleMatches, \
matches
from pysiriproxy.plugins.directions import isDirectionFilter, \
directionsMatch, From_iPhone, From_Server
from pysiriproxy.plugins.objectClasses import isObjectClassFilter, \
objectClassesMatch, SpeechPacket, SpeechRecognized, StartRequest
from pyamp.logging import Colors
from pyamp.util import getStackTrace
and context from other files:
# Path: pysiriproxy/constants.py
# class Keys:
# '''The Keys class defines various properties which contain strings which
# are keys to the dictionary objects sent between the iPhone and Apple's
# server.
#
# '''
#
# AceId = "aceId"
# '''The aceId key.'''
#
# AssistantId = 'AssistantId'
# '''The key for the AssistantId property of an object.'''
#
# Birthday = "birthday"
# '''The birthday key for an object.'''
#
# Class = "class"
# '''The class name for the object.'''
#
# Data = "data"
# '''The key for the data property of an object. '''
#
# Date = "date"
# '''The date key for an object.'''
#
# DateSent = "dateSent"
# '''The key for the dateSent property of an object.'''
#
# DisplayText = "displayText"
# '''The key for the displayText property of an object.'''
#
# DueDate = "dueDate"
# '''The due date key for an object.'''
#
# FirstName = "firstName"
# '''The key for the firstName property of an object.'''
#
# FullName = "fullName"
# '''The key for the fullName property of an object.'''
#
# Group = "group"
# '''The group for the object.'''
#
# Identifier = "identifier"
# '''The key for the identifier property of an object.'''
#
# Interpretations = "interpretations"
# '''The interpretations key for an object.'''
#
# Label = "label"
# '''The key for the label property of an object.'''
#
# LastName = "lastName"
# '''The key for the lastName property of an object.'''
#
# MsgSender = "msgSender"
# '''The key for the msgSender property of an object.'''
#
# Number = "number"
# '''The key for the number property of an object.'''
#
# OrderedContext = 'orderedContext'
# '''The key for the orderedContext property of an object.'''
#
# Outgoing = "outgoing"
# '''The key for the outgoing property of an object.'''
#
# Phones = "phones"
# '''The key for the phones property of an object.'''
#
# Phrases = "phrases"
# '''The phrases key for an object.'''
#
# Properties = "properties"
# '''The properties key for the object.'''
#
# Recognition = "recognition"
# '''The recognition key for an object.'''
#
# RefId = "refId"
# '''The refId for the object.'''
#
# RemoveSpaceAfter = "removeSpaceAfter"
# '''The removeSpaceAfter key for an object.'''
#
# RemoveSpaceBefore = "removeSpaceBefore"
# '''The removeSpaceBefore key for an object.'''
#
# SelectionResponse = "selectionResponse"
# '''The key for the selectionResponse property of an object.'''
#
# SessionValidationData = 'SessionValidationData'
# '''The key for the SessionValidationData property of an object.'''
#
# SpeakableSelectionResponse = "speakableSelectionResponse"
# '''The key for the speakableSelectionResponse property of an object.'''
#
# SpeakableText = "speakableText"
# '''The speakable text key for an object.'''
#
# SpeechId = 'SpeechId'
# '''The key for the SpeechId property of an object.'''
#
# Street = "street"
# '''The street value.'''
#
# Text = "text"
# '''The text key for an object.'''
#
# TheatricalReleaseDate = "theatricalReleaseDate"
# '''The theatrical release date.'''
#
# Title = "title"
# '''The title key for an object.'''
#
# Tokens = "tokens"
# '''The tokens key for an object.'''
#
# Utterance = "utterance"
# '''The utterance key for an object.'''
#
# Version = "v"
# '''The version key for an object.'''
#
# Path: pysiriproxy/plugins/speechRules.py
# _SPEECH_RULES_PROP = "SpeechRules"
# def getSpeechRules(function):
# def isSpeechRule(function):
# def speechRuleMatches(function, text):
# def createSpeechRule(ruleClass):
# def wrapper(text, *args, **kwargs):
# def __init__(self, text, *args, **kwargs):
# def text(self):
# def test(self, text):
# def test(self, text):
# def __init__(self, regex, ignoreCase=True):
# def test(self, text):
# class SpeechRule:
# class MatchSpeechRule(SpeechRule):
# class RegexSpeechRule(SpeechRule):
#
# Path: pysiriproxy/plugins/directions.py
# _DIRECTIONS_PROP = "Directions"
# def _addDirection(direction):
# def getDirections(function):
# def isDirectionFilter(function):
# def directionsMatch(function, direction):
#
# Path: pysiriproxy/plugins/objectClasses.py
# _CLASSES_PROP = "Classes"
# def createClassFilter(className):
# def isObjectClassFilter(function):
# def getObjectClasses(function):
# def objectClassesMatch(function, objectClass):
, which may include functions, classes, or code. Output only the next line. | 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 = getDirections(function)
return directions is not None and len(directions) > 0
def directionsMatch(function, direction):
'''Determine if the given direction is found in the list
of directions for this function.
* function -- The function
* direction -- The given direction
'''
directions = getDirections(function)
return directions is None or len(directions) == 0 \
or direction in directions
# Define all of the direction decorators
<|code_end|>
, predict the next line using imports from the current file:
from pysiriproxy.constants import Directions
from pyamp.patterns import listProperty
and context including class names, function names, and sometimes code from other files:
# Path: pysiriproxy/constants.py
# class Directions:
# '''The Directions class contains several properties which are used to
# indicate which direction data is entering the system.
#
# '''
#
# From_Server = "From_Server"
# '''The From_Server property indicates that data was received from Apple's
# server.
#
# '''
#
# From_iPhone = "From_iPhone"
# '''The From_iPhone property indicates that data was received from the
# iPhone.
#
# '''
. Output only the next line. | 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, objectClass):
'''Determine if the given object class is found in the list
of object classes for this function.
* function -- The function
* objectClass -- The given object classes
'''
objectClasses = getObjectClasses(function)
return objectClasses is None or len(objectClasses) == 0 or \
objectClass in objectClasses
# Grab a reference to the current module object so we can add
# attributes to it
thisModule = sys.modules[__name__]
# Create class filter decorators for all of the known class names
<|code_end|>
, predict the next line using imports from the current file:
import sys
from pysiriproxy.constants import ClassNames
from pyamp.patterns import listProperty
and context including class names, function names, and sometimes code from other files:
# Path: pysiriproxy/constants.py
# class ClassNames(Enum):
# '''The ClassNames class contains properties which define the names of the
# class names of objects sent between the iPhone and Apple's server.
#
# '''
# AnyObject = "AnyObject"
# '''The AnyObject property defined the AnyObject object class.'''
#
# CancelRequest = "CancelRequest"
# '''The CancelRequest property defined the CancelRequest object class.'''
#
# CancelSpeech = "CancelSpeech"
# '''The CancelSpeech property defined the CancelSpeech object class.'''
#
# ClearContext = "ClearContext"
# '''The ClearContext property defined the ClearContext object class.'''
#
# CommandIgnored = "CommandIgnored"
# '''The CommandIgnored property defined the CommandIgnored object class.'''
#
# CommandFailed = "CommandFailed"
# '''The CommandFailed property defined the CommandFailed object class.'''
#
# FinishSpeech = "FinishSpeech"
# '''The FinishSpeech property defined the FinishSpeech object class.'''
#
# LoadAssistant = "LoadAssistant"
# '''The LoadAssistant property defined the LoadAssistant object class.'''
#
# RequestCompleted = "RequestCompleted"
# '''The RequestCompleted property defined the RequestCompleted object
# class.
#
# '''
#
# SetApplicationContext = "SetApplicationContext"
# '''The SetApplicationContext property defined the SetApplicationContext
# object class.
#
# '''
#
# SetRequestOrigin = "SetRequestOrigin"
# '''The SetRequestOrigin property defined the SetRequestOrigin object
# class.
#
# '''
#
# SetRestrictions = "SetRestrictions"
# '''The SetRestrictions property defined the SetRestrictions object class.
#
# '''
#
# SpeechPacket = "SpeechPacket"
# '''The SpeechPacket property defined the SpeechPacket object class.'''
#
# SpeechRecognized = "SpeechRecognized"
# '''The SpeechRecognized property defined the SpeechRecognized object
# class.
#
# '''
#
# StartRequest = "StartRequest"
# '''The StartRequest property defined the StartRequest object class.'''
#
# StartSpeechRequest = "StartSpeechRequest"
# '''The StartSpeechRequest property defined the StartSpeechRequest
# object class.
#
# '''
. Output only the next line. | 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)
@classmethod
def getDirection(cls):
'''Get the data direction for this Connection.'''
return cls.Direction
##### Private functions #####
@classmethod
def __log(cls, message):
'''Log an information message to the output.
* message -- The message to log
'''
logger = LogData().get(cls.Direction, color=Colors.Foreground.Red)
logger.info(message)
class iPhone(Connection):
'''Create an iPhone Connection for testing.'''
<|code_end|>
using the current file's imports:
from pysiriproxy.constants import Directions
from pyamp.logging import LogData, LogLevel, Colors
and any relevant context from other files:
# Path: pysiriproxy/constants.py
# class Directions:
# '''The Directions class contains several properties which are used to
# indicate which direction data is entering the system.
#
# '''
#
# From_Server = "From_Server"
# '''The From_Server property indicates that data was received from Apple's
# server.
#
# '''
#
# From_iPhone = "From_iPhone"
# '''The From_iPhone property indicates that data was received from the
# iPhone.
#
# '''
. Output only the next line. | 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 item snippet to be displayed
to the iPhone user.
'''
def __init__(self, useCurrentLocation=True, items=None):
'''
* useCurrentLocation -- True to use the user's current location
* items -- The list of map items
'''
SiriObject.__init__(self, "MapItemSnippet",
"com.apple.ace.localsearch")
self.useCurrentLocation = useCurrentLocation
self.items = [] if items is None else items
class _ShowMapPoints(SiriObject):
'''The _ShowMapPoints class creates a series of map poitns to be displayed
to the iPhone user.
'''
def __init__(self, showDirections=True, showTraffic=False,
<|code_end|>
with the help of current file imports:
from pysiriproxy.constants import DirectionTypes
from pysiriproxy.objects.baseObject import SiriObject
and context from other files:
# Path: pysiriproxy/constants.py
# class DirectionTypes:
# '''The DirectionTypes class encapsulates the various modes of
# transportation which can be used to generate directions.
#
# '''
# Driving = "ByCar"
# '''Directions for driving.'''
#
# PublicTransit = "ByPublicTransit"
# '''Directions for public transportation.'''
#
# Walking = "Walking"
# '''Directions for walking.'''
#
# Path: pysiriproxy/objects/baseObject.py
# class SiriObject:
# '''The SiriObject class encapsulates the base functionality for all
# object being sent to the iPhone or to Apple's web server.
#
# .. note:: This class is meant to be subclassed to provide the
# implementation for a specific object.
#
# '''
#
# ProtocolVersion = "2.0"
# '''The identifier which indicates the version of the protocol.'''
#
# def __init__(self, className, group):
# '''
# * className -- The class name for the object
# * 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 list of strings which represent names of input variables and
# sets properties of the same name on the current object if the value of
# the argument is not None.
#
# * argumentNames -- The list of argument names to set
# * localVars -- The local variables
#
# '''
# for argName in argumentNames:
# # Get the value of the local argument
# argValue = localVars.get(argName)
#
# # Only set the argument if its value is not None
# if argValue is not None:
# setattr(self, argName, argValue)
#
# def toDict(self):
# '''Convert this object into a Python dictionary.'''
# dictionary = {
# Keys.Class: self.__class,
# Keys.Group: self.__group,
# Keys.Properties: {},
# }
#
# # Store the refId, aceId, and version values if we have one
# if self.__refId is not None:
# dictionary[Keys.RefId] = self.__refId
# if self.__aceId is not None:
# dictionary[Keys.AceId] = self.__aceId
# if self.__version is not None:
# dictionary[Keys.Version] = self.__version
#
# # Traverse all of the object's properties to add them each to
# # the output dictionary object
# for key, item in self.__getProperties().iteritems():
# # Determine how to handle the current property type
# if type(item) == type(list()):
# itemList = []
#
# # Convert all the items in the list to a dictionary, and keep
# # only the properties that are successfully converted
# for val in item:
# try:
# val = val.toDict()
# except:
# pass
# itemList.append(val)
#
# dictionary[Keys.Properties][key] = itemList
# else:
# # Attempt to conver the current property into a dictionary
# try:
# item = item.toDict()
# except:
# pass
#
# dictionary[Keys.Properties][key] = item
#
# return dictionary
#
# def makeRoot(self, refId=None, aceId=None):
# '''Make the SiriObject the root object.
#
# * refId -- The refId for this object
# * aceId -- The aceId for this object
#
# '''
# self.setRefId(refId)
# self.setAceId(aceId)
#
# # Only the root object has a version entry
# self.__version = self.ProtocolVersion
#
# def setRefId(self, refId=None):
# '''Set the ref id for this object.
#
# * refId -- The refId for this object
#
# '''
# self.__refId = refId if refId is not None else self.__randomRefId()
#
# def setAceId(self, aceId=None):
# '''Set the ace id for this object.
#
# * aceId -- The aceId for this object
#
# '''
# self.__aceId = aceId if aceId is not None else self.__randomAceId()
#
# def __getProperties(self):
# '''Get all of the properties for this SiriObject.'''
# return dict((k, p) for k, p in self.__dict__.iteritems() \
# if not k.startswith("_"))
#
# @classmethod
# def __randomRefId(cls):
# '''Create a random refId.'''
# return str(uuid4()).upper()
#
# @classmethod
# def __randomAceId(cls):
# '''Create a random aceId.'''
# return str(uuid4())
#
# @classmethod
# def isArgumentList(cls, obj):
# '''Determine if the given object is a list of arguments, or not.
#
# * obj -- The object
#
# '''
# return not SiriObject.isSiriObject(obj) and type(obj) == type(tuple())
#
# @classmethod
# def isSiriObject(cls, obj):
# '''Determine if the given object is a SiriObject, or not.
#
# * obj -- The object
#
# '''
# return isinstance(obj, SiriObject)
, which may contain function names, class names, or code. Output only the next line. | 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=['accuracy'])
print()
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print("Model architecture")
plot(model, show_shapes=True, to_file=FOLDER+"lstm_priority_sort.png")
print("Model summary")
print(model.summary())
print("Model parameter count")
print(model.count_params())
print()
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print("Training...")
# Train the model each generation and show predictions against the
# validation dataset
losses = []
acces = []
for iteration in range(1, 3):
print()
print('-' * 78)
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print('Iteration', iteration)
<|code_end|>
, predict the next line using imports from the current file:
from keras.models import Sequential
from keras.layers import Activation, TimeDistributed, Dense, recurrent
from keras.utils.visualize_util import plot # Add by Steven Robot
from keras.layers import Merge # Add by Steven Robot
from keras.callbacks import Callback # Add by Steven Robot
from keras.callbacks import ModelCheckpoint # Add by Steven Robot
from util import LossHistory # Add by Steven Robot
import numpy as np
import dataset # Add by Steven Robot
import visualization # Add by Steven
import time # Add by Steven Robot
import os # Add by Steven Robot
import sys # Add by Steven Robot
and context including class names, function names, and sometimes code from other files:
# Path: util.py
# class LossHistory(Callback):
# def on_train_begin(self, logs={}):
# self.losses = []
# self.acces = []
#
# def on_batch_end(self, batch, logs={}):
# self.losses.append(logs.get('loss'))
# self.acces.append(logs.get('acc'))
. Output only the next line. | history = LossHistory() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.