Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>
router = routers.DefaultRouter()
router.register(r'projects', ProjectViewSet)
router.register(r'modules', ModuleViewSet)
router.register(r'issue_kinds', IssueKindViewSet)
<|code_end|>
with the help of current file imports:
from django.conf.urls import url, inclu... | router.register(r'issues', IssueViewSet) |
Based on the snippet: <|code_start|>
router = routers.DefaultRouter()
router.register(r'projects', ProjectViewSet)
router.register(r'modules', ModuleViewSet)
router.register(r'issue_kinds', IssueKindViewSet)
router.register(r'issues', IssueViewSet)
<|code_end|>
, predict the immediate next line with the help of import... | router.register(r'directories', DirectoryViewSet) |
Given snippet: <|code_start|>
class TestClient(unittest.TestCase):
def test_set_base_url_and_token(self):
client = APIClient(
host_url = 'https://example.com:9090',
auth_token = 'some_token',
)
with patch('daprojects_python.client.requests.get') as mock_requests_g... | some_resources = client.list_resources(client.base_url + '/some_resources/', APIResource) |
Given the following code snippet before the placeholder: <|code_start|> def test_resource_subclass(self):
class SomeResource(APIResource):
def some_method(self):
return self.a + self.b
client = APIClient()
with patch('daprojects_python.client.requests.get') as mo... | daprojects_api = DAProjectsAPI( |
Next line prediction: <|code_start|># file test_binfile/test_outlookexpress.py
#
# Copyright 2012 Emory University Libraries
#
# 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
#
# ... | idx = outlookexpress.MacIndex(self.index_filename) |
Continue the code snippet: <|code_start|>
class TaskResultAdmin(admin.ModelAdmin):
list_display = ('object_id', 'status_icon', 'label', 'created',
'duration', 'result')
search_fields = ('object_id', 'label', 'result')
list_filter = ('created', )
# disallow creating task results via ... | admin.site.register(TaskResult, TaskResultAdmin) |
Predict the next line after this snippet: <|code_start|>#
# Copyright 2010,2016 Emory University General Library
#
# 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.a... | tr = TaskResult(label='test task', object_id='id', url='/foo', task_id=id) |
Given the following code snippet before the placeholder: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the Lice... | decorator = content_negotiation({'application/xml': xml_view}) |
Predict the next line for this snippet: <|code_start|># file test_djangoextras/test_validators.py
#
# Copyright 2012 Emory University Libraries
#
# 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 Li... | self.text_val = FileTypeValidator(types=['text/plain']) |
Using the snippet: <|code_start|># file test_binfile/test_eudora.py
#
# Copyright 2011 Emory University Libraries
#
# 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.... | obj = eudora.Toc(fname) |
Based on the snippet: <|code_start|>'''
Test list creation
'''
class testListCreation(unittest.TestCase):
'''
Test menu creation
'''
def setUp(self):
'''
list fixtures for tests
'''
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest... | self.list = list.List('gateways','deny') |
Next line prediction: <|code_start|>'''
Test list creation
'''
class testListCreation(unittest.TestCase):
'''
Test menu creation
'''
def setUp(self):
'''
list fixtures for tests
'''
self.list = list.List('gateways','deny')
def test_list_dict_ok(self):
... | n = node.Node('allow', '10.10.10.10/32') |
Given the following code snippet before the placeholder: <|code_start|>'''
Test gateway creation
'''
class testGatewayCreation(unittest.TestCase):
'''
Test gateway creation
'''
def setUp(self):
'''
gateway fixtures for tests
'''
<|code_end|>
, predict the next line using imports from the current file:... | self.gw = gateway.Gateway('name') |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.mark.parametrize("data,expected", [
(
{'tag': 'domain', 'children': [{'tag': 'params', 'children': []}, {'tag': 'variables', 'children': []}, {'tag': 'users', 'children': []}], 'attrs': {'name': 'wirephone.com.ar'}},
... | f = XMLFactory(data) |
Given the code snippet: <|code_start|>'''
Test condition creation for dialplan
'''
class AppMock(object):
"""An application interface mockup"""
def __init__(self):
super(AppMock, self).__init__()
self.app_name = 'test'
self.data = ''
class testConditionCreation(unittest.TestCase):
'''
Test condition cre... | self.cond = condition.Condition('destination_number','1000') |
Here is a snippet: <|code_start|>'''
Test menu creation
'''
class testMenuCreation(unittest.TestCase):
'''
Test menu creation
'''
def setUp(self):
'''
menu fixtures for tests
'''
<|code_end|>
. Write the next line using the current file imports:
import unittest
import pytest
from wirecurly.configurat... | self.menu = menu.Menu('on_hours') |
Predict the next line for this snippet: <|code_start|>'''
Test node creation for acls
'''
class testNodeCreation(unittest.TestCase):
'''
Test node creation
'''
def setUp(self):
'''
Node fixtures for tests
'''
<|code_end|>
with the help of current file imports:
import unittest
from wirecurly.configur... | self.node = node.Node('allow','100.100.100.100/32') |
Using the snippet: <|code_start|># --------------------------------------------------------
# TFFRCNN - Resnet50
# Copyright (c) 2016
# Licensed under The MIT License [see LICENSE for details]
# Written by miraclebiu
# --------------------------------------------------------
class PVAnet_test(Network):
def __init... | n_classes = cfg.NCLASSES |
Here is a snippet: <|code_start|># --------------------------------------------------------
# TFFRCNN - Resnet50
# Copyright (c) 2016
# Licensed under The MIT License [see LICENSE for details]
# Written by miraclebiu
# --------------------------------------------------------
class Resnet101_test(Network):
def __in... | n_classes = cfg.NCLASSES |
Given the code snippet: <|code_start|># --------------------------------------------------------
# TFFRCNN - Resnet50
# Copyright (c) 2016
# Licensed under The MIT License [see LICENSE for details]
# Written by miraclebiu
# --------------------------------------------------------
class Resnet50_test(Network):
def... | n_classes = cfg.NCLASSES |
Given snippet: <|code_start|>
class VGGnet_test(Network):
def __init__(self, trainable=True):
self.inputs = []
self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3])
self.im_info = tf.placeholder(tf.float32, shape=[None, 3])
self.keep_prob = tf.placeholder(tf.float32)
... | n_classes = cfg.NCLASSES |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@login_required
@ensure_csrf_cookie
def home(request):
if not request.session.get('django_language', None):
request.session['django_language'] = get_language()
me = request.user.member
following = me.following.all().count()
followers = m... | me = get_object_or_404(Member, user__username=request.GET['username']) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@login_required
@ensure_csrf_cookie
def home(request):
if not request.session.get('django_language', None):
request.session['django_language'] = get_language()
me = request.user.member
following = me.following.all().count()
followers = m... | nodwits = Dwit.objects.filter(member=me).count() |
Given snippet: <|code_start|> followers = me.followers.all().count()
nodwits = Dwit.objects.filter(member=me).count()
context_vars={'me':me,'following':following,'followers':followers,'nodwits':nodwits,'navbar':'home'}
if request.GET.get('tag'):
context_vars.update({'tag':request.GET['tag']})
... | dwitspf = DPF.objects.filter(member = me)[int(nfd):int(nfd)+int(nod)] |
Given the code snippet: <|code_start|> return render_to_response(template_name,context_vars,context_instance=context)
@login_required
def dwit(request):
if request.method != 'POST':
response = HttpResponse(mimetype="text/html")
response['content-type']="text/html; charset=UTF-8"
response... | celery_dwitsaved.delay(dwit, rendered) |
Continue the code snippet: <|code_start|> context_vars={'m':m,'fing':fing,'fers':fers,'action':action,'nodwits':nodwits,'following':following,'followers':followers,'navbar':'profile'}
if not action:
if request.method == 'POST':
form = MemberForm(request.POST, request.FILES, instance=m)
... | celery_follow.delay(me, m) |
Given snippet: <|code_start|> ferrors = ''
for field in form:
if field.errors:
ferrors += '<b>'+field.label+'</b>: '
for error in field.errors:
ferrors += error+'<br />'
context... | celery_unfollow.delay(me,m) |
Based on the snippet: <|code_start|> if dwit.tags:
tags = dwit.tags.all()
newdwit.tags.add(*tags)
rendered = render_to_string('flow.html',{'dwits':[newdwit]})
celery_dwitsaved.delay(newdwit, rendered)
response = HttpResponse(mimetype="application/json")
response.wr... | form = MemberForm(request.POST, request.FILES, instance=m) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
@login_required
@ensure_csrf_cookie
def home(request):
if not request.session.get('django_language', None):
request.session['django_language'] = get_language()
me = request.user.member
following = me.following.all().count()
follower... | form = SearchForm(request.GET) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
class MemberIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from hayst... | return Member |
Given the code snippet: <|code_start|>
# Otherwise we need to check the backends.
return _user_has_perm(self, perm, obj)
def has_perms(self, perm_list, obj=None):
"""
Returns True if the user has each of the specified permissions. If
object is passed, it checks if the user h... | celery_send_mail.delay(subject, message, from_email, [self.email]) |
Next line prediction: <|code_start|>
class RegistrationAdmin(admin.ModelAdmin):
actions = ['activate_users', 'resend_activation_email']
list_display = ('user', 'activation_key', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name', 'user__last_name')... | RegistrationProfile.objects.activate_user(profile.activation_key) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class MemberForm(ModelForm):
image = forms.ImageField(label=u'Εικόνα', required=False)
class Meta:
<|code_end|>
with the help of current file imports:
from django.forms import ModelForm
from django import forms
from django.forms ... | model = Member |
Based on the snippet: <|code_start|>
@never_cache
def remote_user_auth_view(request):
"Dummy view for remote user tests"
t = Template("Username is {{ user }}.")
c = RequestContext(request, {})
return HttpResponse(t.render(c))
def auth_processor_no_attr_access(request):
r1 = render_to_response('cont... | RequestContext(request, {}, processors=[context_processors.auth])) |
Predict the next line for this snippet: <|code_start|> {'session_accessed':request.session.accessed})
def auth_processor_attr_access(request):
r1 = render_to_response('context_processors/auth_attrs_access.html',
RequestContext(request, {}, processors=[context_processors.auth]))
return render_to_... | (r'^login_required/$', login_required(password_reset)), |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@task
def celery_dwitsaved(dwit, rendered):
if dwit.direct:
fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:])
else:
fers = dwit.member.followers.all()
for fer in fers:
DPF.objec... | emit_to_channel(fer.user.username, 'newdwit', json.dumps({'content':rendered})) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
@task
def celery_dwitsaved(dwit, rendered):
if dwit.direct:
fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:])
else:
fers = dwit.member.followers.all()
for fer in fers:
<|code_end|>
. Wr... | DPF.objects.create(member = fer, dwit = dwit, stamp = dwit.stamp) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
@task
def celery_dwitsaved(dwit, rendered):
if dwit.direct:
fers = dwit.member.followers.filter(user__username=re.match('^\@\w+',dwit.content).group(0)[1:])
else:
fers = dwit.member.followers.all()
for fer in ... | dwits = Dwit.objects.filter(member=m).exclude(direct=True) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
@namespace('/dwits')
class DwitsNamespace(BaseNamespace, RoomsMixin):
def initialize(self):
self.logger = logging.getLogger("socketio.dwits")
self.log("Socketio session started")
def log(self, message):
... | r = redis_connection().pubsub() |
Given the following code snippet before the placeholder: <|code_start|>
def test_frozendict():
my_dict = {
'key': 'DEFAULT',
}
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from ckan_api_client.utils import freeze, FrozenDict, FrozenList
and context includi... | my_frozen_dict = freeze(my_dict) |
Given the code snippet: <|code_start|>
def test_frozendict():
my_dict = {
'key': 'DEFAULT',
}
my_frozen_dict = freeze(my_dict)
assert my_dict == my_frozen_dict
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from ckan_api_client.utils import freeze, Frozen... | assert isinstance(my_frozen_dict, FrozenDict) |
Next line prediction: <|code_start|>
my_list.append('bacon')
assert my_list == ['egg', 'spam', 'bacon']
assert list(my_frozen_list) == ['egg', 'spam', 'bacon']
with pytest.raises(TypeError):
my_frozen_list[1] = 'SPAM!!'
with pytest.raises(AttributeError):
my_frozen_list.pop(0)
... | assert isinstance(frozobj['a list'], FrozenList) |
Given the code snippet: <|code_start|>
def test_diff_dicts():
dct1 = {
'one': 'VAL-1',
'two': 'VAL-2',
'three': 'VAL-3',
'four': 'VAL-4',
'five': 'VAL-5',
}
dct2 = {
'three': 'VAL-3',
'four': 'VAL-4-2',
'five': 'VAL-5-2',
'six': 'VAL-6... | diff = diff_mappings(dct1, dct2) |
Based on the snippet: <|code_start|>
def test_diff_dicts():
dct1 = {
'one': 'VAL-1',
'two': 'VAL-2',
'three': 'VAL-3',
'four': 'VAL-4',
'five': 'VAL-5',
}
dct2 = {
'three': 'VAL-3',
'four': 'VAL-4-2',
'five': 'VAL-5-2',
'six': 'VAL-6',... | diff = diff_sequences([1, 2, 3], [1, 2, 9]) |
Predict the next line for this snippet: <|code_start|>"""
Test some simple harvesting scenarios, generating data on-the-fly
"""
# import os
# import pytest
# from ckan_api_client.syncing import CkanDataImportClient
# from .utils.harvest_source import HarvestSource
def generate_data():
organizations = generate_... | org = generate_organization() |
Using the snippet: <|code_start|># from ckan_api_client.syncing import CkanDataImportClient
# from .utils.harvest_source import HarvestSource
def generate_data():
organizations = generate_organizations(5)
groups = generate_groups(10)
datasets = generate_datasets(
groups=groups, organizations=orga... | grp = generate_group() |
Given snippet: <|code_start|> groups=groups, organizations=organizations, amount=20)
return {
'organization': organizations,
'group': groups,
'dataset': datasets,
}
def generate_organizations(amount=10):
organizations = {}
for i in xrange(3):
org = generate_orga... | dataset = generate_dataset() |
Using the snippet: <|code_start|>"""
Test some simple harvesting scenarios, generating data on-the-fly
"""
# import os
# import pytest
# from ckan_api_client.syncing import CkanDataImportClient
# from .utils.harvest_source import HarvestSource
def generate_data():
organizations = generate_organizations(5)
... | org['id'] = org['name'] = 'org-{0}'.format(generate_id()) |
Given the following code snippet before the placeholder: <|code_start|>"""Make sure tests setup & fixtures are all fine"""
# todo: we should check all fixtures in here!
def test_site_read(ckan_url):
"""GET /site_read/ should return 200"""
api_url = ckan_url('/api/3/action/site_read')
response = reques... | data = check_response_ok(response) |
Given the code snippet: <|code_start|>"""
Tests to pin-point exact behavior of datasets CRUD, in particular
updates.
"""
def test_dataset_simple_crud(ckan_client_ll):
# Let's try creating a dataset
now = datetime.datetime.now()
now_str = now.strftime('%F %T')
_dataset = {
<|code_end|>
, generate ... | 'name': 'dataset-{0}'.format(gen_random_id()), |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# Generate some dummy data, for testing purposes
def generate_organization():
"""
Generate a random organization object, with:
- ``name``, random, example: ``"org-abc123"``
- ``title``, random, example: ``"Organization abc123"``
- ``d... | random_id = gen_random_id(10) |
Given snippet: <|code_start|>#!/usr/bin/env python
# Generate some dummy data, for testing purposes
def generate_organization():
"""
Generate a random organization object, with:
- ``name``, random, example: ``"org-abc123"``
- ``title``, random, example: ``"Organization abc123"``
- ``descriptio... | "image_url": gen_picture(random_id), |
Here is a snippet: <|code_start|> created = client.post_group(group)
check_group(created, group)
group_id = created['id']
# Retrieve & check
retrieved = client.get_group(group_id)
assert retrieved == created
# Update & check
updated = client.put_group({'id': group_id, 'title': 'My Group... | with pytest.raises(HTTPError) as excinfo: |
Next line prediction: <|code_start|>
@pytest.mark.xfail(run=False, reason='Work in progress')
def test_group_crud(ckan_client_ll):
client = ckan_client_ll
<|code_end|>
. Use current file imports:
(import copy
import pytest
from ckan_api_client.exceptions import HTTPError
from ckan_api_client.tests.utils.strings... | code = gen_random_id() |
Continue the code snippet: <|code_start|>
@pytest.mark.xfail(run=False, reason='Work in progress')
def test_group_crud(ckan_client_ll):
client = ckan_client_ll
code = gen_random_id()
group = {
'name': 'group-{0}'.format(code),
'title': 'Group {0}'.format(code),
}
created = client.... | check_group(created, group) |
Using the snippet: <|code_start|>class ListField(MutableFieldMixin, BaseField):
default = staticmethod(lambda: [])
def validate(self, instance, name, value):
value = super(ListField, self).validate(instance, name, value)
if not isinstance(value, SEQUENCE_TYPES):
raise ValueError("{0... | if not isinstance(value, MAPPING_TYPES): |
Based on the snippet: <|code_start|> # to be extra safe, make copy here, even on
# default values, which might get shared..
instance._updates[name] = copy.deepcopy(
self.validate(instance, name, value))
return instance._updates[name]
def serialize(self, i... | if not isinstance(value, SEQUENCE_TYPES): |
Based on the snippet: <|code_start|> assert len(actual) == len(actual_resources)
for res_id in expected_resources:
expected_resource = expected_resources[res_id]
actual_resource = actual_resources[res_id]
for key_id in expected_resource:
assert expected_resource[key_id] \
... | client = CkanClient(ckan_instance.server_url, api_key=API_KEY) |
Next line prediction: <|code_start|> :return: a requests response object
"""
headers = kwargs.get('headers') or {}
kwargs['headers'] = headers
# Update headers for authorization
if self.api_key is not None:
headers['Authorization'] = self.api_key
# S... | raise HTTPError( |
Predict the next line after this snippet: <|code_start|> def _figure_out_error_message(self, response):
"""
We have a response, which probably contains an error message,
but we need to figure that out..
Usual places for errors are:
- a json message, with {'error': {'message'... | raise BadApiError( |
Predict the next line after this snippet: <|code_start|>
url = urlparse.urljoin(self.base_url, path)
response = requests.request(method, url, **kwargs)
if not response.ok:
# ------------------------------------------------------------
# todo: attach message, if any availa... | with SuppressExceptionIf(True): |
Given the following code snippet before the placeholder: <|code_start|>
# Add included file to stack, checking for cycles in the process.
link_stack.push(filename)
# Process the block's file if it hasn't been processed before.
if not block_map.has_block(filename, block_name):
with open(filename... | class InvalidBlockName(TemplarError): |
Next line prediction: <|code_start|>
class MarkdownToHtmlRule(core.Rule):
def __init__(self, src=r'\.md', dst=r'\.html'):
super().__init__(src, dst)
def apply(self, content):
# TODO(wualbert): rewrite markdown parser, or use a library.
<|code_end|>
. Use current file imports:
(from templar imp... | return markdown.convert(content) |
Given snippet: <|code_start|> =
"""
expect = '<h1 id="hello-world">Hello World!</h1>'
self.assertMarkdown(simple, expect)
simple = """
With some 1337 hax0r
=
"""
expect = '<h1 id="with-some-1337-hax0r">With some 1337 hax0r</h1>'
self.assert... | self.assertEqual(expect, convert(simple)) |
Continue the code snippet: <|code_start|> return self
def add_variable(self, variable, value):
if not isinstance(variable, str):
raise ConfigBuilderError(
'variable must be a string, but instead was: ' + repr(variable))
# TODO: Coerce value into some string (p... | if not isinstance(rule, Rule): |
Here is a snippet: <|code_start|> def to_builder(self):
return ConfigBuilder(
self._template_dirs,
self._variables,
self._recursively_evaluate_jinja_expressions,
self._compiler_rules,
self._preprocess_rules,
self.... | class ConfigBuilderError(TemplarError): |
Predict the next line after this snippet: <|code_start|>"""End-to-end test for templar/cli/templar.py"""
STAGING_DIR = os.path.join('tests', 'cli', 'staging')
TEST_DATA = os.path.join('tests', 'cli', 'test_data')
class TemplarTest(unittest.TestCase):
def setUp(self):
os.mkdir(STAGING_DIR)
def tearD... | with self.assertRaises(ConfigBuilderError) as cm: |
Using the snippet: <|code_start|>"""End-to-end test for templar/cli/templar.py"""
STAGING_DIR = os.path.join('tests', 'cli', 'staging')
TEST_DATA = os.path.join('tests', 'cli', 'test_data')
class TemplarTest(unittest.TestCase):
def setUp(self):
os.mkdir(STAGING_DIR)
def tearDown(self):
shut... | templar.run(templar.flags([ |
Here is a snippet: <|code_start|>"""Tests templar/api/rules/core.py"""
class RuleTest(unittest.TestCase):
def testApplies_withSrcRegex(self):
rule = Rule(src='.html')
self.assertTrue(rule.applies('source.html', 'destination'))
self.assertFalse(rule.applies('source.py', 'destination'))
... | class TestRule(SubstitutionRule): |
Here is a snippet: <|code_start|>
class RuleTest(unittest.TestCase):
def testApplies_withSrcRegex(self):
rule = Rule(src='.html')
self.assertTrue(rule.applies('source.html', 'destination'))
self.assertFalse(rule.applies('source.py', 'destination'))
def testApplies_withDestRegex(self):... | with self.assertRaises(InvalidRule) as cm: |
Given the following code snippet before the placeholder: <|code_start|>"""Tests template/linker/blocks.py"""
class LinkTest(unittest.TestCase):
def setUp(self):
self.is_file_patcher = mock.patch('os.path.isfile')
self.mock_is_file = self.is_file_patcher.start()
self.mock_is_file.return_va... | link('no/such/path') |
Given the code snippet: <|code_start|> def side_effect(filename, *options):
assert filename in file_map, 'File ' + filename + ' not found in ' + str(list(file_map))
return mock.mock_open(read_data=file_map[filename])(filename, *options)
self.mock_is_file.side_effect = lambda f: f... | block_dict = get_block_dict(block_all) |
Predict the next line after this snippet: <|code_start|>"""Tests template/linker/blocks.py"""
class LinkTest(unittest.TestCase):
def setUp(self):
self.is_file_patcher = mock.patch('os.path.isfile')
self.mock_is_file = self.is_file_patcher.start()
self.mock_is_file.return_value = True
... | block_all = Block('some/path', 'all', [data]) |
Predict the next line for this snippet: <|code_start|>"""Tests template/linker/blocks.py"""
class LinkTest(unittest.TestCase):
def setUp(self):
self.is_file_patcher = mock.patch('os.path.isfile')
self.mock_is_file = self.is_file_patcher.start()
self.mock_is_file.return_value = True
d... | with self.assertRaises(SourceNotFound) as cm: |
Here is a snippet: <|code_start|> block_all = Block('some/path', 'all', [block_foo])
self.assertBlockEqual(block_all, block)
def testBlocks_nested(self):
data = self.join_lines(
'<block outer>',
'outer content',
'<block inner>',
'inner content',
'</blo... | with self.assertRaises(InvalidBlockName) as cm: |
Given snippet: <|code_start|>
def testIncludes_relativeToSource(self):
mock_open = self.mock_open({
'path/to/docA.md': '<include docB.md>',
'path/to/docB.md': 'content',
})
with mock_open:
block, variables = link('path/to/docA.md')
self.assertEqua... | with self.assertRaises(IncludeNonExistentBlock) as cm: |
Given the following code snippet before the placeholder: <|code_start|> self.assertBlockEqual(block_all, block)
def testIncludes_preventNonExistentFile(self):
mock_open = self.mock_open({
'docA.md': '<include docB.md>', # docB.md doesn't exist.
})
with mock_open:
... | with self.assertRaises(CyclicalIncludeError) as cm: |
Using the snippet: <|code_start|>
class TemplarTest(unittest.TestCase):
def dedent(self, text):
return textwrap.dedent(text).lstrip('\n').rstrip()
def ignoreWhitespace(self, text):
text = self.dedent(text)
return re.sub('\s+', '', text, flags=re.S)
class MarkdownTest(TemplarTest):
... | self.assertEqual(output + '\n', convert(markdown) + '\n') |
Given snippet: <|code_start|> elif hasattr(self.pattern, 'sub') and callable(self.pattern.sub):
return self.pattern.sub(self.substitute, content)
raise InvalidRule(
"{}'s pattern has type '{}', but expected a string or "
"compiled regex.".format(type(self).__name__, ty... | class InvalidRule(TemplarError): |
Next line prediction: <|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, dis-
#... | ResponseError = EmrResponseError |
Using the snippet: <|code_start|> status = self.connection.revoke_security_group(self.name,
src_group_name,
src_group_owner_id,
ip_protocol,
... | raise BotoClientError('Unable to copy to the same Region') |
Based on the snippet: <|code_start|> if value.lower() == 'true':
self.delete_on_termination = True
else:
self.delete_on_termination = False
else:
setattr(self, name, value)
class NetworkInterface(TaggedEC2Object):
def __init__(self, co... | self.groups = ResultSet([('item', Group)]) |
Given the code snippet: <|code_start|>"""
Exceptions that are specific to the dynamodb module.
"""
class DynamoDBExpiredTokenError(BotoServerError):
"""
Raised when a DynamoDB security token expires. This is generally boto's
(or the user's) notice to renew their DynamoDB security tokens.
"""
pass
... | class DynamoDBKeyNotFoundError(BotoClientError): |
Predict the next line for this snippet: <|code_start|>
statement_id = fields.Many2one(
'l10n.de.tax.statement',
'Statement'
)
currency_id = fields.Many2one(
'res.currency',
related='statement_id.company_id.currency_id',
readonly=True,
help='Utility field to ex... | base_display = _base_display_2018() |
Here is a snippet: <|code_start|> statement_id = fields.Many2one(
'l10n.de.tax.statement',
'Statement'
)
currency_id = fields.Many2one(
'res.currency',
related='statement_id.company_id.currency_id',
readonly=True,
help='Utility field to express amount currency'... | tax_display = _tax_display_2018() |
Given the code snippet: <|code_start|> is_readonly = fields.Boolean(compute='_compute_is_readonly')
state = fields.Selection(related='statement_id.state')
@api.multi
@api.depends('base', 'tax', 'code')
def _compute_amount_format(self):
for line in self:
if line.statement_id.vers... | group_display = _group_display_2018() |
Using the snippet: <|code_start|>
state = fields.Selection(related='statement_id.state')
@api.multi
@api.depends('base', 'tax', 'code')
def _compute_amount_format(self):
for line in self:
if line.statement_id.version == '2019':
base_display = _base_display_2019()
... | total_display = _total_display_2018() |
Given snippet: <|code_start|> tax_display = _tax_display_2018()
base = formatLang(self.env, line.base, monetary=True)
tax = formatLang(self.env, line.tax, monetary=True)
if line.code in base_display:
line.format_base = base
if line.code in ... | editable_display = _editable_display_2018() |
Predict the next line for this snippet: <|code_start|>
name = fields.Char()
code = fields.Char()
statement_id = fields.Many2one(
'l10n.de.tax.statement',
'Statement'
)
currency_id = fields.Many2one(
'res.currency',
related='statement_id.company_id.currency_id',
... | base_display = _base_display_2019() |
Based on the snippet: <|code_start|> name = fields.Char()
code = fields.Char()
statement_id = fields.Many2one(
'l10n.de.tax.statement',
'Statement'
)
currency_id = fields.Many2one(
'res.currency',
related='statement_id.company_id.currency_id',
readonly=True,
... | tax_display = _tax_display_2019() |
Here is a snippet: <|code_start|>
is_group = fields.Boolean(compute='_compute_is_group')
is_total = fields.Boolean(compute='_compute_is_group')
is_readonly = fields.Boolean(compute='_compute_is_readonly')
state = fields.Selection(related='statement_id.state')
@api.multi
@api.depends('base', 't... | group_display = _group_display_2019() |
Given snippet: <|code_start|> is_group = fields.Boolean(compute='_compute_is_group')
is_total = fields.Boolean(compute='_compute_is_group')
is_readonly = fields.Boolean(compute='_compute_is_readonly')
state = fields.Selection(related='statement_id.state')
@api.multi
@api.depends('base', 'tax', ... | total_display = _total_display_2019() |
Using the snippet: <|code_start|> else:
base_display = _base_display_2018()
tax_display = _tax_display_2018()
base = formatLang(self.env, line.base, monetary=True)
tax = formatLang(self.env, line.tax, monetary=True)
if line.code in base_dis... | editable_display = _editable_display_2019() |
Continue the code snippet: <|code_start|>def send_backups_via_email():
result = setup_simple_command(
"send_backups_via_email",
"Report information about users and their passwords.",
)
if isinstance(result, int):
return result
else:
settings, closer, env, args = resul... | sent = send_passwords(request, user, |
Given snippet: <|code_start|>
def get_selected_users(request, *emails):
for email in emails:
for user in request.db.users.find({
'email': email,
}).sort('date_joined'):
yield user
def send_backups_via_email():
result = setup_simple_command(
"send_bac... | preferences_link = urlparse.urljoin( |
Predict the next line after this snippet: <|code_start|> "Report information about users and their passwords.",
)
if isinstance(result, int):
return result
else:
settings, closer, env, args = result
try:
request = env['request']
if len(args) == 0:
... | safe_print('Passwords sent to %s' % |
Here is a snippet: <|code_start|>
def get_all_users(request):
day = request.date_service.today().day
return request.db.users.find({
'send_passwords_periodically': True,
'email_verified': True,
'$where': '''
function () {
var i, sum;
sum = 0;
for (i = 0; i < this... | result = setup_simple_command( |
Using the snippet: <|code_start|> )
if isinstance(result, int):
return result
else:
settings, closer, env, args = result
try:
request = env['request']
if len(args) == 0:
user_iterator = get_all_users(request)
else:
user_iterator = get_... | get_user_display_name(user)) |
Given the following code snippet before the placeholder: <|code_start|> }, multi=True, safe=True)
# copy authorized_apps from user2 to user1
updates = {
'$addToSet': {
'authorized_apps': {
'$each': user2['authorized_apps'],
},
},
... | return send_email_to_admins( |
Based on the snippet: <|code_start|># Yith Library Server is a password storage server.
# Copyright (C) 2012-2013 Yaco Sistemas
# Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com>
# Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Librar... | codes = AuthorizationCodes(self.db) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.