Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class FeatureToggleAttributesAdminInline(admin.TabularInline):
model = FeatureToggleAttribute
extra = 0
min_num = 1
class FeatureToggleAdmin(admin.ModelAdmin):
inlines = [FeatureToggleAttributesAdminInline]
def get... | admin.site.register(FeatureToggle, FeatureToggleAdmin) |
Predict the next line for this snippet: <|code_start|>
ENV_CHOICES = django_model_choices_from_iterable(Environments)
ATTRIB_CHOICES = django_model_choices_from_iterable(Attributes)
ATTRIB_KEY_MAX_LENGTH = getattr(settings, 'FEATURE_TOGGLE_ATTRIB_KEY_MAX_LEN', 100)
ATTRIB_VAL_MAX_LENGTH = getattr(settings, 'FEATURE_T... | raise FeatureToggleAttributeAlreadyExists(**dict(key=key)) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
ENV_CHOICES = django_model_choices_from_iterable(Environments)
ATTRIB_CHOICES = django_model_choices_from_iterable(Attributes)
ATTRIB_KEY_MAX_LENGTH = getattr(settings, 'FEATURE_TOGGLE_ATTRIB_KEY_MAX_LEN', 100)
ATTRIB_VAL_MAX_LENGTH = getattr(settings, 'FEAT... | self.uid = make_meanigful_id(self.name, length=5) |
Continue the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
class FeatureToggleService(object):
@classmethod
def get(cls, uid):
tgl = cls.get_model(uid)
return cls.convert(toggle_model=tgl)
@classmethod
def create(cls, toggle):
assert isinstance(toggle, B... | assert environment in Environments |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class FeatureToggleService(object):
@classmethod
def get(cls, uid):
tgl = cls.get_model(uid)
return cls.convert(toggle_model=tgl)
@classmethod
def c... | raise FeatureToggleDoesNotExist(msg) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class FeatureToggleService(object):
@classmethod
def get(cls, uid):
tgl = cls.get_model(uid)
return cls.convert(toggle_model=tgl)
@classmethod
def create(cls, toggle... | assert isinstance(toggle, BaseToggle) |
Next line prediction: <|code_start|> @classmethod
def create(cls, toggle):
assert isinstance(toggle, BaseToggle)
tgl = FeatureToggle.objects.create(name=toggle.name)
for key, value in tgl.attributes.items():
tgl.set_attribute(key, value)
@classmethod
def get_model(cls... | tgl = Toggle( |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class FeatureToggleService(object):
@classmethod
def get(cls, uid):
tgl = cls.get_model(uid)
return cls.convert(toggle_model=tgl)
@classmethod
def create(cls, toggle):
assert isi... | tgl = FeatureToggle.objects.create(name=toggle.name) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def test_given_basic_active_toggle_when_evaluated_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
simple_active_toggle = BaseToggle(
uid=1,
name="test",
<|code_end|>
. Use current file i... | environment=Environments.Local, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
def test_given_basic_active_toggle_when_evaluated_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import pytest
from... | simple_active_toggle = BaseToggle( |
Given snippet: <|code_start|> uid=1,
name="test",
environment=Environments.Local,
is_active=False,
)
assert bool(simple_active_toggle) is False
def test_given_basic_toggle_when_given_invalid_environment_then_fails():
"""
test_case_type: negative
test_case_complexity:... | simple_active_toggle = Toggle( |
Given the code snippet: <|code_start|> )
def test_given_simple_active_toggle_when_evaluated_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
today = utc_now()
some_far_away_date = today + datetime.timedelta(days=9999)
simple_active_toggle = Toggle(... | simple_active_toggle = TimeBombToggle( |
Given snippet: <|code_start|> """
simple_active_toggle = BaseToggle(
uid=1,
name="test",
environment=Environments.Local,
is_active=False,
)
assert bool(simple_active_toggle) is False
def test_given_basic_toggle_when_given_invalid_environment_then_fails():
"""
tes... | today = utc_now() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class BaseToggle(object):
"""
Interface for implementing toggle class
"""
class Attributes(object):
def __init__(self, attribs):
assert isinstance(attribs, dict)
self.attribs = attribs
def __getattr_... | assert environment in Environments |
Given the following code snippet before the placeholder: <|code_start|> self.is_active = is_active
if attributes:
self.attributes = self.Attributes(attributes)
self.kwargs = kwargs
def __bool__(self):
return bool(self.is_active)
__nonzero__ = __bool__
class Toggl... | if self.end_date_time and self.end_date_time < utc_now(): |
Given snippet: <|code_start|>
class TestToggleService(TestCase):
@classmethod
def setUpClass(cls):
cls.active_tgl = FeatureToggle.objects.create(
uid='test1',
name='test1',
environment=Environments.Local,
is_active=True,
)
cls.inactive_... | Toggle(environment=constants.FeatureToggle.Environment.LOCAL) |
Continue the code snippet: <|code_start|> is_active=True,
)
cls.inactive_tgl = FeatureToggle.objects.create(
uid='test1',
name='test1',
environment=Environments.Local,
is_active=False,
)
@classmethod
def tearDownClass(cls):
... | with self.assertRaises(FeatureToggleDoesNotExist): |
Based on the snippet: <|code_start|> ft_tgl = self.inactive_ft_tgl
ft_tgl.set_attribute(constants.FeatureToggle.Attributes.END_DATE, tomorrow)
tgl = Toggle(environment=ft_tgl.environment, name=ft_tgl.name, code=ft_tgl.code)
self.assertFalse(tgl.is_enabled())
def test_is_enabled_with_... | with self.assertRaises(FeatureToggleAlreadyExists): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class TestToggleService(TestCase):
@classmethod
def setUpClass(cls):
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from django.test import TestCase
from constants import Environments
from feature_toggle ... | cls.active_tgl = FeatureToggle.objects.create( |
Using the snippet: <|code_start|>
class TestToggleService(TestCase):
@classmethod
def setUpClass(cls):
cls.active_tgl = FeatureToggle.objects.create(
uid='test1',
name='test1',
environment=Environments.Local,
is_active=True,
)
cls.inact... | Toggle(environment=constants.FeatureToggle.Environment.LOCAL) |
Given snippet: <|code_start|>
# %% useful funcs
def coefs2mats(coefs, n=8):
const = coefs[0]
jac = coefs[1:n+1]
hes = np.zeros((n,n))
hes[np.triu_indices(n)] = hes.T[np.triu_indices(n)] = coefs[n+1:]
hes[np.diag_indices(n)] *= 2
return const, jac, hes
# invento ejemplo para testear el fit... | coefs, exps = mpf.multipolyfit(deltaX, y + ruidoY, 2, powers_out=True) |
Given the code snippet: <|code_start|>rVecsFile = imagesFolder + camera + model + "Rvecs.npy"
imageSelection = np.arange(33) # selecciono con que imagenes trabajar
# load data
imagePoints = np.load(cornersFile)[imageSelection]
n = len(imagePoints) # cantidad de imagenes
chessboardModel = np.load(patternFile)... | Xint, Ns = bl.int2flat(cameraMatrix, distCoeffs) |
Given the following code snippet before the placeholder: <|code_start|> ranking = sts.chi2.cdf(mahDist, 3)
return mahDist, ranking
else:
return mahDist
# elimino uno de los componentes que es redundante # y lo multiplico
# mul = np.array([[1],[2],[1]])
ind = [0,1,3]
ciVar = varVar(ci, N)[ind... | bl.varMahal(ci, N, cj, rank=True) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 11:47:18 2016
@author: sebalander
"""
# %% IMPORTS
# from copy import deepcopy as dc
reload(stereographic)
<|code_end|>
, predict the next line using imports from the current file:
from matplotl... | reload(unified) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 11:47:18 2016
@author: sebalander
"""
# %% IMPORTS
# from copy import deepcopy as dc
reload(stereographic)
reload(unified)
<|code_end|>
. Use current file imports:
(from matplotlib.pyplot import plot, imshow, legend, show, figure... | reload(rational) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 11:47:18 2016
@author: sebalander
"""
# %% IMPORTS
# from copy import deepcopy as dc
reload(stereographic)
reload(unified)
reload(rational)
<|code_end|>
using the current file's imports:
from matplotlib.pyplo... | reload(fisheye) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 11:47:18 2016
@author: sebalander
"""
# %% IMPORTS
# from copy import deepcopy as dc
reload(stereographic)
reload(unified)
reload(rational)
reload(fisheye)
<|code_end|>
with the help of current file imports:
fr... | reload(poly) |
Predict the next line for this snippet: <|code_start|> else:
return ee.Image.constant(value)
def makeName(img, pattern, date_pattern=None, extra=None):
""" Make a name with the given pattern. The pattern must contain the
propeties to replace between curly braces. There are 2 special words:
* '... | name = string.format(pattern, props) |
Given snippet: <|code_start|># coding=utf-8
ee.Initialize()
l8SR = ee.Image("LANDSAT/LC8_SR/LC82310772014043")
p_l8SR_no_cloud = ee.Geometry.Point([-66.0306, -24.9338])
def test_expressions():
generator = expressions.Expression()
exp_max = generator.max("b('B1')", "b('B2')")
exp_min = generator.min("b('... | vals_max = getValue(img_max, p_l8SR_no_cloud, 30, 'client') |
Next line prediction: <|code_start|># coding=utf-8
ee.Initialize()
list1 = ee.List([1, 2, 3, 4, 5])
list2 = ee.List([4, 5, 6, 7])
# helper
def assert_equal(obj, compare):
assert obj.getInfo() == compare
def test_list_intersection():
<|code_end|>
. Use current file imports:
(from geetools.tools import ee_list... | intersection = ee_list.intersection(list1, list2) |
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8
ee.Initialize()
l8SR = ee.Image("LANDSAT/LC8_SR/LC82310772014043")
p_l8SR_cloud = ee.Geometry.Point([-65.8109, -25.0185])
p_l8SR_no_cloud = ee.Geometry.Point([-66.0306, -24.9338])
list1 = ee.List([1, 2, 3, 4, 5])
list2 = ee.List([... | region_geom = getRegion(pol) |
Predict the next line after this snippet: <|code_start|>class QueryThread(QThread):
fetching_completed = pyqtSignal(object)
progress_number = pyqtSignal(object)
query_completed = pyqtSignal(object)
combobox_results = pyqtSignal(object)
def __init__(self, parent=None):
QThread.__init__(self,... | w = makam.get_work(work['mbid']) |
Continue the code snippet: <|code_start|> self.comboBox_melodic.currentIndexChanged.connect(self.set_toolbutton)
self.comboBox_form.currentIndexChanged.connect(self.set_toolbutton)
self.comboBox_rhythm.currentIndexChanged.connect(self.set_toolbutton)
self.comboBox_composer.currentIndexCha... | self.comboBox_melodic = ComboBox(self) |
Here is a snippet: <|code_start|> samplerate = 44100.
def __init__(self):
pg.GraphicsLayoutWidget.__init__(self, parent=None)
# Set 0 margin 0 spacing to cover the whole area.
self.centralWidget.setContentsMargins(0, 0, 0, 0)
self.centralWidget.setSpacing(0)
self.sectio... | self.visible = downsample_plot(raw_audio, self.limit) |
Next line prediction: <|code_start|>
class FilteringDialog(QDialog):
"""The dialog which pops up when the user clicks the combobox"""
ok_button_clicked = pyqtSignal()
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.attribute = None
self.setFixedSize(200, 300)
... | self.table_attribute = TableView() |
Here is a snippet: <|code_start|>
class FilteringDialog(QDialog):
"""The dialog which pops up when the user clicks the combobox"""
ok_button_clicked = pyqtSignal()
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.attribute = None
self.setFixedSize(200, 300)
... | self.filtering_model = FilteringModel(self) |
Given the code snippet: <|code_start|>
class FilteringDialog(QDialog):
"""The dialog which pops up when the user clicks the combobox"""
ok_button_clicked = pyqtSignal()
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.attribute = None
self.setFixedSize(200, 300... | self.proxy_model = SortFilterProxyModel(self) |
Using the snippet: <|code_start|>
:param pitch_plot: (numpy array or list) List of pitch values. Ex: [234.5, 234,3, 234.0, ...]
:param x_start: (int or float) Time stamp of starting point in seconds.
:param x_end: (int or float) Time stamp of ending point in seconds.
:param hop_size: (in... | plot_y = downsample_plot(self.pitch_plot[start:stop], self.limit) |
Given the following code snippet before the placeholder: <|code_start|>
def add_tonic(self, values):
"""
Adds tonic lines on the pitch plot.
:param values: (list or numpy array) A sequence of tonic values in Hz.
"""
# label options for the tonic values on the tonic line
... | pos_sample = cursor_pos_sample(pos, self.sample_rate, self.hopsize) |
Based on the snippet: <|code_start|> def add_tonic(self, values):
"""
Adds tonic lines on the pitch plot.
:param values: (list or numpy array) A sequence of tonic values in Hz.
"""
# label options for the tonic values on the tonic line
label_opts = {'position': 0.1, ... | pitch = current_pitch(pos_sample, self.pitch_plot) |
Predict the next line for this snippet: <|code_start|>else:
CSS_PATH = os.path.join(os.path.dirname(__file__), '..', 'ui_files', 'css',
'combobox_mac.css')
BUTTON_POS = 20
FONT_SIZE = 10
ICON_PATH_CANCEL = os.path.join(os.path.dirname(__file__), '..', 'ui_files',
... | self.dialog_filtering = FilteringDialog(self) |
Predict the next line after this snippet: <|code_start|> dir_name = dir_name[:-1] if dir_name[-1] == os.sep else dir_name
# walk all the subdirectories
for (path, dirs, files) in os.walk(dir_name):
for f in files:
has_key = (fnmatch.fnmatch(f, keyword) if match_case else
... | makams = get_makams() |
Continue the code snippet: <|code_start|> for (path, dirs, files) in os.walk(dir_name):
for f in files:
has_key = (fnmatch.fnmatch(f, keyword) if match_case else
fnmatch.fnmatch(f.lower(), keyword.lower()))
if has_key and skip_foldername not in path.split(os.sep... | forms = get_forms() |
Predict the next line after this snippet: <|code_start|> fnmatch.fnmatch(f.lower(), keyword.lower()))
if has_key and skip_foldername not in path.split(os.sep)[1:]:
try:
folders.append(str(path))
except TypeError: # already unicode
... | usuls = get_usuls() |
Given the following code snippet before the placeholder: <|code_start|> folders.append(str(path))
except TypeError: # already unicode
folders.append(path)
try:
names.append(str(f))
except TypeError: # already un... | composers = get_composers() |
Predict the next line for this snippet: <|code_start|> try:
names.append(str(f))
except TypeError: # already unicode
names.append(path)
fullnames.append(os.path.join(path, f))
if verbose:
print("> Found " + str(len(name... | performers = get_artists() |
Given the code snippet: <|code_start|> names.append(path)
fullnames.append(os.path.join(path, f))
if verbose:
print("> Found " + str(len(names)) + " files.")
return fullnames, folders, names
def sort_dictionary(dictionary, key):
"""sorts the given dictionary acc... | instruments = get_instruments() |
Continue the code snippet: <|code_start|> """Downloads the available features from Dunya-backend related with the
given docid"""
FOLDER = os.path.join(os.path.dirname(__file__), '..', 'documents')
step_completed = pyqtSignal(object)
# checking existance of documents folder in culture
if not os.... | features = document(docid)['derivedfiles'] |
Continue the code snippet: <|code_start|> print(docid, 'is not found')
return
try:
m_path = os.path.join(doc_folder, docid + '.mp3')
if not os.path.exists(m_path):
# for now, all tokens have permission to download
... | feature = get_document_as_json(docid, thetype, |
Here is a snippet: <|code_start|> def __init__(self, queue, callback, parent=None):
QThread.__init__(self, parent)
self.queue = queue
self.step_completed.connect(callback)
def run(self):
while True:
arg = self.queue.get()
if arg is None:
re... | mp3 = get_mp3(docid) |
Using the snippet: <|code_start|> given docid"""
FOLDER = os.path.join(os.path.dirname(__file__), '..', 'documents')
step_completed = pyqtSignal(object)
# checking existance of documents folder in culture
if not os.path.exists(FOLDER):
os.makedirs(FOLDER)
def __init__(self, queue, call... | except HTTPError: |
Continue the code snippet: <|code_start|>
admin.site.register(PBSServer)
admin.site.register(PBSQueue)
admin.site.register(PBSJob)
<|code_end|>
. Use current file imports:
from pytorque.models import PBSServer
from pytorque.models import PBSQueue
from pytorque.models import PBSJob
from pytorque.models import PBSUserSt... | admin.site.register(PBSUserStat) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class ChartGenerator():
@staticmethod
def getJobStatChart(title, currentTime):
statistics =\
DataPool(
series=
[{'options': {
<|code_end|>
with the help of current file imports:
from datetim... | 'source': PBSServer.objects.order_by('-time')[:20] }, #filter(time__gte=(currentTime - timedelta(hours=+2)))}, |
Next line prediction: <|code_start|> 'queued_jobs',
'total_jobs']}
])
#Step 2: Create the Chart object
chart = Chart(
datasource=statistics,
series_options=
[{'options': {
'type': 'line',
... | lastUserStatTime = PBSUserStat.objects.latest('time').time |
Using the snippet: <|code_start|> customJob.n_p = TorqueService._splitResourcesList(pbsJob[pbs.ATTR_l]['nodes'])
except KeyError:
pass
try:
customJob.setQueued(TorqueService._listToStr(pbsJob[pbs.ATTR_qtime], '|'))
... | customServer = PBSServer(name=serverName) |
Continue the code snippet: <|code_start|> customServer.total_jobs = TorqueService._listToInt(pbsServer[pbs.ATTR_total])
except KeyError:
pass
try:
customServer.running_jobs = int(TorqueService._strToDict(pbsServer[pbs.ATTR_count]... | customQueue = PBSQueue(server=pbsServer, name=queueName) |
Given snippet: <|code_start|> pass
try:
customQueue.resource_walltime = TorqueService._listToStr(pbsQueue[pbs.ATTR_rescdflt]['walltime'],
'|')
except KeyError:
pass
try:
... | customJob = PBSJob(jobId=jobName) |
Predict the next line after this snippet: <|code_start|> curr_hidden = [fwd_hidden, bwd_hidden[::-1]]
curr_dim = [dim, dim]
return bricks, hidden_list
class Model():
def __init__(self, config, vocab_size):
question = tensor.imatrix('question')
question_mask = tensor.imat... | embed.weights_init = Constant(init_embedding_table(filename='embeddings/vocab_embeddings.txt')) |
Based on the snippet: <|code_start|> assert 0 <= self.redoIndex <= len(self.redo_chain)
if self.stallNextRedo:
self.stallNextRedo = False
return
if self.processTempChange:
self.processTempChange = False
self.__redo_move(self.tempChange)
... | width = column_width(change[1]) |
Predict the next line for this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
kTestFile = "#bookmarks_test_file_with_unlikely_fi... | b1 = Bookmark(1, 5, {}) |
Next line prediction: <|code_start|>
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'],
'Email address already taken.')
def test_signup_verify_invalid_code(self):
url = reverse('authemail-signup-verify')
... | signup_code = SignupCode.objects.latest('code') |
Given the code snippet: <|code_start|> payload = {
'email': 'XXX@mail.com'
}
response = self.client.post(url, payload)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'], 'Password reset not allowed.')
def... | password_reset_code_old1 = PasswordResetCode.objects.create_password_reset_code( |
Continue the code snippet: <|code_start|> url = reverse('authemail-email-change')
for error_dict in error_dicts:
response = self.client.post(url, error_dict['payload'])
self.assertEqual(response.status_code, error_dict['status_code'])
self.assertEqual(response.data[er... | email_change_code = EmailChangeCode.objects.latest('code') |
Using the snippet: <|code_start|>
class LandingFrontEnd(TemplateView):
template_name = 'landing.html'
class SignupFrontEnd(FormView):
template_name = 'signup.html'
form_class = SignupForm
success_url = reverse_lazy('signup_email_sent_page')
def form_valid(self, form):
first_name = for... | account = wrapper.Authemail() |
Here is a snippet: <|code_start|>
class LandingFrontEnd(TemplateView):
template_name = 'landing.html'
class SignupFrontEnd(FormView):
template_name = 'signup.html'
<|code_end|>
. Write the next line using the current file imports:
from django.urls import reverse, reverse_lazy
from django.http import Http... | form_class = SignupForm |
Given the code snippet: <|code_start|>
class SignupEmailSentFrontEnd(TemplateView):
template_name = 'signup_email_sent.html'
class SignupVerifyFrontEnd(View):
def get(self, request, format=None):
code = request.GET.get('code', '')
account = wrapper.Authemail()
response = account.sign... | form_class = LoginForm |
Based on the snippet: <|code_start|>
def get_context_data(self, **kwargs):
context = super(HomeFrontEnd, self).get_context_data(**kwargs)
token = self.request.session['auth_token']
account = wrapper.Authemail()
account.users_me(token=token)
context['first_name'] = account.... | form_class = PasswordResetForm |
Here is a snippet: <|code_start|> if 'detail' in response:
form.add_error(None, response['detail'])
return self.form_invalid(form)
return super(PasswordResetFrontEnd, self).form_valid(form)
class PasswordResetEmailSentFrontEnd(TemplateView):
template_name = 'password_reset_... | form_class = PasswordResetVerifiedForm |
Given snippet: <|code_start|>class PasswordResetVerifiedFrontEnd(FormView):
template_name = 'password_reset_verified.html'
form_class = PasswordResetVerifiedForm
success_url = reverse_lazy('password_reset_success_page')
def form_valid(self, form):
code = self.request.session['password_reset_cod... | form_class = EmailChangeForm |
Continue the code snippet: <|code_start|> template_name = 'email_change_emails_sent.html'
class EmailChangeVerifyFrontEnd(View):
def get(self, request, format=None):
code = request.GET.get('code', '')
account = wrapper.Authemail()
response = account.email_change_verify(code=code)
... | form_class = PasswordChangeForm |
Here is a snippet: <|code_start|>class EmailChangeNotVerifiedFrontEnd(TemplateView):
template_name = 'email_change_not_verified.html'
class PasswordChangeFrontEnd(FormView):
template_name = 'password_change.html'
form_class = PasswordChangeForm
success_url = reverse_lazy('password_change_success_page'... | form_class = UsersMeChangeForm |
Continue the code snippet: <|code_start|>
class Signup(APIView):
permission_classes = (AllowAny,)
serializer_class = SignupSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
email = serializer.dat... | signup_code = SignupCode.objects.get(user=user) |
Based on the snippet: <|code_start|> try:
password_reset_code = PasswordResetCode.objects.get(code=code)
password_reset_code.user.set_password(password)
password_reset_code.user.save()
# Delete password reset code just used
pass... | EmailChangeCode.objects.filter(user=user).delete() |
Predict the next line after this snippet: <|code_start|>
class Logout(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
"""
Remove all auth tokens owned by request.user.
"""
tokens = Token.objects.filter(user=request.user)
for token ... | PasswordResetCode.objects.filter(user=user).delete() |
Here is a snippet: <|code_start|> if serializer.is_valid():
email = serializer.data['email']
password = serializer.data['password']
first_name = serializer.data['first_name']
last_name = serializer.data['last_name']
must_validate_email = getattr(settin... | send_multi_format_email('welcome_email', |
Based on the snippet: <|code_start|>
content = {'email': email, 'first_name': first_name,
'last_name': last_name}
return Response(content, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class SignupVerify(A... | serializer_class = LoginSerializer |
Predict the next line after this snippet: <|code_start|> else:
content = {'detail':
_('User account not verified.')}
return Response(content, status=status.HTTP_401_UNAUTHORIZED)
else:
content = {'detail':
... | serializer_class = PasswordResetSerializer |
Given the code snippet: <|code_start|>
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
class PasswordResetVerify(APIView):
permission_classes = (AllowAny,)
def get(self, request, format=None):
code = request.GET.get('code', ... | serializer_class = PasswordResetVerifiedSerializer |
Given the code snippet: <|code_start|> serializer_class = PasswordResetVerifiedSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
code = serializer.data['code']
password = serializer.data['pass... | serializer_class = EmailChangeSerializer |
Given the following code snippet before the placeholder: <|code_start|> if user_with_email.is_verified:
# Delete email change code since won't be used
email_change_code.delete()
content = {'detail': _('Email address already taken.')}
... | serializer_class = PasswordChangeSerializer |
Using the snippet: <|code_start|> return Response(content, status=status.HTTP_200_OK)
except EmailChangeCode.DoesNotExist:
content = {'detail': _('Unable to verify user.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
class PasswordChange(APIView):
permis... | serializer_class = UserSerializer |
Predict the next line after this snippet: <|code_start|>
class EmailChangeCodeInline(admin.TabularInline):
model = EmailChangeCode
fieldsets = (
(None, {
'fields': ('code', 'email', 'created_at')
}),
)
readonly_fields = ('code', 'email', 'created_at')
def has_add_permis... | add_form = EmailUserCreationForm |
Here is a snippet: <|code_start|> return False
class EmailChangeCodeInline(admin.TabularInline):
model = EmailChangeCode
fieldsets = (
(None, {
'fields': ('code', 'email', 'created_at')
}),
)
readonly_fields = ('code', 'email', 'created_at')
def has_add_permissi... | form = EmailUserChangeForm |
Here is a snippet: <|code_start|>
class SignupCodeAdmin(admin.ModelAdmin):
list_display = ('code', 'user', 'ipaddr', 'created_at')
ordering = ('-created_at',)
readonly_fields = ('user', 'code', 'ipaddr')
def has_add_permission(self, request, obj=None):
return False
class SignupCodeInline(ad... | model = SignupCode |
Given the following code snippet before the placeholder: <|code_start|> ordering = ('-created_at',)
readonly_fields = ('user', 'code', 'ipaddr')
def has_add_permission(self, request, obj=None):
return False
class SignupCodeInline(admin.TabularInline):
model = SignupCode
fieldsets = (
... | model = PasswordResetCode |
Given snippet: <|code_start|> ordering = ('-created_at',)
readonly_fields = ('user', 'code')
def has_add_permission(self, request, obj=None):
return False
class PasswordResetCodeInline(admin.TabularInline):
model = PasswordResetCode
fieldsets = (
(None, {
'fields': ('co... | model = EmailChangeCode |
Predict the next line after this snippet: <|code_start|> 'publisher_category_id': GetCategoryId(rating.category),
'date': rating.date,
'rating': rating.rating,
'url': rating.url,
}
def FeedRatingToUnified(item):
return {
'type': SOURCE_TYPE_FEED,
'publisher_id': item.feed_url,
... | FeedRatingToUnified(item) for item in feeds.FeedItem.query( |
Given the following code snippet before the placeholder: <|code_start|>
def AddRatingAtTime(user,
url,
rating,
source,
category_id,
time):
# Get existing ratings before we the new rating is added so we can tell who
# this user will be connecting to.
stats = GetRatingStats(url)
# Make sure t... | item_id=items.UrlToItemId(url)).put() |
Continue the code snippet: <|code_start|> if hasattr(self, 'category'):
result['category'] = self.category.to_dict()
return result
# Returns the list of urls this object is interested in for conversion to
# json.
def GetPageUrls(self):
return {self.url}
# Saves a url->page info map to be used... | class Recommendation(json_encoder.Serializable): |
Given the code snippet: <|code_start|> if publisher_category_id:
publisher_category_id = long(publisher_category_id)
if subscriber_category_id:
subscriber_category_id = long(subscriber_category_id)
if positive:
parts = (str(publisher_id), publisher_category_id, str(subscriber_id),
subscrib... | 'rating': ratings.POSITIVE, |
Based on the snippet: <|code_start|> date = ndb.DateTimeProperty()
time_period_numeric = ndb.IntegerProperty()
serialized_recommendation = ndb.BlobProperty()
# When False then this past recommendation is not counted as an old
# recommendation.
committed = ndb.BooleanProperty()
# Increasing number, one for ... | for time_period in time_periods.TIME_PERIODS: |
Continue the code snippet: <|code_start|> canonical_url_tasks = [
GetPageInfoAsync(page_info.canonical_url)
for page_info in page_infos
if page_info.url != page_info.canonical_url
]
for task in canonical_url_tasks:
task.get_result()
def _MetadataToPageInfo(m, key, url):
return PageInfo(
... | url = url_util.Normalize(url) |
Using the snippet: <|code_start|># Copyright 2020 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
#
# Unless required by applica... | url_util.DeduplicateUrls( |
Next line prediction: <|code_start|>#
# 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
#
# Unless required by applicable law or agreed to in w... | items.ItemIdsFromBytes(items.ItemIdsToBytes([1, 2, 3]))) |
Predict the next line after this snippet: <|code_start|> else:
stream = io.BytesIO(content)
parsed = feedparser.parse(stream)
else:
try:
parsed = feedparser.parse(url, etag=etag, modified=modified_tuple)
except StandardError as e:
logging.warning('Failed to parse feed:... | entry_date = feed_util.GetEntryDate( |
Based on the snippet: <|code_start|> if hasattr(parsed, 'etag'):
self.etag = parsed.etag
new_items = []
for entry in parsed.entries:
if not hasattr(entry, 'link') or not entry.link:
continue
if hasattr(entry, 'id') and entry.id:
entry_id = entry.id
else:
# Some... | item_id=items.UrlToItemId(canonical_url)) |
Using the snippet: <|code_start|> etag = ndb.StringProperty()
last_updated = ndb.DateTimeProperty()
def GetUrl(self):
return self.key.id()
def Update(self, canonicalize=None):
return self.UpdateAsync(
canonicalize=canonicalize, enable_async=False).get_result()
# Updates the list of items in ... | rpc = urlfetch.create_rpc(deadline=url_util.URL_FETCH_DEADLINE_SECONDS) |
Using the snippet: <|code_start|> FindContent(tree, [{
'path': './/head/link[@rel="canonical"]',
'attribute': 'href'
}, {
'path': './/head/meta[@property="og:url"]',
'attribute': 'content'
}]))
if not result.canonical_url:
result.canonical_url = final_url
... | result.estimated_reading_time = reading_time_estimator.Estimate(tree) |
Given the following code snippet before the placeholder: <|code_start|> feed. This allows us to avoid doing updates for every single new item.
Args:
publisher: The publisher that recommended the items.
num_items: The number of items the publisher recommended.
"""
for connection in self.conne... | if rating == ratings.NEUTRAL: |
Using the snippet: <|code_start|># Copyright 2020 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
#
# Unless required by applica... | class InMemoryStore(connection_trainer.ConnectionStore): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.