Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>
class Fieldset:
def __init__(self, name, index):
self.name = name
<|code_end|>
with the help of current file imports:
from decimal import Decimal as D
from django import forms
from django.utils.text import force_text
from django.utils.translation i... | self.index = index |
Given the following code snippet before the placeholder: <|code_start|> # 'Voluntarios',
# Option(_('Voluntarios'), 'volunteer-list', menu=self),
# Option(_('Detalle voluntario'), None, menu=self),
# ),
# Menu(
# 'Socios',
# ... | ), |
Given snippet: <|code_start|>
class PersonFilter(django_filters.FilterSet):
q = django_filters.CharFilter(
label=_('Nombre'),
name='name',
method='custom_filter',
widget=forms.TextInput(attrs={'placeholder': _('Nombre')}),
)
def custom_filter(self, queryset, name, value)... | return queryset.annotate( |
Predict the next line after this snippet: <|code_start|>
class GroupFilter(django_filters.FilterSet):
q = django_filters.CharFilter(name='group_name', method='custom_filter')
class Meta:
model = Group
fields = []
def custom_filter(self, queryset, name, value):
return queryset.fil... | class Meta: |
Here is a snippet: <|code_start|>#!/usr/bin/env python
class HelloRoot(object):
def index(self):
return "Hello World!"
def page(self, page):
return page
class HelloApp(App):
def initialize(self):
ctl = HelloRoot()
route = self.route()
route.mapper.explicit = Fal... | route.connect('index', '/', controller=ctl, action='index') |
Given snippet: <|code_start|>#!/usr/bin/env python
class HelloRoot(object):
def index(self):
return "Hello World!"
def page(self, page):
return page
class HelloApp(App):
def initialize(self):
ctl = HelloRoot()
route = self.route()
<|code_end|>
, continue by predicting t... | route.mapper.explicit = False |
Predict the next line after this snippet: <|code_start|> '</div>'
js_code = '''if(!window.webflash){webflash=(function(){var j=document;var k=j.cookie;var f=null;var e=false;\
var g=null;var c=/msie|MSIE/.test(navigator.userAgent);var a=function(m){return j.createTextNode(m.message)};\
var l=f... | **extra_payload) |
Based on the snippet: <|code_start|> response.set_cookie(self.cookie_name, payload)
if len(response.headers['Set-Cookie']) > 4096:
raise ValueError('Flash value is too long (cookie would be >4k)')
def prepare_payload(self, **data):
return url_quote(json_encode(data))
def js_... | def pop_payload(self): |
Given the code snippet: <|code_start|> '</div>'
js_code = '''if(!window.webflash){webflash=(function(){var j=document;var k=j.cookie;var f=null;var e=false;\
var g=null;var c=/msie|MSIE/.test(navigator.userAgent);var a=function(m){return j.createTextNode(m.message)};\
var l=function(n,m){};var... | **extra_payload) |
Next line prediction: <|code_start|>
def __init__(self, cookie_name="webflash", default_status="ok"):
self.default_status = default_status
self.cookie_name = cookie_name
def __call__(self, message, status=None, **extra_payload):
# Force the message to be unicode so lazystrings, etc... a... | if use_js: |
Predict the next line after this snippet: <|code_start|>
class AssetApp(App):
def initialize(self):
root = os.path.join(os.path.dirname(__file__), "static")
<|code_end|>
using the current file's imports:
from solo.web.app import App
from solo.web.server import WebServer
import os.path
and any relevant... | self.asset('static' ,'/', root, default_filename='index.html') |
Using the snippet: <|code_start|>#!/usr/bin/env python
class HelloRoot(object):
def index(self):
return "Hello World!"
class HelloApp(App):
def initialize(self):
ctl = HelloRoot()
route = self.route()
route.mapper.explicit = False
<|code_end|>
, determine the next line of co... | route.connect('index', '/', controller=ctl, action='index') |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# Copyright (C) 2015 Thomas Huang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is d... | 'before_error_response', 'after_error_response'] |
Next line prediction: <|code_start|>#!/usr/bin/env python
# Copyright (C) 2015 Thomas Huang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distri... | 'on_end_resource', 'on_end_request', |
Given the code snippet: <|code_start|># This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ... | def __init__(self, name='Lilac', encoding='utf8', debug=False, dispatcher=None): |
Given snippet: <|code_start|>#!/usr/bin/env python
# Copyright (C) 2015 Thomas Huang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed i... | classtype = (type, types.ClassType) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# Copyright (C) 2015 Thomas Huang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distribut... | return __ |
Given snippet: <|code_start|>class FileIter(object):
""" A fixed-block-size iterator for use as a WSGI app_iter.
``file`` is a Python file pointer (or at least an object with a ``read``
method that takes a size hint).
``block_size`` is an optional block size for iteration."""
def __init__(self, f... | class FileIterator(object): |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def main(args):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaul... | help='upstream branch (or tag) to track.') |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def main(args):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentD... | if opts.upstream_current: |
Given the code snippet: <|code_start|> parser.add_argument('branch_name')
g = parser.add_mutually_exclusive_group()
g.add_argument('--upstream_current', action='store_true',
help='set upstream branch to current branch.')
g.add_argument('--upstream', metavar='REF', default=root(),
... | sys.stderr.write('Switched to branch %s.\n' % opts.branch_name) |
Here is a snippet: <|code_start|> )
parser.add_argument('branch_name')
g = parser.add_mutually_exclusive_group()
g.add_argument('--upstream_current', action='store_true',
help='set upstream branch to current branch.')
g.add_argument('--upstream', metavar='REF', default=root(),
... | return 1 |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def main(args):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefa... | parser.add_argument('branch_name') |
Using the snippet: <|code_start|>LA 22 LOUISIANA
MA 25 MASSACHUSETTS
MD 24 MARYLAND
ME 23 MAINE
MI 26 MICHIGAN
MN 27 MINNESOTA
MO 29 MISSOURI
MS 28 MISSISSIPPI
MT 30 MONTANA
NC 37 NORTH CAROLINA
ND 38 NORTH DAKOTA
NE 31 NEBRASKA
NH 33 NEW HAMPSHIRE
NJ 34 NEW JERSEY
NM 35 NEW MEXICO
NV 32 NEVADA
NY 36 NEW YORK
OH 39 OHI... | WI 55 WISCONSIN |
Next line prediction: <|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 applicabl... | predictions = [] |
Given snippet: <|code_start|># 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 distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express... | vms_limits.append(vm_state_and_num_sample.vm_state.limit) |
Continue the code snippet: <|code_start|> if self.cap_to_limit == True:
usage = min(usage, limit)
vm_state.usage.appendleft(usage)
vm_state.limit.appendleft(limit)
def Predict(self, vm_states_and_num_samples):
total_normalized_usage = []
for idx in range(self.num... | current_total_limit += vm_state_and_num_sample.vm_state.limit[0] |
Next line prediction: <|code_start|> ] + _SecondsToMicroseconds(fortune_teller.horizon + TIME_STEP_IN_SEC)
results.append(simulation_result)
return results
def _SortBySimulatedTime(data):
key, streams = data
streams = list(streams)
streams.sort(key=lambda k: k["simulated_t... | ) |
Given the code snippet: <|code_start|>
class _State:
def __init__(self, num_history_samples):
self.num_history_samples = num_history_samples
self.usage = deque(maxlen=self.num_history_samples)
self.limit = deque(maxlen=self.num_history_samples)
class NSigmaPredictor(StatefulPredictor):
... | for idx in range(self.num_history_samples): |
Based on the snippet: <|code_start|> return PredictorFactory().CreatePredictor(config.predictor)
class PredictorFactory(object):
__instance = None
def __new__(cls):
if PredictorFactory.__instance is None:
PredictorFactory.__instance = object.__new__(cls)
PredictorFactor... | return self.decorator_factories[name]( |
Continue the code 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 appl... | predictions = [] |
Based on the snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
class _State:
def __init__(self):
self.usage = 0
class MaxPredictor(StatefulPredictor):
def __init__(self, config):
super().__init__(config)
self... | predicted_peak = sum(vms_peaks) |
Continue the code snippet: <|code_start|> self.num_history_samples = num_history_samples
self.usage = deque(maxlen=self.num_history_samples)
self.limit = deque(maxlen=self.num_history_samples)
class PerVMPercentilePredictor(StatefulPredictor):
def __init__(self, config):
super().__i... | list(vm_state_and_num_sample.vm_state.usage), |
Here is a snippet: <|code_start|> # Assume lines on left and right have opposite signed slopes
left_xs = []
left_ys = []
right_xs = []
right_ys = []
for line in lines:
for x1, y1, x2, y2 in line:
if x2 - x1 == 0: continue; # Infinite slope
slope = float(y2-y1) / fl... | cv2.line(img, (x1_left, y1), (x2_left, y2), color, thickness) |
Next line prediction: <|code_start|> with self.test_session(use_gpu=False) as sess:
t = constant_op.constant(tensor_input, shape=[1, 3, 3, 2])
argmax_op = tf.argmax(t, axis=3)
argmax = sess.run([argmax_op])
self.assertAllEqual(argmax, [[[[1, 1, 1], [0, 1, 1], [1, 0... | [[0.89411765, 0.10196079, 0.10980392, 1.]], |
Using the snippet: <|code_start|> # nets
G = generator(batch_size, gf_dim, ch, rows, cols)
G.compile("sgd", "mse")
g_vars = G.trainable_weights
print "G.shape: ", G.output_shape
E = encoder(batch_size, df_dim, ch, rows, cols)
E.compile("sgd", "mse")
e_vars... | like_loss = tf.reduce_mean(tf.square(F_legit - F_dec_fake)) / 2. |
Given snippet: <|code_start|>BATCH_SIZE = 128
LEARNING_RATE = 1e-3
STEP_PER_EPOCH = udacity_data.NUM_TRAIN_IMAGES / BATCH_SIZE
def loss(pred, labels):
train_vars = tf.trainable_variables()
norm = tf.add_n([tf.nn.l2_loss(v) for v in train_vars])
# create a summary to monitor L2 norm
tf.summary.scalar('... | x_image = tf.placeholder(tf.float32, shape=[None, 66, 200, 3], name="x_image") |
Here is a snippet: <|code_start|>dirname = os.path.dirname(os.path.abspath(__file__))
up_dir = os.path.dirname(dirname)
sys.path.append(up_dir)
class REDISDB(Backend):
name = "redis"
expiretime = 60*60*24*7 # for a week
def init(self):
logger.debug("Connecting to Redis")
self.connection = ... | def addSet(self, key, value): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
dirname = os.path.dirname(os.path.abspath(__file__))
up_dir = os.path.dirname(dirname)
sys.path.append(up_dir)
class REDISDB(Backend):
name = "redis"
<|code_end|>
, generate the next line using the imports in this file:
import sys
im... | expiretime = 60*60*24*7 # for a week |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
dirname = os.path.dirname(os.path.abspath(__file__))
up_dir = os.path.dirname(dirname)
sys.path.append(up_dir)
class LOG(DocType):
<|code_end|>
. Use current file imports:
import sys
import os
from relo.core.interfaces import DocType
... | name = "LOG Plugin" |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
dirname = os.path.dirname(os.path.abspath(__file__))
up_dir = os.path.dirname(dirname)
sys.path.append(up_dir)
class TEST(DocType):
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import os
from relo.core... | name = "TEST Plugin" |
Next line prediction: <|code_start|>#!/usr/bin/env python
#encoding: utf-8
def curl(url, path):
command = "curl -L -# -o '%s' '%s'" % (path, url)
logger.debug(command)
subprocess.call(command, shell=True)
class AbstractDownloader(object):
def __init__(self):
pass
def url2name(self, url):... | openUrl.info().split(';'))) |
Using the snippet: <|code_start|>
if progress is not None:
progress(0)
self._progress = progress
self._lastprogress = 0
self._totalread = 0
def _updateprogress(self, length):
if self._progress is not None:
self._totalread += length
progr... | return data |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
dirname = os.path.dirname(os.path.abspath(__file__))
up_dir = os.path.dirname(dirname)
sys.path.append(up_dir)
#from pyPdf import PdfFileReader
class PDF(DocType):
name = "PDF Plugin"
def load(self, path):
#self.path = path... | process_pdf(rsrcmgr, device, fp) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
class AbstractUpdater(object):
def __init__(self):
self.localVersion = 0
self.remoteVersion = 0
def getLocalVersion(self):
pass
<|code_end|>
. Use current file imports:
from relo.core.log import logger
fr... | def getRemoteVersion(self): |
Using the snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
class AbstractUpdater(object):
def __init__(self):
self.localVersion = 0
<|code_end|>
, determine the next line of code. You have imports:
from relo.core.log import logger
from relo.core.config import conf, RELO_DEVELOP_VERSION_URL,... | self.remoteVersion = 0 |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
class AbstractUpdater(object):
def __init__(self):
self.localVersion = 0
self.remoteVersion = 0
def getLocalVersion(self):
pass
<|code_end|>
, generate the next line using the imports in this file:
from relo... | def getRemoteVersion(self): |
Next line prediction: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
class AbstractUpdater(object):
def __init__(self):
self.localVersion = 0
self.remoteVersion = 0
def getLocalVersion(self):
pass
def getRemoteVersion(self):
<|code_end|>
. Use current file imports:
(from re... | pass |
Using the snippet: <|code_start|>
try:
# available in python-2.5 and greater
except ImportError:
# compatibility fallback
logger = getLogger("pki")
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import string
import random
import pki.models
from subprocess import Pop... | def refresh_pki_metadata(ca_list): |
Here is a snippet: <|code_start|>
try:
# available in python-2.5 and greater
except ImportError:
# compatibility fallback
logger = getLogger("pki")
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import string
import random
import pki.models
from subprocess import Po... | def refresh_pki_metadata(ca_list): |
Given the code snippet: <|code_start|>#Save the available component classes names defined in CL. This are the classes
#defined in pyoptools.raytrace.comp_lib
_av_comp=[]
#for cl in dir(CL):
# if cl[0].isupper():
# _av_comp.append(cl)
# Replace the check for something more robust than checking if the firs ch... | type=self.parser.get(cmp,"type") |
Using the snippet: <|code_start|>
class Job(models.Model):
SCHEDULED = 0
QUEUED = 1
FINISHED = 2
FAILED = 3
STARTED = 4
FLOW = 5
STATUS_CHOICES = (
(SCHEDULED, 'scheduled'),
(QUEUED, 'queued'),
(FINISHED, 'finished'),
(FAILED, 'failed'),
(STARTED, '... | status = models.PositiveIntegerField(null=True, |
Given snippet: <|code_start|> if name is None:
name = 'Stranger'
return 'Hi there, %s!' % (name,)
def do_nothing():
"""The best job in the world."""
pass
def div_by_zero(x):
"""Prepare for a division-by-zero exception."""
return x / 0
def some_calculation(x, y, z=1):
"""Some arb... | time.sleep(timeout) |
Continue the code snippet: <|code_start|>
class TestGetRestrictedDatetime(unittest.TestCase):
def setUp(self):
self.dt = datetime(2013, 1, 1, 6, tzinfo=utc)
@params(
('0-24', datetime(2013,1,1,6, tzinfo=utc)),
('1.30 - 5.30', datetime(2013,1,2,1,30, tzinfo=utc)),
<|code_end|>
. Use cu... | ('7:00-8:00', datetime(2013,1,1,7,0, tzinfo=utc)), |
Based on the snippet: <|code_start|>
class TestGetRestrictedDatetime(unittest.TestCase):
def setUp(self):
self.dt = datetime(2013, 1, 1, 6, tzinfo=utc)
@params(
('0-24', datetime(2013,1,1,6, tzinfo=utc)),
('1.30 - 5.30', datetime(2013,1,2,1,30, tzinfo=utc)),
<|code_end|>
, predict the... | ('7:00-8:00', datetime(2013,1,1,7,0, tzinfo=utc)), |
Given the following code snippet before the placeholder: <|code_start|>try:
except ImportError: # not 2.6+ or is 3.x
try:
except ImportError:
<|code_end|>
, predict the next line using imports from the current file:
from itertools import tee
from future_builtins import zip
from itertools import izi... | pass |
Given the code snippet: <|code_start|>log = logging.getLogger("safecity.tropo.views")
KEYWORDS = {
'JOIN': ['join', 'register'],
'UPDATE': ['update', 'change'],
'QUIT': ['quit', 'leave'],
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from safecity.app... | } |
Given snippet: <|code_start|>log = logging.getLogger("safecity.locate.vet_skip_words")
class Command(NoArgsCommand):
title = 'locate.vet_skip_words'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import csv
import logging
import os
import re
from optparse import make_option
... | help = 'Verify that no skip_words are road names or other keywords.' |
Here is a snippet: <|code_start|> alias_type='CA'
)
alias.roads.add(road)
log.info('Loading alias tables.')
id_name_mapping = {}
reader = csv.DictReader(open(ROADS_CSV, 'r'))
for r... | try: |
Based on the snippet: <|code_start|>log = logging.getLogger("safecity.locate.load_aliases")
ROADS_CSV = 'data/streets/names.csv'
ALIASES_CSV = 'data/streets/aliases.csv'
ALIAS_TYPES = {
'ALIAS': 'AL',
'HONORARY': 'HN',
'911': 'EM',
'NAMING_CONV': 'NC',
}
class Command(NoArgsCommand):
title = 'l... | ) |
Given snippet: <|code_start|>
urlpatterns = patterns('',
url('^$',
views.mock,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls.defaults import *
from safecity.apps.mock import views
and context:
# Path: safecity/apps/mock/views.py
# class MockInc... | name='mock'), |
Here is a snippet: <|code_start|>
urlpatterns = patterns('',
url('^$',
views.index,
name='public_index'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls.defaults import *
from safecity.apps.public import views
and context from other files:
# Path: safeci... | ) |
Next line prediction: <|code_start|>
urlpatterns = patterns('',
url('^incoming/',
views.incoming,
<|code_end|>
. Use current file imports:
(from django.conf.urls.defaults import *
from safecity.apps.tropo import views)
and context including class names, function names, or small code snippets from other f... | name='tropo_incoming'), |
Given snippet: <|code_start|> self.reconnect_wait_time = self.MAX_WAIT_TIME
def __reset_wait_time(self):
self.reconnect_wait_time = self.STARTING_WAIT_TIME
def __run(self):
while self.running:
if not self.connected:
if not self.last_connect_attempt or tim... | with self.lock: |
Next line prediction: <|code_start|> io_occured = True
except IOError:
echo_colorized_warning('Read failed. Will disconnect and attempt to reconnect.')
try:
self.packet_layer.close()
except IOError... | if not io_occured: |
Given snippet: <|code_start|> print('\n')
for num in list:
print(str(num))
def printFeatures(featureset):
for list in badext.docExtract():
print('\n')
for num in list:
print(str(num))
printFeatures(badext.docExtract())
docList = []
loadedDocList = []
os.listdir('./datas... | documents = [] |
Given the following code snippet before the placeholder: <|code_start|>d.documents
lynneDocs
with open("./datasets/C50train/LynneO'Donnell/116963") as lynne:
lynneDocs = lynne.read()
with open("./datasets/C50train/LynneO'Donnell/116963newsML.txt") as lynne:
lynneDocs = lynne.read()
lynneDocs
d = DocumentExtra... | for char in num: |
Predict the next line after this snippet: <|code_start|> print(n)
#print(str(clf.score(preprocessing.scale(testvecs), testlabels) * 100) + "% score on this dataset.")
testvecsscaled = preprocessing.scale(testvecs)
# Cross-validation
print("Computing cross validation...")
cvIterations = 7
scores = cross_validation.c... | plot_confusion_matrix(cm) |
Given snippet: <|code_start|>
# scale our feature vectors to make them suitable for SVM input
print("Scaling feature vectors...")
extracted = preprocessing.scale(extracted)
# instantiate classifier and train it
print("Instantiating classifier...")
clf = svm.SVC(probability=True, kernel='linear', class_weight='auto')
pr... | (scores.mean(), scores.std() * 2)) |
Next line prediction: <|code_start|> return self._server.password_grant(account_ident, credentials, scope)
class Server(object):
def __init__(self, dao=None):
self._dao = dao
def register_client(self, client_id, **kwds):
if self._dao.has_client_id(client_id):
raise RegisterE... | 'redirect_uri': redirect_uri, |
Predict the next line after this snippet: <|code_start|> def has_authorization_code(self, authorization_code):
return authorization_code in self._codes
def insert_authorization_code(self, authorization_code):
self._codes.put_object(authorization_code['code'], authorization_code)
def has_tok... | def update_authorization_code(self, authorization_code, param): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'chinfeng'
try:
except ImportError:
logger = logging.getLogger(__name__)
def json_default(obj):
if isinstance(obj, datetime.datetime):
return str(obj)
else:
<|code_end|>
, predict the immediate next line with the help of import... | return obj |
Here is a snippet: <|code_start|>
def send(self, *args, **kwargs):
for e in self._events:
e.call(*args, **kwargs)
class _EventManager(object):
def __init__(self, owner):
self._owner = owner
def __getattr__(self, key):
return _EventProxy(
(e for e in (self._... | for sn in self._service_names: |
Given the code snippet: <|code_start|>
class Activator(_Callable):
def __init__(self, func):
super(self.__class__, self).__init__(func)
class Deactivator(_Callable):
def __init__(self, func):
super(self.__class__, self).__init__(func)
class Task(object):
def __init__(self, fn, instance):... | if extr: |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'chinfeng'
try:
except ImportError:
class OAuthTestCase(WSGITestCase):
def get_app(self):
<|code_end|>
, predict the next line using imports from the current file:
import uuid
from urlparse import u... | self._storage = StorageService() |
Given the code snippet: <|code_start|>
def __iter__(self):
for doc in self._collection.find(fields={'key': True, '_id': False}):
yield doc['key']
def keys(self):
return list(self)
class MongoStorage(StorageBase):
def __init__(self, db):
self._db = db
def get_bucket... | def __contains__(self, item): |
Given snippet: <|code_start|> if obj:
return obj['content']
def delete_object(self, key):
self._collection.remove({'key': key})
def find(self, fields):
find_fields = {'content.%s' % k: v for k, v in fields.items()}
for doc in self._collection.find(find_fields):
... | self._db = db |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'chinfeng'
logger = logging.getLogger(__name__)
class GumTestCase(TestCase):
def setUp(self):
logging.basicConfig(level=logging.DEBUG, format='[%(asctime)-15s %(levelname)s:%(module)s] %(message)s')
fmk... | self._fmk = fmk |
Given snippet: <|code_start|> indexes VARCHAR
)
''')
def create_bucket(self, name, indexes=()):
# TODO
# CREATE BUCKET TABLE
cursor = self._sqlite_db.cursor()
if indexes:
cursor.execute(
'INSERT OR REPLACE INTO settings(bucket... | PRIMARY KEY (entity_id, index_name), |
Predict the next line after this snippet: <|code_start|> )
''')
def create_bucket(self, name, indexes=()):
# TODO
# CREATE BUCKET TABLE
cursor = self._sqlite_db.cursor()
if indexes:
cursor.execute(
'INSERT OR REPLACE INTO settings(bucket,... | FOREIGN KEY (entity_id) REFERENCES {table}_entities(id) ON DELETE CASCADE |
Based on the snippet: <|code_start|> if isinstance(obj, bytes):
return {'__bytes__': base64.b64encode(obj).decode('ascii')}
else:
return super(self.__class__, self).default(obj)
class EnhancedJSONDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSO... | k VARCHAR UNIQUE, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'chinfeng'
_singleton_storage = None
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return {'__utctimestamp__': mktime(obj.timetuple())}
if isinstance(... | return json.loads(raw, cls=EnhancedJSONDecoder) |
Given the following code snippet before the placeholder: <|code_start|>
@service
class WSGIService(object):
@configuration(rootapp='rootapp')
def __init__(self, rootapp):
self._apps = {}
self._server = None
self._rootapp = rootapp
self.start_wsgi_server()
@configuration(port... | if hasattr(app, '__route__'): |
Given the following code snippet before the placeholder: <|code_start|>
def on_stop(self):
if self._server:
self._server.shutdown()
del self._server
@bind('tserv.application')
def application(self, app):
wsgiref.validate.validator(app)
if hasattr(app, '__route__'... | return ['no application deployed'.encode('utf-8')] |
Continue the code snippet: <|code_start|> '', port, self._wsgi_app, server_class=sc
)
self._server.serve_forever()
except BaseException as err:
err.args = ('tserv start fails.', ) + err.args
logger.exception(err)
def on_stop(self):
if s... | if app_route in self._apps: |
Given the following code snippet before the placeholder: <|code_start|>
def process_request(self, request, client_address):
self._pool.apply_async(self.process_request_worker, args=(request, client_address))
def serve_forever(self, *args, **kwds):
self._pool.apply_async(wsgiref.simple_server.WS... | logger.exception(err) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'chinfeng'
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write('Hello world!')
@service
@provide('tserv.application')
@provide('cserv.application')
class FirstApplication(tornado.wsgi.WSGIAdap... | ]) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'chinfeng'
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write('Hello world!')
@service
@provide('tserv.application')
@provide('cserv.application')
class FirstApplication(tornado.wsgi.WSGIAdapter):
<|code_... | __route__ = 'firstapp' |
Given snippet: <|code_start|> wsgiref.validate.validator(app)
if hasattr(app, '__route__'):
self._apps[app.__route__] = app
else:
self._apps[app.__class__.__name__] = app
@application.unbind
def application(self, app):
if hasattr(app, '__route__'):
... | start_response(HTTP_STATUS(404), [('Content-Type', 'text/plain'), ]) |
Predict the next line for this snippet: <|code_start|> self._apps = {}
self._server = None
self._default_app = None
self.start_wsgi_server()
@configuration(port=('port', 8002))
def start_wsgi_server(self, port):
try:
sc = functools.partial(TaskPoolWSGIServer, ... | else: |
Predict the next line for this snippet: <|code_start|>__author__ = 'chinfeng'
logger = logging.getLogger(__name__)
class TaskPoolWSGIServer(wsgiref.simple_server.WSGIServer):
def __init__(self, executor, *args, **kwds):
wsgiref.simple_server.WSGIServer.__init__(self, *args, **kwds)
self._executor... | def start_wsgi_server(self, port): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'chinfeng'
logger = logging.getLogger(__name__)
class TaskPoolWSGIServer(wsgiref.simple_server.WSGIServer):
def __init__(self, executor, *args, **kwds):
wsgiref.simple_server.WSGIServer.__init__(self, *args, **kwds)
self._executor ... | self.start_wsgi_server() |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
my_vcr = VCR(
path_transformer=VCR.ensure_suffix(".yaml"),
cassette_library_dir="tests/cassettes/",
record_mode=pytest.config.getoption("--vcrmode"),
)
logging.basicConfig() # you need to initialize logging, oth... | lengh_str_regex = r"\d+(h|m|s)(\d+(m))?(\d+s)?" |
Given the code snippet: <|code_start|> ),
module_urltitle.handle_url(botmock, None, "#channel", msg, msg),
)
@my_vcr.use_cassette()
def test_six(botmock):
msg = "http://fi.wikipedia.org/wiki/Birger_Ek"
module_urltitle.init(botmock)
eq_(
(
"#channel",
u"Ti... | @my_vcr.use_cassette() |
Using the snippet: <|code_start|>
log = logging.getLogger("bot_mock")
class BotMock(botcore.CoreCommands):
config = {}
def __init__(self, config={}, network=None):
self.config = config
if network:
self.network = network
self.nickname = self.network.nickname
... | def get_url(self, url, nocache=False, params=None, headers=None, cookies=None): |
Predict the next line for this snippet: <|code_start|> return self.extract_packet(self.cls, x)
class ASN1F_CHOICE(ASN1F_PACKET):
ASN1_tag = ASN1_Class_UNIVERSAL.NONE
def __init__(self, name, default, *args):
self.name=name
self.choice = {}
# FIXME TypeError: unhashable type: 'AS... | return RandChoice(*[fuzz(x()) for x in list(self.choice.values())]) |
Given the code snippet: <|code_start|>
class ProjectsTestCase(TestCase):
list_url = '/projects/'
add_url = '/projects/add/'
def test_login_required_for_list(self):
response = self.client.get(self.list_url)
self.assertRedirectToLogin(response, self.list_url)
def test_user_see_list_pa... | self.assert200(response) |
Continue the code snippet: <|code_start|> def test_user_see_list_page(self):
self.login()
response = self.client.get(self.list_url)
self.assert200(response)
self.assertTemplateUsed('projects/list.jade')
def test_login_required_for_add(self):
response = self.client.get(se... | aws_secret_access_key='aws_secret_access_key', |
Given the following code snippet before the placeholder: <|code_start|>
projects = self.get_context_variable('projects')
self.assertEqual(len(projects), 1)
self.assertEqual(projects[0].title, valid_data['title'])
self.assertTrue(subscribe.called)
def test_invalid_data_not_added(sel... | def test_page_not_allowed_for_anon(self): |
Given the code snippet: <|code_start|>
def test_listing_works(self):
self.login()
response = self.client.get(self.url)
self.assert200(response)
self.assertTemplateUsed('fep/list.jade')
content = response.data.decode('utf-8')
for item in self.items:
self.... | self.assertTrue(form.errors) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.