Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|>
## TODO
# def test_duplicated_functions():
# m = rw.http.Module('test')
#
# @m.get('/')
# def foo():
# pass
#
# with pytest.raises(rw.routing.DuplicateError):
# @m.get('/something_else')
# def foo():
# pass
class HTTPTest(tornado... | sub_index = generate_handler_func(sub.get, '/') |
Given the following code snippet before the placeholder: <|code_start|>
def test_reverse_path():
assert generate_rule('/').get_path() == '/'
assert generate_rule('/somewhere').get_path() == '/somewhere'
assert generate_rule('/user/<user>').get_path({'user': 'dino'}) == '/user/dino'
def test_converter_defa... | rt0.add_route('get', '/', 0, generate_route_func('index')) |
Based on the snippet: <|code_start|>
if len(''.join(strings)) != len(''.join(strings_o)):
return len(''.join(strings)) > len(''.join(strings_o))
for i in range(len(strings)):
if strings[i] != strings_o[i]:
return strings[i] < strings_o[i]
# strings are t... | @rw.scope.inject |
Given the code snippet: <|code_start|># -*- coding:utf-8 -*-
__author__ = '东方鹗'
class LoginForm(FlaskForm):
email = StringField('邮箱', validators=[DataRequired()])
password = PasswordField('密码', validators=[DataRequired()])
remember_me = BooleanField(label='记住我', default=False)
submit = SubmitField('... | if User.query.filter_by(username=field.data).first(): |
Given the following code snippet before the placeholder: <|code_start|> -- notifications_subscription table and the same data exists
-- in both tables
FROM notifications_subscription s
WHERE
s.group_id = %s
AND
... | create_group_notifications.delay(message_id) |
Predict the next line after this snippet: <|code_start|>@shared_task(name='send-system-message')
def send_system_message(recipient, subject, message_content):
"""Send a direct message to a user coming from the system user"""
# Handle calls where we're passed the user_id instead of a User object.
if not isi... | send_immediate_notification.delay(notification.pk) |
Predict the next line for this snippet: <|code_start|>
User = get_user_model()
class ImpersonationMiddlewareTest(TestCase):
"""Tests for the impersonation middleware."""
def setUp(self):
"""Setup the ImpersonationMiddlewareTest TestCase"""
self.user = User.objects.create_user(
us... | middleware = ImpersonationMiddleware() |
Using the snippet: <|code_start|>"""Tests for accepting terms middleware."""
# pylint: disable=invalid-name
class TestAcceptTermsAndConductMiddleware(TestCase):
"""Tests for AcceptTermsAndConductMiddleware."""
def setUp(self):
"""Setup the TestAcceptTermsAndConductMiddleware TestCase"""
self.... | self.mw = AcceptTermsAndConductMiddleware() |
Predict the next line after this snippet: <|code_start|>"""Admin functionality for group app"""
class CategoryAdmin(admin.ModelAdmin):
"""Admin for Group Categories"""
readonly_fields = [
'modified_at', 'created_at'
]
<|code_end|>
using the current file's imports:
from django.contrib import a... | admin.site.register(Category, CategoryAdmin) |
Continue the code snippet: <|code_start|>"""Connect base url definitions."""
# pylint: disable=no-value-for-parameter,invalid-name
autocomplete_light.autodiscover()
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', include('open_connect.welcome.urls')),
url(r'^admin/', include(admin.site.urls... | ConnectSignupView.as_view(), |
Given the code snippet: <|code_start|> url(r'^admin/', include(admin.site.urls)),
# Because we're overriding django-allauth's signup view with our own view
# we need to include it above the include for django-allatuh
url(r'^user/signup/$',
ConnectSignupView.as_view(),
name='account_signu... | url(r'^explore/$', GroupListView.as_view(), name='explore'), |
Continue the code snippet: <|code_start|>
class Meta(object):
"""Meta options for Thread."""
ordering = ['-latest_message__created_at']
def __unicode__(self):
"""Return object's unicode representation."""
return "Thread %s" % self.subject
@property
def is_system_thread(... | subscription = Subscription.objects.get( |
Based on the snippet: <|code_start|> def save(self, **kwargs):
"""Save a message."""
self.clean_text = self._text_cleaner()
shorten = kwargs.pop('shorten', True)
if not self.pk:
created = True
self.status = self.get_initial_status()
else:
... | tasks.send_message(self.pk, False) |
Given the code snippet: <|code_start|> subscribed_email=True,
user__unsubscribed=False
).exclude(
user_id=message.sender_id
)
# User.objects.filter(userthread__thread=message.thread)
for userthread in userthreads:
create_group_notification.delay(message.pk, userthread.pk)... | notification = Notification.objects.create( |
Based on the snippet: <|code_start|>"""Tests for visit tracking middleware."""
# pylint: disable=invalid-name
User = get_user_model()
middleware = list(settings.MIDDLEWARE_CLASSES)
# pylint: disable=line-too-long
if 'open_connect.middleware.visit_tracking.VisitTrackingMiddleware' not in middleware:
middleware... | visit_count = Visit.objects.count() |
Predict the next line for this snippet: <|code_start|> def set_exit(self):
# TODO: docstring
self.__exit = True
def process_messages(self):
# TODO: docstring
if self._timeout is not None:
self._fail_after = time.time() + self._timeout
while not self.__... | raise TimeoutError('connection closed?')
|
Based on the snippet: <|code_start|> seq=next(self.__seq),
request_seq=int(request.get('seq', 0)),
success=success,
command=request.get('command', ''),
message=message or '',
body=kwargs,
)
def set_ex... | with convert_eof():
|
Here is a snippet: <|code_start|>
class DjangoFormStr(object):
def can_provide(self, type_object, type_name):
form_class = find_mod_attr('django.forms', 'Form')
return form_class is not None and issubclass(type_object, form_class)
def get_str(self, val):
<|code_end|>
. Write the next l... | return '%s: %r' % (find_class_name(val), val)
|
Given the code snippet: <|code_start|>
class SignatureTests(unittest.TestCase):
maxDiff = None
def assertSigsEqual(self, found, expected, *args, **kwargs):
conv = kwargs.pop('conv_first_posarg', False)
if expected != found:
if conv:
expected = conv_first_posarg(expe... | return funcsigs.Signature( |
Based on the snippet: <|code_start|>`sphinx.ext.autodoc` can only automatically discover the signatures of basic
callables. This extension makes it use `sigtools.specifiers.signature` on the
callable instead.
Enable it by appending ``'sigtools.sphinxext'`` to the ``extensions`` list
in your Sphinx ``conf.py``
"""
... | sig = specifiers.signature(obj) |
Next line prediction: <|code_start|>--------------------------------------------------------------------
`sphinx.ext.autodoc` can only automatically discover the signatures of basic
callables. This extension makes it use `sigtools.specifiers.signature` on the
callable instead.
Enable it by appending ``'sigtools.sphin... | obj = _util.safe_get(obj, object(), type(parent)) |
Continue the code snippet: <|code_start|># Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, d... | sig = embed(*sigs, use_varargs=use_varargs, use_varkwargs=use_varkwargs) |
Using the snippet: <|code_start|>
conv_pok_pos = '<a>', {2: 'a'}, ['*args', 'a']
conv_pok_kwo = '*, a', {2: 'a'}, ['**kwargs', 'a']
three = (
'a, b, c', {1: 'a', 2: 'b', 3: 'c'},
['a, *args, **kwargs', 'b, *args, **kwargs', 'c'])
dont_use_varargs = (
'a, *p, b', {1: 'ap', 2: 'b... | with self.assertRaises(IncompatibleSignatures): |
Given snippet: <|code_start|>#!/usr/bin/env python
# sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),... | sigs = [s(sig_str, name='_' + str(i)) |
Based on the snippet: <|code_start|> @wraps(func)
def _decorate(decorated):
return _SimpleWrapped(func, decorated)
return _decorate
class _SimpleWrapped(object):
def __init__(self, wrapper, wrapped):
update_wrapper(self, wrapped)
self.func = partial(wrapper, wrapped)
sel... | _util.safe_get(self.__wrapped__, instance, owner)) |
Given snippet: <|code_start|>`sigtools.wrappers`: Combine multiple functions
-----------------------------------------------
The functions here help you combine multiple functions into a new callable
which will automatically advertise the correct signature.
"""
class Combination(object):
"""Creates a callable ... | return signatures.merge( |
Next line prediction: <|code_start|># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM... | specifiers.set_signature_forger(self, self.get_signature, |
Predict the next line for this snippet: <|code_start|># sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software... | class Signature(_util.funcsigs.Signature): |
Given the following code snippet before the placeholder: <|code_start|># of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of th... | sig = forwards( |
Using the snippet: <|code_start|># Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use,... | outer_sig = s(outer, name='o') |
Continue the code snippet: <|code_start|># sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... | sig = signatures.mask( |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentat... | expected_sig = support.s(expected_str) |
Using the snippet: <|code_start|># The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# ... | in_sig = funcsigs.Signature(in_sig.parameters.values(), |
Predict the next line after this snippet: <|code_start|>#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTI... | sphinxextfixt.outer, {}, '(c, *args, **kwargs)', None) |
Continue the code snippet: <|code_start|># furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIE... | class _PokTranslator(_util.OverrideableDataDesc): |
Here is a snippet: <|code_start|> except AttributeError:
pass
try:
del self._sigtools__forger
except AttributeError:
pass
super(_PokTranslator, self).__init__(**kwargs)
self.func = func
self.posoarg_names = set(posoargs)
self.kwo... | sig = _specifiers.forged_signature(self.func, auto=False) |
Based on the snippet: <|code_start|> param.replace(kind=param.POSITIONAL_ONLY))
to_use.remove(param.name)
elif param.name in self.kwoarg_names:
kwoparams.append(
param.replace(kind=param.KEYWORD_ONLY))
... | sources=_signatures.copy_sources(sig.sources, {self.func:self})) |
Given the code snippet: <|code_start|># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
class UtilTests(unittest.TestCas... | tutil.transform_exp_sources(od([('func', 'abc'), ('func2', 'abc')])), |
Using the snippet: <|code_start|># of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to w... | list(wrappers.wrappers(func)), |
Here is a snippet: <|code_start|># Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use,... | self.assertSigsEqual(signatures.signature(func), support.s(sig_str)) |
Next line prediction: <|code_start|># Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to u... | self.assertSigsEqual(signatures.signature(func), support.s(sig_str)) |
Continue the code snippet: <|code_start|># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT O... | @tup('a, b, j, k, l', (1, 2, 3, 4, 5), {}, (1, 2, (3, 4, 5)), [_deco_all]) |
Given the following code snippet before the placeholder: <|code_start|>
def getclosure(obj):
try:
return obj.__closure__
except AttributeError:
return obj.func_closure
def getcode(obj):
try:
return obj.__code__
except AttributeError:
return obj.func_code
class Wrapp... | list(wrappers.wrappers(func)), |
Given snippet: <|code_start|># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def getclosure(obj):
try:
retu... | self.assertSigsEqual(sig, support.s(sig_str)) |
Predict the next line after this snippet: <|code_start|># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH TH... | sig = signatures.signature(func) |
Predict the next line after this snippet: <|code_start|> try:
return obj.__code__
except AttributeError:
return obj.func_code
class WrapperTests(Fixtures):
def _test(self, func, sig_str, args, kwargs, ret, exp_sources, decorators):
"""Tests .wrappers.decorator
Checks its re... | @tup('a, b, j, k, l', (1, 2, 3, 4, 5), {}, (1, 2, (3, 4, 5)), |
Next line prediction: <|code_start|># furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, IN... | class WrapperTests(Fixtures): |
Based on the snippet: <|code_start|> self.assertSigsEqual(sig_get, support.s(expected_get))
self.assertSourcesEqual(sig_get.sources, {
'outer': exp_src_get[0], 'inner': exp_src_get[1],
'+depths': ['outer', 'inner']})
a = (
'a, *p, b, **k', 'c, *, d', (), {},
... | @modifiers.kwoargs('cb') |
Here is a snippet: <|code_start|># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# bulk of the testing happens in tes... | self.assertEqual(sigtools.signature, specifiers.signature) |
Using the snippet: <|code_start|>
# bulk of the testing happens in test_merge and test_embed
not_py33 = sys.version_info < (3,3)
def _func(*args, **kwargs):
raise NotImplementedError
def _free_func(x, y, z):
raise NotImplementedError
class _cls(object):
method = _func
_inst = _cls()
_im_type = type(... | outer_f = support.f(outer, name='outer') |
Based on the snippet: <|code_start|>
def _free_func(x, y, z):
raise NotImplementedError
class _cls(object):
method = _func
_inst = _cls()
_im_type = type(_inst.method)
class MiscTests(unittest.TestCase):
def test_sigtools_signature(self):
self.assertEqual(sigtools.signature, specifiers.signature... | sig_get = specifiers.signature(_util.safe_get(forw, object(), object)) |
Based on the snippet: <|code_start|> Cls.__new__
self.assertEqual(type(Cls.__dict__['__new__'].__wrapped__),
staticmethod)
def test_emulation(self):
func = specifiers.forwards_to_method('abc', emulate=False)(_func)
self.assertTrue(_func is func)
func... | self.assertSigsEqual(signatures.signature(func), exp) |
Continue the code snippet: <|code_start|># THE SOFTWARE.
# bulk of the testing happens in test_merge and test_embed
not_py33 = sys.version_info < (3,3)
def _func(*args, **kwargs):
raise NotImplementedError
def _free_func(x, y, z):
raise NotImplementedError
class _cls(object):
method = _func
_inst... | class ForwardsTest(Fixtures): |
Based on the snippet: <|code_start|> def __init__(self, obj, forger):
self.obj = obj
self.forger = forger
func = specifiers.forwards_to_function(func, emulate=Emulator)(_func)
self.assertTrue(isinstance(func, Emulator))
@specifiers.forwards_to_functio... | class ForgerFunctionTests(SignatureTests): |
Given the following code snippet before the placeholder: <|code_start|>
def chain_afts(self, v, *args, **kwargs):
raise NotImplementedError
@_Derivate
@modifiers.kwoargs('y')
def _sub_inst(x, y):
raise NotImplementedError
base_func = _base_inst.ft, 'x, y, z', {'_free_func':... | @tup('a, y=None, z=None', {0: 'a', '_free_func': 'yz'}) |
Continue the code snippet: <|code_start|>class _ForgerWrapper(object):
def __init__(self, obj, forger):
update_wrapper(self, obj)
self.__wrapped__ = obj
self._transformed = False
self._signature_forger = forger
try:
del self.__signature__
except AttributeE... | _util.safe_get(self.__wrapped__, instance, owner), |
Predict the next line after this snippet: <|code_start|>
"""
`sigtools.specifiers`: Decorators to enhance a callable's signature
-------------------------------------------------------------------
The ``forwards_to_*`` decorators from this module will leave a "note" on the
decorated object for `sigtools.specifiers.sig... | _kwowr = modifiers.kwoargs('obj') |
Predict the next line after this snippet: <|code_start|> (a, b, /)
"""
@modifiers.kwoargs('emulate')
def _apply_forger(emulate=None, *args, **kwargs):
def _applier(obj):
return set_signature_forger(
obj, partial(func, *args, **kwargs), emulate)
return _app... | return signatures.forwards( |
Given the following code snippet before the placeholder: <|code_start|>-------------------------------------------------------------------
The ``forwards_to_*`` decorators from this module will leave a "note" on the
decorated object for `sigtools.specifiers.signature` to pick up. These "notes"
tell `signature` in whic... | signature = _specifiers.forged_signature |
Here is a snippet: <|code_start|># OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`sigtools.support`: Utilities for use in interactive sessions and unit tests
----------------------------------------------------------------------------
"""
__all__ = [
's', 'f', 'r... | def read_sig(sig_str, ret=_util.UNSET, *, |
Using the snippet: <|code_start|> code.append(f'@modifiers.annotate({return_annotation})')
elif annotations:
annotation_args = ', '.join(
f'{key}={value}'.format(key, value)
for key, value in annotations.items())
code.append(f'@modifiers.annotate({annotation_args})')
... | exec(code, { "modifiers": modifiers }, locals) |
Given the following code snippet before the placeholder: <|code_start|>
.. warning::
The contents of the arguments are eventually passed to `exec`.
Do not use with untrusted input.
::
>>> from sigtools.support import s
>>> sig = s('a, b=2, *args, c:"annotation", **kwargs')
... | pospars, pokpars, varargs, kwopars, varkwargs = signatures.sort_params(sig) |
Given the following code snippet before the placeholder: <|code_start|> >>> func(1, 2, 3, 4, c=5, d=6)
{'b': 2, 'a': 1, 'kwargs': {'d': 6}, 'args': (3, 4)}
"""
return make_func(
func_code(
*read_sig(sig_str, ret=ret, **kwargs),
name=name,
pre=pre,
... | return specifiers.signature(f(*args, **kwargs)) |
Using the snippet: <|code_start|>
def inner(a, b):
raise NotImplementedError
class AClass(object):
class_attr = True
"""class attr doc"""
def __init__(self):
self.abc = 123
"""instance attr doc"""
@specifiers.forwards_to(inner)
def outer(self, c, *args, **kwargs):
ra... | @modifiers.autokwoargs |
Based on the snippet: <|code_start|>
def inner(a, b):
raise NotImplementedError
class AClass(object):
class_attr = True
"""class attr doc"""
def __init__(self):
self.abc = 123
"""instance attr doc"""
<|code_end|>
, predict the immediate next line with the help of imports:
from sigt... | @specifiers.forwards_to(inner) |
Given the code snippet: <|code_start|># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLA... | sig = support.s(sig_str) |
Next line prediction: <|code_start|># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def remove_spaces(s):
return s.strip().replace(' ', '')
force_modifiers = {
'use_modifiers_a... | pf_sig = _specifiers.forged_signature(support.func_from_sig(sig)) |
Given the following code snippet before the placeholder: <|code_start|># copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of... | class RoundTripTests(Fixtures): |
Given the following code snippet before the placeholder: <|code_start|># sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fil... | sig = merge(*sigs) |
Here is a snippet: <|code_start|> annotation_right = 'a:1', {1: 'a', 2: 'a'}, 'a', 'a:1'
star_erase = '', {}, '*args', ''
star_same = '*args', {1: ['args'], 2: ['args']}, '*args', '*args'
star_name = '*largs', {1: ['largs']}, '*largs', '*rargs'
star_same_pok = (
'a, *args', Od([(1, ['a', 'ar... | self.assertRaises(IncompatibleSignatures, merge, *sigs) |
Given snippet: <|code_start|>#!/usr/bin/env python
# sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 Yann Kaiser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),... | sigs = [s(sig, name='_' + str(i)) |
Using the snippet: <|code_start|>
sig = merge(*sigs)
exp_sig = s(result)
exp_sources['+depths'] = dict(
('_' + str(i + 1), 0) for i in range(len(signatures)))
self.assertSigsEqual(sig, exp_sig)
self.assertSourcesEqual(sig.sources, exp_sources)
sigs = [
... | pokarg_found_kwo = '*, a', Od([(1, 'a'), (2, 'a')]), '*, a', 'a' |
Continue the code snippet: <|code_start|>logger = logging.getLogger(__name__)
class CommandAdmin(admin.ModelAdmin):
list_display = ('title', 'command', 'created', 'updated', "order")
search_fields = ['title', 'command']
prepopulated_fields = {'slug': ('title',)}
actions = tuple(list(admin.ModelAdmin.a... | admin.site.register(Command, CommandAdmin) |
Given the code snippet: <|code_start|>
class Command(BaseCommand):
help = "Pulls tweets via and associates with a given fire"
def handle(self, *args, **options):
<|code_end|>
, generate the next line using the imports in this file:
from django.core.management.base import BaseCommand
from calfire_tracker.twee... | task_run = TwitterHashtagSearch() |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger("calfire_tracker")
class Compiler(TestCase):
fixtures = ["calfire_tracker/fixtures/wildfire_sources.json"]
def setUp(self):
"""
setup some variables for our tests
"""
logger.debug("Setting up te... | self.source = WildfireSource.objects.filter(source_short="calfire", source_active=True)[0] |
Here is a snippet: <|code_start|>
logger = logging.getLogger("calfire_tracker")
class Command(BaseCommand):
help = "Scrapes California Wildfires data from CalFire and some Inciweb Pages"
def calfire_current_incidents(self, *args, **options):
<|code_end|>
. Write the next line using the current file imports:
... | task_run = RetrieveCalFireCurrentIncidents() |
Using the snippet: <|code_start|>
class Agora(models.Model):
'''
Represents an Agora, formed by a group of people which can vote and delegate
'''
ELECTION_TYPES = (
('SIMPLE_DELEGATION', _('Simple election for delegates where only one delegate can be chosen')),
<|code_end|>
, determine the ne... | ) + parse_voting_methods() |
Given the code snippet: <|code_start|>
# find question in election
question = None
for q in self.election.questions:
if q['question'] == self.label:
question = q
# gather possible answers
possible_answers = [answer['value'] for answer in question['ans... | class BaseSTVTally(BaseTally): |
Here is a snippet: <|code_start|> def __init__(self, *args, **kwargs):
self.election = kwargs['election']
del kwargs['election']
self.question = kwargs['question']
del kwargs['question']
return super(PluralityField, self).__init__(*args, **kwargs)
def clean(self, value)... | class PluralityTally(BaseTally): |
Given the code snippet: <|code_start|>
if not election.is_frozen():
election.frozen_at_date = election.archived_at_date
election.save()
context = get_base_email_context(self.request)
context.update(dict(
election=election,
election_url=reverse('elec... | context['delegate'] = get_delegate_in_agora(vote.voter, election.agora) |
Using the snippet: <|code_start|># Copyright (C) 2012 Eduardo Robles Elvira <edulix AT wadobo DOT com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, o... | url(r'^api/', include(v1.urls)), |
Based on the snippet: <|code_start|> if not isinstance(value, list):
raise error
# check for repeated answers
if len(value) != len(set(value)):
raise error
# find question in election
question = None
for q in self.election.questions:
i... | class WrightSTVTally(BaseTally): |
Given the following code snippet before the placeholder: <|code_start|>
# anonymous user has no special permissions
data = self.postAndParse('agora/1/action/', data=orig_data,
code=HTTP_OK, content_type='application/json')
self.assertEquals(set(data["permissions"]), set([]))
... | result = send_request_membership_mails.apply_async(kwargs=kwargs) |
Based on the snippet: <|code_start|>
# Give permissions to view and change profile
for perm in ASSIGNED_PERMISSIONS['profile']:
assign(perm[0], new_user, new_profile)
# Give permissions to view and change itself
for perm in ASSIGNED_PERMISSIONS['user']:
assign(pe... | salt, activation_key = generate_sha1(user.username) |
Given snippet: <|code_start|> String containing the username of the new user.
:param email:
String containing the email address of the new user.
:param password:
String containing the password for the new user.
:param active:
Boolean that defines... | profile_model = get_profile_model() |
Predict the next line for this snippet: <|code_start|> election.save()
context = get_base_email_context_task(is_secure, site_id)
context.update(dict(
election=election,
election_url=reverse('election-view',
kwargs=dict(username=election.agora.creator.username,
ag... | context['delegate'] = get_delegate_in_agora(voter, election.agora) |
Predict the next line after this snippet: <|code_start|>"""A management command to create an offlineimap configuration file."""
class Command(BaseCommand):
"""Command definition."""
help = "Generate an offlineimap configuration file."
def add_arguments(self, parser):
"""Add extra arguments t... | ImapMigration().load() |
Given the following code snippet before the placeholder: <|code_start|>"""A management command to create an offlineimap configuration file."""
class Command(BaseCommand):
"""Command definition."""
help = "Generate an offlineimap configuration file."
def add_arguments(self, parser):
"""Add ex... | "migrations": Migration.objects.select_related( |
Here is a snippet: <|code_start|> 'syslog': {
'format': '%(name)s: %(levelname)s %(message)s'
},
},
'handlers': {
'syslog-auth': {
'class': 'logging.handlers.SysLogHandler',
'facility': SysLogHandler.LOG_AUTH,
'formatter': 'syslog'
}... | modoboa_imap_migration_settings.apply(globals()) |
Predict the next line for this snippet: <|code_start|> 2: "(noSuchName)",
3: "(badValue)",
4: "(readOnly)",
5: "(genErr)",
6: "(noAccess)",
7: "(wrongType)",
8: "(wrongLength)",
9: "(wrongEncoding)",
10: "(wrongValue)",
11: "(noCreation)",
12: "(inconsistentValue)",
13: "(... | value: Union[PyType, Type, None] = None |
Given snippet: <|code_start|>"""
Unit tests for types specified in RFC-2578
"""
@pytest.mark.parametrize(
"value, expected",
[
(-42, 0), # Underflow below threshold
(-1, 0), # Underflow at threshold
(0, 0), # The minimum value
(42, 42), # A normal value
(2 ** 32 -... | instance = t.Counter(value) |
Given the following code snippet before the placeholder: <|code_start|>asyncio.
Care is taken to make this as pythonic as possible and hide as many of the gory
implementations as possible.
This module provides "syntactic sugar" around the lower-level, but almost
identical, module :py:mod:`puresnmp.aio.api.raw`.
The ... | T = TypeVar("T", bound=PyType) # pylint: disable=invalid-name |
Given snippet: <|code_start|>
See the "raw" equivalent for detailed documentation & examples.
"""
raw_output = raw.multiwalk(ip, community, oids, port, timeout, fetcher)
async for oid, value in raw_output:
if isinstance(value, Type):
value = value.pythonize()
yield VarBind(oi... | mappings: List[Tuple[str, TWrappedPyType]], |
Predict the next line for this snippet: <|code_start|>The "raw" module returns the variable types unmodified which are all subclasses
of :py:class:`x690.types.Type`.
"""
# TODO (advanced): This module should not make use of it's own functions. The
# is beginning to be too "thick", containing too much business logi... | async def get(ip, community, oid, port=161, timeout=DEFAULT_TIMEOUT): |
Using the snippet: <|code_start|>"""
This module contains the high-level functions to access the library with
asyncio.
Care is taken to make this as pythonic as possible and hide as many of the gory
implementations as possible.
This module provides "syntactic sugar" around the lower-level, but almost
identical, modul... | TWalkResponse = AsyncGenerator[VarBind, None] |
Based on the snippet: <|code_start|> community,
scalar_oids,
repeating_oids,
max_list_size=1,
port=161,
timeout=DEFAULT_TIMEOUT,
):
# type: (str, str, List[str], List[str], int, int, int) -> BulkResult
"""
Delegates to :py:func:`~puresnmp.aio.api.raw.bulkget` but returns simple
Py... | return BulkResult(pythonized_scalars, pythonized_list) |
Given the code snippet: <|code_start|> @property
def values(self):
# type: () -> Dict[str, Any]
"""
Returns all the values contained in this trap as dictionary mapping
OIDs to values.
"""
output = {}
for oid_raw, value_raw in self.raw_trap.varbinds[2:]:
... | ip, community, oids, port=161, timeout=DEFAULT_TIMEOUT, version=Version.V2C |
Continue the code snippet: <|code_start|>
@property
def uptime(self) -> timedelta:
"""
Returns the uptime of the device.
"""
return self.raw_trap.varbinds[0].value.pythonize() # type: ignore
@property
def oid(self) -> str:
"""
Returns the Trap-OID
... | def get(ip, community, oid, port=161, timeout=2, version=Version.V2C): |
Next line prediction: <|code_start|>
if TYPE_CHECKING: # pragma: no cover
# pylint: disable=unused-import, invalid-name, ungrouped-imports
T = TypeVar("T", bound=PyType)
_set = set
LOG = logging.getLogger(__name__)
OID = ObjectIdentifier.from_string
TWalkResponse = Generator[VarBind, None, None]
class T... | raw_trap: Trap |
Next line prediction: <|code_start|>
Care is taken to make this as pythonic as possible and hide as many of the gory
implementations as possible.
This module provides "syntactic sugar" around the lower-level, but almost
identical, module :py:mod:`puresnmp.api.raw`.
The "raw" module returns the variable types unmodifi... | TWalkResponse = Generator[VarBind, None, None] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.