Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
('/education', Education),
... | ('/toplanguages', TopLanguages), |
Predict the next line after this snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
('/education', Education),
... | ('/mostactiveusers', MostActiveUsers)], debug=True) |
Next line prediction: <|code_start|>
class Author(models.Model):
id = BigHashidAutoField(primary_key=True, prefix="a_", alphabet="0123456789abcdef")
name = models.CharField(max_length=40)
uid = models.UUIDField(null=True, blank=True)
id_str = models.CharField(max_length=15, blank=True)
def __str... | reference_id = HashidField(salt="alternative salt", allow_int_lookup=True, prefix="ref_") |
Given snippet: <|code_start|>
class Author(models.Model):
id = BigHashidAutoField(primary_key=True, prefix="a_", alphabet="0123456789abcdef")
name = models.CharField(max_length=40)
uid = models.UUIDField(null=True, blank=True)
id_str = models.CharField(max_length=15, blank=True)
def __str__(self... | id = HashidAutoField(primary_key=True, salt="A different salt", min_length=20) |
Continue the code snippet: <|code_start|>
class MockRequest:
pass
class MockSuperUser:
def has_perm(self, perm):
return True
site = AdminSite()
request = MockRequest()
request.user = MockSuperUser()
class HashidAdminTests(TestCase):
def test_admin_widget_is_text(self):
<|code_end|>
. Use cur... | admin = RecordAdmin(Record, site) |
Based on the snippet: <|code_start|>
class MockRequest:
pass
class MockSuperUser:
def has_perm(self, perm):
return True
site = AdminSite()
request = MockRequest()
request.user = MockSuperUser()
class HashidAdminTests(TestCase):
def test_admin_widget_is_text(self):
<|code_end|>
, predict the ... | admin = RecordAdmin(Record, site) |
Predict the next line after this snippet: <|code_start|>
class Artist(models.Model):
id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef")
name = models.CharField(max_length=40)
def __str__(self):
return "{} ({})".format(self.name, self.id)
class Record(models.Model):
id = Big... | reference_id = HashidField() |
Predict the next line after this snippet: <|code_start|>
class Artist(models.Model):
id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef")
name = models.CharField(max_length=40)
def __str__(self):
return "{} ({})".format(self.name, self.id)
class Record(models.Model):
id = Big... | key = BigHashidField(min_length=10, alphabet="abcdlmnotuvwxyz123789", null=True, blank=True) |
Next line prediction: <|code_start|>
class Artist(models.Model):
id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef")
name = models.CharField(max_length=40)
def __str__(self):
return "{} ({})".format(self.name, self.id)
class Record(models.Model):
<|code_end|>
. Use current file ... | id = BigHashidAutoField(primary_key=True) |
Given the following code snippet before the placeholder: <|code_start|>
def _is_int_representation(number):
"""Returns whether a value is an integer or a string representation of an integer."""
try:
int(number)
except ValueError:
return False
else:
return True
def get_id_for... | if isinstance(value, Hashid): |
Given the code snippet: <|code_start|>@skipUnless(have_drf, "Requires Django REST Framework to be installed")
class TestRestFramework(TestCase):
def assertSerializerError(self, serializer, field, code):
serializer_name = serializer.__class__.__name__
self.assertFalse(serializer.is_valid(),
... | model = Artist |
Given snippet: <|code_start|>
def test_modelserializer_integerfield(self):
class ArtistSerializer(serializers.ModelSerializer):
id = HashidSerializerIntegerField(source_field=Artist._meta.get_field('id'))
class Meta:
model = Artist
fields = ('id', 'na... | model = Record |
Predict the next line for this snippet: <|code_start|> 'name': "Test Record 1024",
'artist': 1024,
'reference_id': 2222222222,
}
s = RecordSerializer(data=data)
self.assertTrue(s.is_valid())
r512 = s.save()
self.assertEqual(r512.id, 1024)
... | model = Track |
Given snippet: <|code_start|>
class AuthorSerializer(serializers.HyperlinkedModelSerializer):
id = HashidSerializerCharField(source_field='library.Author.id', read_only=True)
class Meta:
model = Author
fields = ('url', 'id', 'name', 'uid', 'books')
class BookSerializer(serializers.Hyperlink... | key = HashidSerializerIntegerField(source_field="library.Book.key") |
Using the snippet: <|code_start|> obj = Spy()
theMock = Mock(obj, strict=True, spec=object)
mock_registry.register(obj, theMock)
return obj
def spy2(fn): # type: (...) -> None
"""Spy usage of given `fn`.
Patches the module, class or object `fn` lives in, so that all
interactions can be r... | when2(fn, Ellipsis).thenAnswer(answer) |
Given the code snippet: <|code_start|>
Spying means that all functions will behave as before, so they will
be side effects, but the interactions can be verified afterwards.
Returns Dummy-like, almost empty object as proxy to `object`.
The *returned* object must be injected and used by the code under t... | return RememberedProxyInvocation(theMock, method_name) |
Using the snippet: <|code_start|>
E.g.::
import time
time = spy(time)
# inject time
do_work(..., time)
verify(time).time()
"""
if inspect.isclass(object) or inspect.ismodule(object):
class_ = None
else:
class_ = object.__class__
class Spy(_D... | theMock = Mock(obj, strict=True, spec=object) |
Given the code snippet: <|code_start|>__all__ = ['spy']
def spy(object):
"""Spy an object.
Spying means that all functions will behave as before, so they will
be side effects, but the interactions can be verified afterwards.
Returns Dummy-like, almost empty object as proxy to `object`.
The *ret... | class Spy(_Dummy): |
Next line prediction: <|code_start|>
import time
time = spy(time)
# inject time
do_work(..., time)
verify(time).time()
"""
if inspect.isclass(object) or inspect.ismodule(object):
class_ = None
else:
class_ = object.__class__
class Spy(_Dummy):
... | mock_registry.register(obj, theMock) |
Predict the next line for this snippet: <|code_start|> name += class_.__name__
return "<%s id=%s>" % (name, id(self))
obj = Spy()
theMock = Mock(obj, strict=True, spec=object)
mock_registry.register(obj, theMock)
return obj
def spy2(fn): # type: (...) -> None
"""Spy ... | answer = get_obj(fn) |
Here is a snippet: <|code_start|>
class TestCustomDictLike:
def testAssignKeyValuePair(self):
td = _Dict()
obj = {}
<|code_end|>
. Write the next line using the current file imports:
import pytest
from mockito.mock_registry import _Dict
from mockito.mocking import Mock
and context from other f... | mock = Mock(None) |
Given the following code snippet before the placeholder: <|code_start|>
pytestmark = pytest.mark.usefixtures("unstub")
class Dog(object):
def bark(self, sound):
return sound
def bark_hard(self, sound):
return sound + '!'
class TestMockito2:
def testWhen2(self):
rex = Dog()
... | when2(rex.bark, 'Miau').thenReturn('Wuff') |
Predict the next line for this snippet: <|code_start|>
pytestmark = pytest.mark.usefixtures("unstub")
class Dog(object):
def bark(self, sound):
return sound
def bark_hard(self, sound):
return sound + '!'
class TestMockito2:
def testWhen2(self):
rex = Dog()
when2(rex... | patch(rex.bark, lambda sound: sound + '!') |
Using the snippet: <|code_start|> class B(object):
pass
when2(A.B, 'Hi').thenReturn('Ho')
assert A.B('Hi') == 'Ho'
def testPatch(self):
patch(os.path.commonprefix, lambda m: 'yup')
patch(os.path.commonprefix, lambda m: 'yep')
assert os.path.comm... | verify(os.path).exists('/Foo') |
Given the following code snippet before the placeholder: <|code_start|> when2(A.B.c)
def testEnsureToResolveClass(self):
class A(object):
class B(object):
pass
when2(A.B, 'Hi').thenReturn('Ho')
assert A.B('Hi') == 'Ho'
def testPatch(self):
p... | spy2(os.path.exists) |
Here is a snippet: <|code_start|>
def bark_hard(self, sound):
return sound + '!'
class TestMockito2:
def testWhen2(self):
rex = Dog()
when2(rex.bark, 'Miau').thenReturn('Wuff')
when2(rex.bark, 'Miau').thenReturn('Grrr')
assert rex.bark('Miau') == 'Grrr'
def testPa... | f = newmethod(f, rex) |
Given the following code snippet before the placeholder: <|code_start|>
class Dog(object):
def waggle(self):
return 'Unsure'
def bark(self, sound='Wuff'):
return sound
class TestUntub:
def testIndependentUnstubbing(self):
rex = Dog()
mox = Dog()
<|code_end|>
, predict t... | when(rex).waggle().thenReturn('Yup') |
Based on the snippet: <|code_start|>
class Dog(object):
def waggle(self):
return 'Unsure'
def bark(self, sound='Wuff'):
return sound
class TestUntub:
def testIndependentUnstubbing(self):
rex = Dog()
mox = Dog()
when(rex).waggle().thenReturn('Yup')
when(m... | unstub(rex) |
Predict the next line for this snippet: <|code_start|> return sound
class TestUntub:
def testIndependentUnstubbing(self):
rex = Dog()
mox = Dog()
when(rex).waggle().thenReturn('Yup')
when(mox).waggle().thenReturn('Nope')
assert rex.waggle() == 'Yup'
assert ... | verify(rex).waggle() |
Predict the next line after this snippet: <|code_start|>
def testOnlyUnstubTheExactStub(self):
rex = Dog()
when(rex).bark('Shhh').thenReturn('Nope')
with when(rex).bark('Miau').thenReturn('Grrr'):
assert rex.bark('Miau') == 'Grrr'
assert rex.bark('Shhh') == 'Nope'
... | with pytest.raises(ArgumentError): |
Continue the code snippet: <|code_start|>
pytestmark = pytest.mark.usefixtures("unstub")
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array... | when(module).one_arg(array).thenReturn('yep') |
Here is a snippet: <|code_start|>
pytestmark = pytest.mark.usefixtures("unstub")
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = np.ar... | with patch(mockito.invocation.MatchingInvocation.compare, xcompare): |
Based on the snippet: <|code_start|>
PY3 = sys.version_info >= (3,)
def foo():
pass
class TestLateImports:
def testOs(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
import sys
import os
import os.path
import os.path
import o... | assert get_obj('os') is os |
Given the code snippet: <|code_start|> "object 'os.path.exists' has no attribute 'forever'"
def testUnknownMum(self):
with pytest.raises(ImportError) as exc:
assert get_obj('mum') is foo
if PY3:
assert str(exc.value) == "No module named 'mum'"
else:
... | get_obj_attr_tuple('os') |
Predict the next line after this snippet: <|code_start|>
# master_db_host="192.168.1.175"
# master_db_user="zzjr"
# master_db_password='zzjr#2015'
# master_db_name='zzjr_server'
#
# def exec_db(db_name,cmd):
# res={'status':None,'mod_rows':None}
# try:
# con = mdb.connect(master_db_host, master_db_us... | dblist=Dblist.objects.filter(db_role=db_role) |
Given snippet: <|code_start|># coding:utf-8
'''# "user_id","db_name","sqllog","create_time","status","comments","type"'''
class SqllogForm(forms.ModelForm):
class Meta:
model = Sqllog
ordering = ['-create_time']
fields = [
"user_id","user_name","db_name","sqllog","check_mod_r... | model = Dblist |
Predict the next line after this snippet: <|code_start|> error = e.message
return my_render('setting.html', locals(), request)
@login_required(login_url='/login')
def upload(request):
user = request.user
assets = get_group_user_perm(user).get('asset').keys()
asset_select = []
if request... | runner = MyRunner(res) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# coding: utf-8
try:
except ImportError:
os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings'
define("port", default=PORT, help="run on the given port", type=int)
<|code_end|>
, generate the next line using the imports in this file:
import time... | define("host", default=IP, help="run port on given host", type=str) |
Using the snippet: <|code_start|>#!/usr/bin/env python
# coding: utf-8
try:
except ImportError:
os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings'
<|code_end|>
, determine the next line of code. You have imports:
import time
import datetime
import json
import os
import sys
import os.path
import thread... | define("port", default=PORT, help="run on the given port", type=int) |
Next line prediction: <|code_start|># coding: utf-8
db = mysql.connect(user="root", passwd="", \
db="jumpserver", charset="utf8")
db.autocommit(True)
c = db.cursor()
# Create your views here.
redis_path='/root/jumpserver-master/redis-3.2.8/src/redis-cli -c '
notallowcmds=["del","flushall","flushdb","set... | mylist=Redislist.objects.filter(redis_role="master") |
Predict the next line for this snippet: <|code_start|> return HttpResponse(json.dumps(res), content_type="application/json")
return my_render('dbtool/check_sql.html', locals(), request)
########submit_sql######
@require_role(role='user')
def dbtool_submit_sql(request):
defend_attack(request)
... | if Sqllog.objects.filter(Q(sqllog=unicode(sqllog)) & ~Q(status = 0)): |
Using the snippet: <|code_start|>
con = mdb.connect(check_db_host, check_db_user, check_db_password, db, charset='utf8')
con.autocommit(0)
cur = con.cursor()
cur.execute(cmd)
cur.close()
mod_rows= cur.rowcount
# con.commit() not commi... | dblist=Dblist.objects.all() |
Given snippet: <|code_start|> con.rollback()
return HttpResponse(json.dumps(res), content_type="application/json")
except mdb.Error, e:
res["err_code"]=e.args[0]
res["err_text"] = e.args[1]
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
... | sf_post = SqllogForm(request.POST) |
Given the following code snippet before the placeholder: <|code_start|>class Annotation(object):
"""A name mention and its predicted candidates
Parameters
----------
Attributes
----------
TODO
is_first : bool or unset
Indicates if this annotation is the first in the document for th... | u'\t'.join([unicode(c) for c in self.candidates]) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
class ToWeak(object):
"""Convert annotations to char-level for weak evaluation
A better approach is to use measures with partial overlap support.
"""
def __init__(self, fname):
self.fname = fname
def __call__(self... | a = Annotation.from_string(line.rstrip('\n').decode(ENC)) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
class ToWeak(object):
"""Convert annotations to char-level for weak evaluation
A better approach is to use measures with partial overlap support.
"""
def __init__(self, fname):
self.fname = fname
def __call__(self):
<|code_end|>
... | return u'\n'.join(unicode(a) for a in self.annotations()).encode(ENC) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
class ToWeak(object):
"""Convert annotations to char-level for weak evaluation
A better approach is to use measures with partial overlap support.
"""
def __init__(self, fname):
self.fname = fname
def __call__(self):
<|code_end|>
. Wri... | return u'\n'.join(unicode(a) for a in self.annotations()).encode(ENC) |
Next line prediction: <|code_start|>
def by_mention(annotations):
return [("{}//{}..{}".format(a.docid, a.start, a.end), [a])
for a in annotations]
# Reading annotations
class Reader(object):
"Read annotations, grouped into documents"
def __init__(self, fh, group=by_document, cls=Document):
... | yield Annotation.from_string(line.rstrip('\n')) |
Given the code snippet: <|code_start|> VALIDATION = {
'nested': 'ignore',
'crossing': 'ignore',
'duplicate': 'ignore',
}
def _validate(self, _categories=['nested', 'crossing', 'duplicate']):
# XXX: do we nee to ensure start > end for all Annotations first?
issues = {c... | .format(issue, unicode(a), unicode(b))) |
Here is a snippet: <|code_start|> """Handle KB ambiguity in the gold standard by modifying it to match system
The following back-off strategy applies for each span with gold standard
ambiguity:
* attempt to match it to the top candidate for that span
* attempt to match it to the top candida... | system = Reader(utf8_open(system)) |
Given the code snippet: <|code_start|> """Handle KB ambiguity in the gold standard by modifying it to match system
The following back-off strategy applies for each span with gold standard
ambiguity:
* attempt to match it to the top candidate for that span
* attempt to match it to the top ca... | system = Reader(utf8_open(system)) |
Here is a snippet: <|code_start|> return 'correct link'
if self.gold is None:
return 'nil-as-link'
if self.system is None:
return 'link-as-nil'
return 'wrong-link'
@staticmethod
def _str(val, pre):
if val is MISSING:
return u''
... | self.system = list(Reader(utf8_open(system))) |
Next line prediction: <|code_start|> return 'wrong-link'
@staticmethod
def _str(val, pre):
if val is MISSING:
return u''
elif val is None:
return u'{}NIL'.format(pre)
return u'{}"{}"'.format(pre, val)
@property
def _system_str(self):
retur... | self.measure = get_measure('strong_mention_match') |
Next line prediction: <|code_start|>class Analyze(object):
"""Analyze errors"""
def __init__(self, system, gold=None, unique=False, summary=False, with_correct=False):
self.system = list(Reader(utf8_open(system)))
self.gold = list(Reader(utf8_open(gold)))
self.unique = unique
sel... | for s, g in Evaluate.iter_pairs(self.system, self.gold): |
Given the following code snippet before the placeholder: <|code_start|> return 'correct link'
if self.gold is None:
return 'nil-as-link'
if self.system is None:
return 'link-as-nil'
return 'wrong-link'
@staticmethod
def _str(val, pre):
if val i... | self.system = list(Reader(utf8_open(system))) |
Using the snippet: <|code_start|> return u'{0.label}\t{0.doc_id}\t{0._gold_str}\t{0._system_str}'.format(self)
class Analyze(object):
"""Analyze errors"""
def __init__(self, system, gold=None, unique=False, summary=False, with_correct=False):
self.system = list(Reader(utf8_open(system)))
... | return u'\n'.join(unicode(error) for error in _data()) |
Using the snippet: <|code_start|> ('vp', ['vap', 'vapr', 'vap']),
('tas', ['tas']),
('ps', ['ps'])])
unit_names = array([['mj/m^2', 'mj/m2', 'mjm-2', 'mjm-2day-1', 'mjm-2d-1', 'mj/m^2/day', 'mj... | alldata[i] = fill(alldata[i], time, ref, var_name) |
Predict the next line for this snippet: <|code_start|> if name.startswith('_'):
return object.__getattribute__(self, name)
if name in self._shim_cache:
return self._shim_cache[name]
if self._should_shim(name):
meth = self._shim(name)
self._shim_ca... | old_path = path = get_invoked_arg(current_api, 'path', args, kwargs) |
Given the following code snippet before the placeholder: <|code_start|>
if name in self._shim_cache:
return self._shim_cache[name]
if self._should_shim(name):
meth = self._shim(name)
self._shim_cache[name] = meth
return meth
# local defined in sh... | set_invoked_arg(legacy, 'name', name, args, kwargs) |
Predict the next line after this snippet: <|code_start|> return object.__getattribute__(self, name)
if name in self._shim_cache:
return self._shim_cache[name]
if self._should_shim(name):
meth = self._shim(name)
self._shim_cache[name] = meth
re... | name, path = _path_split(path) |
Predict the next line for this snippet: <|code_start|>
def parse_tags(desc):
# real tags and not system-like tags
tags = _hashtags(desc)
if '#notebook' in tags:
tags.remove('#notebook')
if '#inactive' in tags:
tags.remove('#inactive')
return tags
class NotebookGist(object):
""... | def __init__(self, gist, gisthub): |
Here is a snippet: <|code_start|> path : unicode
The URL path of the notebooks directory
Returns
-------
name : unicode
A notebook name (with the .ipynb extension) that starts
with basename and does not refer to any existing notebook.
"""
... | tags = parse_tags(name) |
Given the code snippet: <|code_start|>
current = nbformat.v4
def is_notebook(path):
# checks if path follows bundle format
if not path.endswith('.ipynb'):
return False
# if that we have same named ipynb file in directory
name = path.rsplit('/', 1)[-1]
file_path = os.path.join(path, name)
... | bundle_class = NotebookBundle |
Predict the next line for this snippet: <|code_start|>
class PathTranslateShim(ShimManager):
"""
Provide backwards compat to ipython removing name from its api calls
This could be done with inspect and a metaclass
"""
def __init__(self, *args, **kwargs):
self._shim_cache = {}
self.... | old_name = name = get_invoked_arg(legacy, 'name', args, kwargs) |
Next line prediction: <|code_start|>
class PathTranslateShim(ShimManager):
"""
Provide backwards compat to ipython removing name from its api calls
This could be done with inspect and a metaclass
"""
def __init__(self, *args, **kwargs):
self._shim_cache = {}
self._manager = self.__... | set_invoked_arg(legacy, 'name', name, args, kwargs) |
Next line prediction: <|code_start|>
class PathTranslateShim(ShimManager):
"""
Provide backwards compat to ipython removing name from its api calls
This could be done with inspect and a metaclass
"""
def __init__(self, *args, **kwargs):
self._shim_cache = {}
self._manager = self.__... | name, path = _path_split(name) |
Predict the next line for this snippet: <|code_start|>
def _fullpath(name, path):
fullpath = url_path_join(path, name)
return fullpath
def _path_split(path):
bits = path.rsplit('/', 1)
path = ''
name = bits.pop()
if bits:
path = bits[0]
return name, path
<|code_end|>
with the he... | class NBXContentsManager(DispatcherMixin, ContentsManager): |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# coding=utf8
"""
In cases where you want to generate IDs automatically, decorators are
available. These should be the outermost decorators, as they change the
signature of some of the put methods slightly.
>>> from simplekv.memory import DictStore
>>> from si... | class HashDecorator(StoreDecorator): |
Predict the next line after this snippet: <|code_start|> except OSError as e:
if 2 == e.errno:
pass # file already gone
else:
raise
return self._dstore.put_file(key, file, *args, **kwargs)... | key = text_type(getattr(uuid, self.uuidfunc)()) |
Next line prediction: <|code_start|> offset = len(self.buffer) - self.hm.digest_size
rv, self.buffer = self.buffer[:offset], self.buffer[offset:]
# update hmac
self.hm.update(rv)
if finished:
# check hash
if not self.buffer == self.hm.digest():
... | class HMACDecorator(StoreDecorator): |
Predict the next line after this snippet: <|code_start|>@contextmanager
def boto3_bucket(access_key, secret_key, host,
bucket_name=None, **kwargs):
name = bucket_name or 'testrun-bucket-{}'.format(uuid())
s3_client = boto3.client('s3')
s3_client.create_bucket(Bucket=name)
s3_resource = ... | parser = ConfigParser({'host': 's3.amazonaws.com', |
Next line prediction: <|code_start|>
UUID_REGEXP = re.compile(
r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
)
class IDGen(object):
@pytest.fixture(params=[
u'constant',
u'foo{}bar',
u'{}.jpeg',
u'prefix-{}.hello',
u'justprefix{}',
])
def ... | return UUIDDecorator(store) |
Given the following code snippet before the placeholder: <|code_start|> if os.path.exists(tmpfile.name):
os.unlink(tmpfile.name)
def test_put_generates_valid_uuid(self, uuidstore, value):
key = uuidstore.put(None, value)
uuid.UUID(hex=key)
def test_put_file_generates... | return HashDecorator(store, hashfunc) |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture
def validate_hash(self, hashfunc):
hash_regexp = re.compile(r'^[0-9a-f]{{{}}}$'.format(
hashfunc().digest_size * 2,
))
return hash_regexp.match
@pytest.fixture
def value_hash(self, hashfunc, valu... | assert isinstance(key, text_type) |
Using the snippet: <|code_start|>
:param store: The store to pass keys on to.
:param prefix: Prefix to add.
"""
def __init__(self, prefix, store):
super(PrefixDecorator, self).__init__(store)
self.prefix = prefix
def _filter(self, key):
return key.startswith(self.prefix)
... | quoted = quote_plus(key.encode('utf-8')) |
Next line prediction: <|code_start|> def _filter(self, key):
return key.startswith(self.prefix)
def _map_key(self, key):
self._check_valid_key(key)
return self.prefix + key
def _map_key_prefix(self, key_prefix):
return self.prefix + key_prefix
def _unmap_key(self, key):... | return unquote_plus(key) |
Next line prediction: <|code_start|> """Prefixes any key with a string before passing it on the decorated
store. Automatically strips the prefix upon key retrieval.
:param store: The store to pass keys on to.
:param prefix: Prefix to add.
"""
def __init__(self, prefix, store):
super(Pre... | if not isinstance(key, text_type): |
Here is a snippet: <|code_start|> :param store: The store to pass keys on to.
:param prefix: Prefix to add.
"""
def __init__(self, prefix, store):
super(PrefixDecorator, self).__init__(store)
self.prefix = prefix
def _filter(self, key):
return key.startswith(self.prefix)
... | if isinstance(quoted, binary_type): |
Predict the next line for this snippet: <|code_start|> self.refresh_button.clicked.connect(self.refresh_data)
self.buttonbox.addButton(
self.refresh_button, QDialogButtonBox.ActionRole)
self.layout.addWidget(self.buttonbox)
self.refresh_data()
def refresh_data(self):
... | servers = [ServerProcess(FakeProcess(42), '/my/home/dir', |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright (c) Spyder Project Contributors
# Licensed under the terms of the MIT License
"""Spyder configuration page for notebook plugin."""
# Qt imports
# Spyder imports
# Local imports
class NotebookConfigPage(PluginConfigPage):... | _('Notebook theme'), theme_choices, 'theme', restart=True) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""Tests for serverinfo.py."""
# Third party imports
# Local imports
class FakeProcess:
"""Fake for ServerProcess class."""
def __init__(self, pid):
... | servers = [ServerProcess(FakeProcess(42), '/my/home/dir', |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""Tests for serverinfo.py."""
# Third party imports
# Local imports
class FakeProcess:
"""Fake for ServerProcess class."""
def __init__(self, pid):
... | state=ServerState.RUNNING, |
Predict the next line for this snippet: <|code_start|>
"""Tests for serverinfo.py."""
# Third party imports
# Local imports
class FakeProcess:
"""Fake for ServerProcess class."""
def __init__(self, pid):
self.pid = pid
def processId(self):
"""Member function which needs to be faked."""... | res = ServerInfoDialog(servers) |
Predict the next line for this snippet: <|code_start|> self.pageAction(QWebEnginePage.Copy),
None,
self.zoom_in_action,
self.zoom_out_action]
if not WEBENGINE:
settings = self.page().settings()
settings.setAttribute(QWebEngineSettings.Devel... | message = _("An error occurred while starting the kernel") |
Given the code snippet: <|code_start|> WebView which opens document in an external browser.
This is a subclass of QWebEngineView, which as soon as the URL is set,
opens the web page in an external browser and closes itself. It is used
in NotebookWidget to open links.
"""
def __init__(self, pare... | class NotebookWidget(DOMWidget): |
Next line prediction: <|code_start|>
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
opti... | DBSession.configure(bind=engine) |
Predict the next line after this snippet: <|code_start|>
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_ur... | Base.metadata.create_all(engine) |
Here is a snippet: <|code_start|>
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = pa... | agency_type = AgencyTypes.get_from_code(DBSession, parts[3]) |
Given the following code snippet before the placeholder: <|code_start|>def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
... | a = Agencies( |
Continue the code snippet: <|code_start|>}
#@view_config(route_name='home')
#def home(request):
#
# return Response('<html><body>hi.</body></html>')
@view_config(route_name='home', renderer='templates/index.mak')
def home(request):
return {}
@view_config(route_name='feed', renderer='templates/feed.mak')
def ... | session = DBSession, |
Given the code snippet: <|code_start|> 'geocode_lng': geocode_lng,
'geocode_successful': geocode_successful,
'status_text': status_text,
'status_description': status_description,
'agency_name': agency_name,
'agency_descriptio... | _agencies = Agencies.get_all( |
Continue the code snippet: <|code_start|>
@view_config(route_name='status.json')
def status_json(request):
""" Returns the status of the system
"""
response = {'success': False}
try:
response['dispatch_count'] = Dispatches.get_count(DBSession)
response['current_dispatch_count'] = Curre... | dispatch_types = DispatchTypes.get_all( |
Using the snippet: <|code_start|> 'alive': True
}
#@view_config(route_name='home')
#def home(request):
#
# return Response('<html><body>hi.</body></html>')
@view_config(route_name='home', renderer='templates/index.mak')
def home(request):
return {}
@view_config(route_name='feed', renderer='templates/feed.... | dispatches = Dispatches.get_by_date( |
Using the snippet: <|code_start|>
@view_config(route_name='browse', renderer='templates/browse.mak')
def browse(request):
return {}
@view_config(route_name='search', renderer='templates/search.mak')
def search(request):
return {}
@view_config(route_name='about', renderer='templates/about.mak')
def about(req... | response['current_dispatch_count'] = CurrentDispatches.get_count(DBSession) |
Using the snippet: <|code_start|>@view_config(route_name='browse', renderer='templates/browse.mak')
def browse(request):
return {}
@view_config(route_name='search', renderer='templates/search.mak')
def search(request):
return {}
@view_config(route_name='about', renderer='templates/about.mak')
def about(requ... | response['run_count'] = Runs.get_count(DBSession) |
Given the following code snippet before the placeholder: <|code_start|>
class TestMyViewSuccessCondition(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
engine = create_engine('sqlite://')
<|code_end|>
, predict the next line using imports from the current file:
import unittes... | DBSession.configure(bind=engine) |
Continue the code snippet: <|code_start|># All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions ... | event = check_call({"action": "nonexistent_action"}) |
Given the code snippet: <|code_start|># Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer... | event = await check_call(s, {"action": "nonexistent_action"}) |
Given the following code snippet before the placeholder: <|code_start|># notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materi... | s = Session() |
Using the snippet: <|code_start|>
matplotlib.use('Agg')
saveflag = True
dim = 4
class MSTest(unittest.TestCase):
def test_MSstatistics(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sprocket.m... | ms = MS() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.