Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|># All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #...
patcher = mock.patch(name)
Given the following code snippet before the placeholder: <|code_start|> class DriverManagerTestCase(base.BaseTestCase): def setUp(self): super(DriverManagerTestCase, self).setUp() def test_initialize_called(self): driver1 = Extension('mock_driver1', Mock(), None, ...
mocked_context)
Given the code snippet: <|code_start|> mock_method = Mock(side_effect=fc_exc.FlowClassifierException) setattr(driver.obj, method_name, mock_method) manager = FlowClassifierDriverManager.make_test_instance([driver]) mocked_context = Mock() self.assertRaises(expected_exc, ...
def test_update_flow_classifier_postcommit_exception(self):
Given the code snippet: <|code_start|> self.assertEqual(self.plugin_context_precommit.current, fc['flow_classifier']) self.assertEqual(self.plugin_context_postcommit.current, fc['flow_classifier']) def _test_delete_flo...
self._test_delete_flow_classifier_driver_manager_exception()
Given the following code snippet before the placeholder: <|code_start|> .assert_called_once_with(mock.ANY)) self.assertIsInstance( self.plugin_context, fc_ctx.FlowClassifierContext ) self.assertIsInstance( self.plugi...
driver_manager = self.fake_driver_manager
Next line prediction: <|code_start|> }) as fc: driver_manager = self.fake_driver_manager (driver_manager.create_flow_classifier_precommit .assert_called_once_with(mock.ANY)) (driver_manager.create_flow_classifier_postcommit .as...
self.fmt, {'logical_source_port': port['port']['id']},
Using the snippet: <|code_start|> LOG = logging.getLogger(__name__) cfg.CONF.import_group('OVS', 'neutron.plugins.ml2.drivers.openvswitch.agent.' 'common.config') # This table is used to process the traffic across differet subnet scenario. # Flow 1: pri=1, ip,dl_dst=nexthop_mac,nw_src=ne...
TAP_TUNNEL_OUTPUT_TABLE = 25
Predict the next line after this snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is...
INGRESS_TABLE = 10
Predict the next line for this snippet: <|code_start|># WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # pp1 = uuidutils.generate_uuid() pp2 = uuidutils.generate_uuid() pp3 = uuidutils....
'._discover_via_entry_points')
Predict the next line for this snippet: <|code_start|># Copyright 2015 Futurewei. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.o...
cfg.CONF.register_opts(FLOWCLASSIFIER_DRIVER_OPTS, "flowclassifier")
Continue the code snippet: <|code_start|> floatX = theano.config.floatX tol = 1e-4 def _wta(X): M = K.max(X, axis=-1, keepdims=True) R = K.switch(K.equal(X, M), X, 0.) <|code_end|> . Use current file imports: import numpy as np import theano import theano.tensor as T from keras.layers.recurrent import Recu...
return R
Continue the code snippet: <|code_start|> def _IstaStep(cost, states, lr=.001, lambdav=.1, x_prior=0): grads = T.grad(cost, states) new_x = states-lr*grads if x_prior != 0: new_x += lambdav*lr*.1*_proxInnov(states, x_prior) new_states = _proxOp(new_x, lr*lambdav) return theano.gradient.disc...
def __init__(self, input_dim, output_dim,
Continue the code snippet: <|code_start|> activity_regularizer.set_layer(self) self.regularizers.append(activity_regularizer) kwargs['input_shape'] = (self.input_dim,) super(SparseCoding, self).__init__(**kwargs) @property def output_shape(self): input_shape = se...
sequences=[],
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
).version,
Predict the next line for this snippet: <|code_start|> def test_list_voices_flattened(): client = TextToSpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_voices), "__call__")...
)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
class TextToSpeechTransport(abc.ABC):
Using the snippet: <|code_start|>class WordDictSyn: def __init__(self): self.__words = {} self.__stemmer = SnowballStemmer("german", ignore_stopwords=False) self.__id_mapping = {} self.__current_mapping_id = 0 def analyze(self, word_list): cleaned_list = [] ...
item.add_variant(word_list[i])
Here is a snippet: <|code_start|> def test_url_prefix(): url = "http://127.0.0.1:5000" meta = requests.get(url, headers={'Accept': 'application/json'}).json() url_prefix, __, __ = parse_meta(meta) assert url_prefix == "" def test_resjs_web(tmpdir): resjs("http://127.0.0.1:5000", tmpdir.join("res.j...
resp = requests.get("http://127.0.0.1:5000?f=docs.min.css")
Given the following code snippet before the placeholder: <|code_start|> def test_url_prefix(): url = "http://127.0.0.1:5000" meta = requests.get(url, headers={'Accept': 'application/json'}).json() url_prefix, __, __ = parse_meta(meta) assert url_prefix == "" def test_resjs_web(tmpdir): resjs("htt...
resjs2 = requests.get("http://127.0.0.1:5000?f=res.js")
Given the code snippet: <|code_start|> def test_resjs_web(tmpdir): resjs("http://127.0.0.1:5000", tmpdir.join("res.js").strpath, prefix="/api", min=True) assert tmpdir.join("res.js").check() def test_resjs_node(tmpdir): resjs("http://127.0.0.1:5000", tmpdir.join("res.js").strpath, node=True) ...
dest = tmpdir.join("res.js").strpath
Given the following code snippet before the placeholder: <|code_start|> sys.path.append('./server') app = importlib.import_module("index").app @pytest.fixture(params=[ {"url_prefix": "http://127.0.0.1:5000"}, {"test_client": app.test_client} ]) def res(request): return Res(**request.param) def test_bas...
def test_ajax(res):
Here is a snippet: <|code_start|> } Event(timestamp=datetime.now(), user=self.request.user, type=msg['type'], message=msg['message']).save() Pusher.send("activity", "my_event", msg) return self.render_json_response(json_dict) class AddExp(JSONResponseMixin, AjaxResponseMixin, View): ...
if self.request.user.credits:
Given snippet: <|code_start|> amount ) } Event(timestamp=datetime.now(), user=self.request.user, type=msg['type'], message=msg['message']).save() Pusher.send("activity", "my_event", msg) return self.render_json_response(json_dict) class GiveCoin(JSONResponseM...
class BuyView(JSONResponseMixin, AjaxResponseMixin, View):
Predict the next line after this snippet: <|code_start|> amount = random.randint(1, 100) self.request.user.exp += amount self.request.user.save() json_dict = { 'exp': self.request.user.exp, } msg = { "type": "rpg", "user": self.request.u...
'my': self.request.user.credits,
Based on the snippet: <|code_start|># Create your views here.from datetime import datetime __all__ = ( 'StreamView', 'ChatSendView', <|code_end|> , predict the immediate next line with the help of imports: import os import random import misaka as m from django.conf import settings from django.contrib.auth i...
'HistoryView'
Given the code snippet: <|code_start|> class StreamView(LoginRequiredMixin, TemplateView): template_name = 'activity/stream.html' def get_context_data(self, **kwargs): context = super(StreamView, self).get_context_data(**kwargs) return context class HistoryView(LoginRequiredMixin, JSONRespons...
}
Predict the next line after this snippet: <|code_start|> logger = logging.getLogger(__name__) class Marcotti(object): def __init__(self, config): logger.info("Marcotti v{0}: Python {1} on {2}".format( __version__, sys.version, sys.platform)) <|code_end|> using the current file's imports: ...
logger.info("Opened connection to {0}".format(self._public_db_uri(config.database_uri)))
Next line prediction: <|code_start|> try: # first get the member meme that the dict refers to memberMeme = templateRepository.resolveTemplate(memePath, memeberMemePath) try: #naturally, that meme should have a registered metameme ...
pass
Next line prediction: <|code_start|> #Meme members are stored in unresolved form. When validating, we'll have to pass the full template paths resolvedMembers = {} unresolvedMember = False for unresolvedMemberMeme in self.memberMemes.keys(): me...
exception = "Meme %s is invalid because member meme %s is invalid. Ivalidity is inherited from members.!" %(self.path.fullTemplatePath, resolvedMemberMemeKey)
Predict the next line after this snippet: <|code_start|> enhancedByMeme = templateRepository.resolveTemplateAbsolutely(enhancedBy) enhancedByMM = enhancedByMeme.metaMeme try: assert enhancedByMM not in enhancedByMemesList enhancedByM...
errorMsg = "Error validating meme %s. Traceback = %s" %(self.path.fullTemplatePath, e)
Given the code snippet: <|code_start|> maxVal = None try: minStr = restrictionMMIElement.getAttribute("restrictionMin") minVal = int(minStr) except: pass try: maxStr = restrictionMMIElement.getAttribute("restrictionMax") ...
for restrictionValElement in restrictionElement.getElementsByTagName("RestrictionValueInteger"):
Continue the code snippet: <|code_start|> stringArray = str.split(eachReadLine) Graph.logQ.put( [logType , logLevel.DEBUG , method , "Starting testcase %s, meme %s" %(n, stringArray[0])]) testResult = False try: entityID = Graph.api.createEntityFromMeme(stringArray[0]) ...
testResult = False
Next line prediction: <|code_start|> class MifareClassic4k(): def __init__(self, carddata): self._carddata = carddata <|code_end|> . Use current file imports: (from rfid.formats.mifare.Mifare import MifareSector) and context including class names, function names, or small code snippets from other fi...
self._num_blocks = 256
Given the following code snippet before the placeholder: <|code_start|>try: except ImportError: @patch("lighthouse.checks.tcp.socket") <|code_end|> , predict the next line using imports from the current file: import unittest2 as unittest import unittest import errno import socket from mock import patch fro...
class TCPCheckTests(unittest.TestCase):
Here is a snippet: <|code_start|> list(check.results), [False, False] ) @patch.object(Check, "apply_check_config", Mock()) @patch.object(Check, "validate_config", Mock()) @patch.object(Check, "get_installed_classes") def test_from_config_uses_installed_classes(self, get_i...
)
Predict the next line for this snippet: <|code_start|> cluster.name = "datastore" cluster.haproxy = { "port": 99 } stanza = FrontendStanza(cluster, bind_address="127.0.0.1") self.assertEqual( stanza.lines, [ "bind 127.0.0.1:99"...
[
Based on the snippet: <|code_start|>try: except ImportError: class RedisCheckTests(unittest.TestCase): def test_query_and_response_values(self): check = RedisCheck() check.apply_config({ "host": "127.0.0.1", "port": 1234, "rise": 1, "fall": 1 }) <|code_end|> , pr...
self.assertEqual(check.query, "PING")
Continue the code snippet: <|code_start|>try: except ImportError: @patch("lighthouse.scripts.reporter.reporter.Reporter") @patch("lighthouse.scripts.reporter.parser") <|code_end|> . Use current file imports: import unittest2 as unittest import unittest from mock import patch from lighthouse.scripts import ...
class ReporterScriptTests(unittest.TestCase):
Given the following code snippet before the placeholder: <|code_start|>try: except ImportError: class BaseStanzaTests(unittest.TestCase): <|code_end|> , predict the next line using imports from the current file: import unittest2 as unittest import unittest from lighthouse.haproxy.stanzas.stanza import Stan...
def test_no_lines(self):
Predict the next line after this snippet: <|code_start|>try: except ImportError: class TestTarget(object): name = "target" config_subdirectory = None class TestTargetWithSubdir(object): name = "target" config_subdirectory = "bazz" @patch("lighthouse.configs.monitor.os") class ConfigMonitorTests...
def test_adds_subdirectory_to_file_path(self, mock_os):
Predict the next line for this snippet: <|code_start|> wait_args, _ = wait_on_event.call_args composite = wait_args[0] self.assertEqual(composite.is_set(), False) event2.set() self.assertEqual(composite.is_set(), True) @patch.object(events, "wait_on_event") def test_a...
self.assertEqual(composite.is_set(), True)
Next line prediction: <|code_start|>try: except ImportError: @patch("lighthouse.scripts.writer.writer.Writer") @patch("lighthouse.scripts.writer.parser") class WriterScriptTests(unittest.TestCase): def test_run_handles_keyboardinterrupt(self, parser, Writer): Writer.return_value.start.side_effect = Key...
def test_log_setup_called(self, log, parser, Writer):
Predict the next line for this snippet: <|code_start|> SOCKET_BUFFER_SIZE = 8192 version_re = re.compile('.*(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+).*') first_cap_re = re.compile('(.)([A-Z][a-z]+)') <|code_end|> with the help of current file imports: import collections import errno import logging import os i...
all_cap_re = re.compile('([a-z0-9])([A-Z])')
Based on the snippet: <|code_start|>try: except ImportError: class Balancertests(unittest.TestCase): def test_entrypoint(self): self.assertEqual(Balancer.entry_point, "lighthouse.balancers") @patch.object(Balancer, "apply_config") @patch.object(Balancer, "validate_config") def test_sync_fi...
self.assertEqual(balancer, MockBalancer.return_value)
Given the following code snippet before the placeholder: <|code_start|>try: except ImportError: class StatsStanzaTests(unittest.TestCase): def test_default_uri(self): stanza = StatsStanza(9000) <|code_end|> , predict the next line using imports from the current file: import unittest2 as unittest ...
self.assertEqual(
Here is a snippet: <|code_start|> "abalancer": Balancer(), "otherbalancer": Balancer() } self.assertRaises( ValueError, Cluster.validate_config, {"discovery": "zookeeper"} ) @patch("lighthouse.cluster.Balancer") def test_applying_config(se...
"otherbalancer": Balancer()
Predict the next line for this snippet: <|code_start|>try: except ImportError: class SectionTests(unittest.TestCase): def test_no_stanzas(self): section = Section("A Section") self.assertTrue( "# No stanzas defined for this section." in str(section) ) def test_heading(s...
stanza2.lines = ["reticulate_splines=true"]
Based on the snippet: <|code_start|> def test_no_stanzas(self): section = Section("A Section") self.assertTrue( "# No stanzas defined for this section." in str(section) ) def test_heading(self): section = Section("This is a section, ok") self.assertTrue( ...
self.assertEqual(
Next line prediction: <|code_start|> class BackendStanzaTests(unittest.TestCase): def test_includes_cookie_in_http_mode(self): http_node = Mock(host="server1.int", ip="10.0.1.12", port=8000) http_node.name = "server1.int:8000" cluster = Mock() cluster.name = "accounts" clu...
cluster = Mock()
Next line prediction: <|code_start|> included_stanzas = [] def add_included_stanzas(heading, *stanzas): included_stanzas.extend(stanzas) Section.side_effect = add_included_stanzas global_stanza = Mock("global") defaults_stanza = Mock("defaults") config = HA...
Section.side_effect = add_included_stanzas
Using the snippet: <|code_start|>try: except ImportError: class ProxyStanzaTests(unittest.TestCase): def test_optional_bind_address(self): stanza = ProxyStanza("payserver", 2222, [], bind_address="0.0.0.0") self.assertEqual(stanza.header, "listen payserver") self.assertIn("bind 0.0.0.0:...
[
Predict the next line for this snippet: <|code_start|>try: except ImportError: test_content = """ port: 8888 extras: <|code_end|> with the help of current file imports: import unittest2 as unittest import unittest import sys from mock import patch, Mock, mock_open from watchdog import events from lighth...
- "foo"
Continue the code snippet: <|code_start|> ] self.assertEqual( FakePlugin.get_installed_classes(), {"fakeplugin": FakePlugin} ) @patch.object(FakePlugin, "validate_config") @patch.object(FakePlugin, "apply_config") def test_from_config(self, validate_config, a...
def test_from_config__class_level_name(self, pkg_resources):
Next line prediction: <|code_start|>try: except ImportError: class ConfigurableTests(unittest.TestCase): def test_validate_config_must_be_overridden(self): self.assertRaises( NotImplementedError, Configurable.validate_config, {"foo": "bar"} ) @patch.obje...
patcher.stop()
Continue the code snippet: <|code_start|> class DiscoveryTests(unittest.TestCase): def test_validate_dependencies_requried(self): self.assertRaises( NotImplementedError, Discovery.validate_dependencies ) @patch.object(Discovery, "validate_dependencies", True) @pat...
discovery.apply_config.assert_called_once_with({"foo": "bar"})
Given the following code snippet before the placeholder: <|code_start|> class MetaFrontendStanzaTests(unittest.TestCase): def test_custom_bind_address(self): cluster1 = Mock(haproxy={}) cluster2 = Mock(haproxy={}) stanza = MetaFrontendStanza( "api", 8000, [], [cluster1, cluste...
def test_member_cluster_with_no_acls(self):
Predict the next line for this snippet: <|code_start|> check.perform() connection.request.assert_called_once_with("POST", "/foo") def test_perform_with_https(self, client): connection = client.HTTPSConnection.return_value connection.getresponse.return_value.status = 200 ch...
check.host = "localhost"
Continue the code snippet: <|code_start|> def test_deserialize(self): peer = Peer.deserialize( json.dumps({ "name": "cluster03", "ip": "196.0.0.8", "port": 3333 }) ) self.assertEqual(peer.name, "cluster03") self...
json.dumps({
Predict the next line for this snippet: <|code_start|>try: except ImportError: class NodeTests(unittest.TestCase): def test_constructor(self): peer = Peer("cluster04", 8888) node = Node("somehost", "10.0.1.12", 1234, peer=peer) self.assertEqual(node.host, "somehost") self.asser...
self.assertEqual(node.peer, current_peer.return_value)
Next line prediction: <|code_start|>try: except ImportError: class LogConfigTests(unittest.TestCase): def test_validate_config_is_noop(self): self.assertEqual( config.Logging.validate_config({}), None ) @patch("lighthouse.log.config.logging") def test_apply_conf...
def test_from_config_returns_none_on_name_mismatch(self, mock_logging):
Given snippet: <|code_start|>try: except ImportError: class PeersStanzaTests(unittest.TestCase): def test_peers(self): peer1 = Mock() peer1.name = "server1" peer1.ip = "192.168.0.13" peer1.port = "88" peer2 = Mock() peer2.name = "server2" peer2.ip = "192....
Mock(peer=None), # skipped
Using the snippet: <|code_start|> class InstituteAddressAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'hostel', 'room'] list_filter = ['hostel'] search_fields = ['user__username', 'user__first_name', 'room'] class ProgramAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'department...
class SecondaryEmailAdmin(SimpleHistoryAdmin):
Given the code snippet: <|code_start|> class InstituteAddressAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'hostel', 'room'] list_filter = ['hostel'] search_fields = ['user__username', 'user__first_name', 'room'] class ProgramAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'depar...
list_filter = ['status', 'sender', ]
Next line prediction: <|code_start|>class InstituteAddressAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'hostel', 'room'] list_filter = ['hostel'] search_fields = ['user__username', 'user__first_name', 'room'] class ProgramAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'department...
class Media:
Predict the next line after this snippet: <|code_start|> class InstituteAddressAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'hostel', 'room'] list_filter = ['hostel'] <|code_end|> using the current file's imports: from django.contrib import admin from simple_history.admin import SimpleHistoryAdm...
search_fields = ['user__username', 'user__first_name', 'room']
Given snippet: <|code_start|> class InstituteAddressAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'hostel', 'room'] list_filter = ['hostel'] search_fields = ['user__username', 'user__first_name', 'room'] class ProgramAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'department', '...
search_fields = ['user__username', 'user__first_name', 'number', ]
Using the snippet: <|code_start|> class RegistrationForm(forms.ModelForm): name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'form-control'})) authorization_grant_type = forms.ChoiceField(choices=get_choices_with_blank_dash(Application.GRANT_TYPES[:2]), ...
),
Given the following code snippet before the placeholder: <|code_start|> class RegistrationForm(forms.ModelForm): name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'form-control'})) authorization_grant_type = forms.ChoiceField(choices=get_choices_with_blank_dash(Application.GRANT_T...
attrs={'class': 'form-control', }
Using the snippet: <|code_start|> try: except ImportError: class LoginViewTestCase(TestCase): login_url = reverse('account:login') login_redirect_url = reverse(settings.LOGIN_REDIRECT_URL) next_ = reverse('oauth2_provider:list') template_name = 'account/login.html' def setUp(self): self...
def test_application_logo_default_ext(self):
Given the code snippet: <|code_start|> try: except ImportError: class LoginViewTestCase(TestCase): login_url = reverse('account:login') login_redirect_url = reverse(settings.LOGIN_REDIRECT_URL) next_ = reverse('oauth2_provider:list') template_name = 'account/login.html' def setUp(self): ...
def test_application_logo_upload(self):
Given the code snippet: <|code_start|> router = DefaultRouter() router.register('resources', ResourcesViewset, base_name='resources') urlpatterns = [ url('^api/', include(router.urls, namespace='api')), <|code_end|> , generate the next line using the imports in this file: from django.conf.urls import include, ur...
]
Continue the code snippet: <|code_start|> redirect_uris='http://localhost:7000/', logo='app_logo/1235.png', user=self.u1, ) self.app_admin = ApplicationAdmin(Application, AdminSite()) def tearDown(self): self.u1.delete() self.application1.delete() ...
self.assertEqual(self.app_admin.total_users(self.application1), 2)
Continue the code snippet: <|code_start|> ) self.assertNotEqual(str(application3), '') def test_validation_error_on_clean(self): application4 = Application( name='resource_owner_password_based_app', description='testapp', client_type=Application.CLIENT_CO...
def setUp(self):
Based on the snippet: <|code_start|> client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, redirect_uris='http://localhost:5000/', user=self.u1, ) self.assertNotEqual(str(application3), '') def tes...
self.assertNotEqual(filename, 'app_logo/987654321.png')
Next line prediction: <|code_start|> class ApplicationModelTestCase(TestCase): def setUp(self): self.u1 = User.objects.create(username='username', password='password') UserProfile.objects.create(user=self.u1) self.application1 = Application.objects.create( name='application1',...
logo='app_logo/1235.png',
Here is a snippet: <|code_start|> class ResourcesViewset(viewsets.GenericViewSet): pagination_class = DefaultLimitOffsetPagination permission_classes = [TokenHasScope] required_scopes = ['priv_rooms'] @list_route(methods=['GET'], serializer_class=UserRoomSerializer) def rooms(self, request): ...
return self.get_paginated_response(serialized_queryset.data)
Using the snippet: <|code_start|> urlpatterns = [ url(r'^login/$', LoginView.as_view(), name="login"), url(r'^logout/$', LogoutView.as_view(), name='logout'), <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import url from .views import LoginView, LogoutView and contex...
]
Predict the next line for this snippet: <|code_start|> class CustomOAuth2Validator(OAuth2Validator): def get_default_scopes(self, client_id, request, *args, **kwargs): application = get_object_or_404(get_oauth2_application_model(), client_id=client_id) return get_default_scopes(application) <|c...
def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):
Based on the snippet: <|code_start|> class ProgramSerializer(serializers.ModelSerializer): department_name = serializers.SerializerMethodField() degree_name = serializers.SerializerMethodField() def get_department_name(self, obj): return obj.get_department_display() def get_degree_name(self...
class ContactNumberSerializer(serializers.ModelSerializer):
Given the code snippet: <|code_start|>class ContactNumberSerializer(serializers.ModelSerializer): class Meta: model = ContactNumber exclude = ['user'] class InstituteAddressSerializer(serializers.ModelSerializer): hostel_name = serializers.SerializerMethodField() def get_hostel_name(self,...
super(UserSerializer, self).__init__(*args, **kwargs)
Continue the code snippet: <|code_start|> return obj.get_hostel_display() class Meta: model = InstituteAddress exclude = ['user'] class UserSerializer(serializers.ModelSerializer): program = ProgramSerializer() secondary_emails = SecondaryEmailSerializer(many=True) contacts = C...
for field in fields_to_remove:
Predict the next line for this snippet: <|code_start|> class SecondaryEmailSerializer(serializers.ModelSerializer): class Meta: model = SecondaryEmail exclude = ['user'] class ContactNumberSerializer(serializers.ModelSerializer): class Meta: model = ContactNumber exclude = ['us...
roll_number = serializers.CharField(source='userprofile.roll_number')
Given the code snippet: <|code_start|> secondary_emails = SecondaryEmailSerializer(many=True) contacts = ContactNumberSerializer(many=True) insti_address = InstituteAddressSerializer() mobile = serializers.CharField(source='userprofile.mobile') roll_number = serializers.CharField(source='userprofile....
subject = serializers.CharField()
Given the code snippet: <|code_start|> if self.room: return "%s-%s" % (self.hostel, self.room) return self.hostel return '' @python_2_unicode_compatible class Program(models.Model): user = models.OneToOneField(User, related_name='program') department = models.Cha...
class SecondaryEmail(models.Model):
Here is a snippet: <|code_start|> def __str__(self): return "%s, %s" % (self.get_degree_display(), self.get_department_display()) @python_2_unicode_compatible class ContactNumber(models.Model): user = models.ForeignKey(User, related_name='contacts') number = models.CharField(max_length=16) _hi...
status = models.BooleanField(default=True)
Here is a snippet: <|code_start|> def validate_join_year(value): current_year = timezone.now().year if value < 1958: raise ValidationError(_('%d! Are you kidding me? IITB was not even there back then!' % value)) if value > current_year: raise ValidationError(_('Welcome kiddo, welcome to II...
raise ValidationError(_('Please enter your expected graduation year'))
Given the code snippet: <|code_start|> if value > current_year: raise ValidationError(_('Welcome kiddo, welcome to IITB in future!')) def validate_graduation_year(value): current_year = timezone.now().year if value < 1958: raise ValidationError(_('%d! Are you kidding me? IITB was not even t...
return ''
Predict the next line after this snippet: <|code_start|> graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year]) degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True) _history_ = HistoricalRecords() def __str__(self): ...
message_id = models.CharField(max_length=256)
Using the snippet: <|code_start|> class DocView(TemplateView): template_name = 'sso/5-minutes-doc.html' tabs = [TabNav(tab[0], tab[1], tab[2], 'doc', tab[0] == 'basic') for tab in tabs_list] def get_context_data(self, **kwargs): context = super(DocView, self).get_context_data(**kwargs) con...
return context
Using the snippet: <|code_start|> class IndexView(TemplateView): template_name = 'sso/index.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) if request.user.is_authenticated(): context['base_template'] = 'sso/logged_in.html' else: ...
('libraries', 'Libraries', 'library.html'),
Next line prediction: <|code_start|> class IndexView(TemplateView): template_name = 'sso/index.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) if request.user.is_authenticated(): context['base_template'] = 'sso/logged_in.html' else:...
class DocView(TemplateView):
Based on the snippet: <|code_start|> class IndexView(TemplateView): template_name = 'sso/index.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) if request.user.is_authenticated(): context['base_template'] = 'sso/logged_in.html' else:...
('widgets', 'Widgets', 'widget.html'),
Predict the next line for this snippet: <|code_start|> class IndexView(TemplateView): template_name = 'sso/index.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) if request.user.is_authenticated(): context['base_template'] = 'sso/logged_in.ht...
context['login_js_url'] = static('widget/js/login.min.js')
Continue the code snippet: <|code_start|> class UserProfileAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'roll_number', 'sex', 'type'] list_filter = ['sex', 'type', ] search_fields = ['user__username', 'user__first_name', 'roll_number'] class InstituteAddressInline(admin.TabularInline): m...
fieldsets = (
Here is a snippet: <|code_start|> class UserProfileAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'roll_number', 'sex', 'type'] list_filter = ['sex', 'type', ] search_fields = ['user__username', 'user__first_name', 'roll_number'] class InstituteAddressInline(admin.TabularInline): model = ...
class ContactInline(admin.TabularInline):
Here is a snippet: <|code_start|> class UserProfileAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'roll_number', 'sex', 'type'] list_filter = ['sex', 'type', ] search_fields = ['user__username', 'user__first_name', 'roll_number'] class InstituteAddressInline(admin.TabularInline): model = ...
class SecondaryEmailInline(admin.TabularInline):
Given the code snippet: <|code_start|>class UserProfileAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'roll_number', 'sex', 'type'] list_filter = ['sex', 'type', ] search_fields = ['user__username', 'user__first_name', 'roll_number'] class InstituteAddressInline(admin.TabularInline): model =...
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
Next line prediction: <|code_start|> class UserProfileAdmin(SimpleHistoryAdmin): list_display = ['id', 'user', 'roll_number', 'sex', 'type'] list_filter = ['sex', 'type', ] search_fields = ['user__username', 'user__first_name', 'roll_number'] class InstituteAddressInline(admin.TabularInline): model...
class SecondaryEmailInline(admin.TabularInline):
Continue the code snippet: <|code_start|> class ProfilePictureForm(forms.Form): profile_picture = forms.ImageField() def clean_profile_picture(self): profile_picture = self.cleaned_data['profile_picture'] content_type = profile_picture.content_type.split('/')[0] if content_type in ['i...
'hostel': forms.Select(
Based on the snippet: <|code_start|> ), 'room': forms.TextInput( attrs={'class': 'form-control', }, ), } class ProgramForm(forms.ModelForm): def clean(self): cleaned_data = super(ProgramForm, self).clean() join_year = cleaned_data.get('joi...
'join_year': forms.NumberInput(