Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) 2010-2012 OpenStack Foundation
# Copyright (c) 2016-2020 OpenIO SAS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
try:
except ImportError:
# Before Queens
class ContainerController(SwiftContainerController):
pass_through_headers = ['x-container-read', 'x-container-write',
'x-container-sync-key', 'x-container-sync-to',
<|code_end|>
, predict the next line using imports from the current file:
import json
from xml.etree.cElementTree import Element, SubElement, tostring
from swift.common.utils import public, Timestamp, \
override_bytes_from_content_type
from swift.common.constraints import check_metadata
from swift.common import constraints
from swift.common.middleware.listing_formats import \
get_listing_content_type
from swift.common.request_helpers import get_listing_content_type
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import Response, HTTPBadRequest, HTTPNotFound, \
HTTPNoContent, HTTPConflict, HTTPPreconditionFailed, HTTPForbidden, \
HTTPCreated
from swift.common.http import is_success, HTTP_ACCEPTED
from swift.common.request_helpers import is_sys_or_user_meta, get_param
from swift.proxy.controllers.container import ContainerController \
as SwiftContainerController
from swift.proxy.controllers.base import clear_info_cache, \
delay_denial, cors_validation, set_info_cache
from oio.common import exceptions
from oioswift.utils import \
handle_oio_no_such_container, handle_oio_timeout, \
handle_service_busy, REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context including class names, function names, and sometimes code from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def handle_oio_no_such_container(fnc):
# """Catch NoSuchContainer errors and return '404 Not Found'"""
# @wraps(fnc)
# def _oio_no_such_container_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except NoSuchContainer:
# return HTTPNotFound(request=req)
# return _oio_no_such_container_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | 'x-versions-location'] |
Continue the code snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
try:
except ImportError:
# Before Queens
class ContainerController(SwiftContainerController):
pass_through_headers = ['x-container-read', 'x-container-write',
'x-container-sync-key', 'x-container-sync-to',
'x-versions-location']
@handle_oio_no_such_container
@handle_oio_timeout
@handle_service_busy
<|code_end|>
. Use current file imports:
import json
from xml.etree.cElementTree import Element, SubElement, tostring
from swift.common.utils import public, Timestamp, \
override_bytes_from_content_type
from swift.common.constraints import check_metadata
from swift.common import constraints
from swift.common.middleware.listing_formats import \
get_listing_content_type
from swift.common.request_helpers import get_listing_content_type
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import Response, HTTPBadRequest, HTTPNotFound, \
HTTPNoContent, HTTPConflict, HTTPPreconditionFailed, HTTPForbidden, \
HTTPCreated
from swift.common.http import is_success, HTTP_ACCEPTED
from swift.common.request_helpers import is_sys_or_user_meta, get_param
from swift.proxy.controllers.container import ContainerController \
as SwiftContainerController
from swift.proxy.controllers.base import clear_info_cache, \
delay_denial, cors_validation, set_info_cache
from oio.common import exceptions
from oioswift.utils import \
handle_oio_no_such_container, handle_oio_timeout, \
handle_service_busy, REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context (classes, functions, or code) from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def handle_oio_no_such_container(fnc):
# """Catch NoSuchContainer errors and return '404 Not Found'"""
# @wraps(fnc)
# def _oio_no_such_container_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except NoSuchContainer:
# return HTTPNotFound(request=req)
# return _oio_no_such_container_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | def GETorHEAD(self, req): |
Predict the next line after this snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
try:
except ImportError:
# Before Queens
class ContainerController(SwiftContainerController):
pass_through_headers = ['x-container-read', 'x-container-write',
'x-container-sync-key', 'x-container-sync-to',
'x-versions-location']
@handle_oio_no_such_container
@handle_oio_timeout
@handle_service_busy
<|code_end|>
using the current file's imports:
import json
from xml.etree.cElementTree import Element, SubElement, tostring
from swift.common.utils import public, Timestamp, \
override_bytes_from_content_type
from swift.common.constraints import check_metadata
from swift.common import constraints
from swift.common.middleware.listing_formats import \
get_listing_content_type
from swift.common.request_helpers import get_listing_content_type
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import Response, HTTPBadRequest, HTTPNotFound, \
HTTPNoContent, HTTPConflict, HTTPPreconditionFailed, HTTPForbidden, \
HTTPCreated
from swift.common.http import is_success, HTTP_ACCEPTED
from swift.common.request_helpers import is_sys_or_user_meta, get_param
from swift.proxy.controllers.container import ContainerController \
as SwiftContainerController
from swift.proxy.controllers.base import clear_info_cache, \
delay_denial, cors_validation, set_info_cache
from oio.common import exceptions
from oioswift.utils import \
handle_oio_no_such_container, handle_oio_timeout, \
handle_service_busy, REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and any relevant context from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def handle_oio_no_such_container(fnc):
# """Catch NoSuchContainer errors and return '404 Not Found'"""
# @wraps(fnc)
# def _oio_no_such_container_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except NoSuchContainer:
# return HTTPNotFound(request=req)
# return _oio_no_such_container_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | def GETorHEAD(self, req): |
Continue the code snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
try:
except ImportError:
# Before Queens
class ContainerController(SwiftContainerController):
pass_through_headers = ['x-container-read', 'x-container-write',
'x-container-sync-key', 'x-container-sync-to',
'x-versions-location']
@handle_oio_no_such_container
@handle_oio_timeout
@handle_service_busy
<|code_end|>
. Use current file imports:
import json
from xml.etree.cElementTree import Element, SubElement, tostring
from swift.common.utils import public, Timestamp, \
override_bytes_from_content_type
from swift.common.constraints import check_metadata
from swift.common import constraints
from swift.common.middleware.listing_formats import \
get_listing_content_type
from swift.common.request_helpers import get_listing_content_type
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import Response, HTTPBadRequest, HTTPNotFound, \
HTTPNoContent, HTTPConflict, HTTPPreconditionFailed, HTTPForbidden, \
HTTPCreated
from swift.common.http import is_success, HTTP_ACCEPTED
from swift.common.request_helpers import is_sys_or_user_meta, get_param
from swift.proxy.controllers.container import ContainerController \
as SwiftContainerController
from swift.proxy.controllers.base import clear_info_cache, \
delay_denial, cors_validation, set_info_cache
from oio.common import exceptions
from oioswift.utils import \
handle_oio_no_such_container, handle_oio_timeout, \
handle_service_busy, REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context (classes, functions, or code) from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def handle_oio_no_such_container(fnc):
# """Catch NoSuchContainer errors and return '404 Not Found'"""
# @wraps(fnc)
# def _oio_no_such_container_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except NoSuchContainer:
# return HTTPNotFound(request=req)
# return _oio_no_such_container_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | def GETorHEAD(self, req): |
Given the code snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
# Hack PYTHONPATH so "test" is swift's test directory
sys.path.insert(1, os.path.abspath(os.path.join(__file__, '../../../../..')))
class TestOioServerSideCopyMiddleware(TestServerSideCopyMiddleware):
def setUp(self):
self.app = FakeSwift()
self.ssc = copy.filter_factory({
'object_post_as_copy': 'yes',
})(self.app)
self.ssc.logger = self.app.logger
def tearDown(self):
# get_object_info() does not close response iterator,
# thus we have to disable the unclosed_requests test.
pass
def test_basic_put_with_x_copy_from(self):
self.app.register('HEAD', '/v1/a/c/o', swob.HTTPOk, {})
self.app.register('PUT', '/v1/a/c/o2', swob.HTTPCreated, {})
req = Request.blank('/v1/a/c/o2', environ={'REQUEST_METHOD': 'PUT'},
headers={'Content-Length': '0',
'X-Copy-From': 'c/o'})
status, headers, body = self.call_ssc(req)
<|code_end|>
, generate the next line using the imports in this file:
import os.path
import sys
from six.moves import urllib
from swift.common import swob
from swift.common.swob import Request
from oioswift.common.middleware import copy
from test.unit.common.middleware.helpers import FakeSwift # noqa: E402
from test.unit.common.middleware.test_copy \
import TestServerSideCopyMiddleware # noqa: E402
and context (functions, classes, or occasionally code) from other files:
# Path: oioswift/common/middleware/copy.py
# class OioServerSideCopyMiddleware(ServerSideCopyMiddleware):
# def __init__(self, app, conf):
# def fast_copy_allowed(self, req):
# def __call__(self, env, start_response):
# def _start_response(status, headers, exc_info=None):
# def filter_factory(global_conf, **local_conf):
# def copy_filter(app):
. Output only the next line. | self.assertEqual(status, '201 Created') |
Given the code snippet: <|code_start|> ('DELETE', '/v1/a/c/o'),
])
def test_delete_latest_version_no_marker_success(self):
self.skipTest("Disabled for oio-swift")
def test_delete_latest_version_restores_marker_success(self):
self.skipTest("Disabled for oio-swift")
def test_delete_latest_version_is_marker_success(self):
self.skipTest("Disabled for oio-swift")
def test_delete_latest_version_doubled_up_markers_success(self):
self.skipTest("Disabled for oio-swift")
def test_history_delete_marker_no_object_success(self):
self.skipTest("Disabled for oio-swift")
def test_history_delete_marker_over_object_success(self):
self.skipTest("Disabled for oio-swift")
def test_delete_single_version_success(self):
self.skipTest("Disabled for oio-swift")
def test_DELETE_on_expired_versioned_object(self):
self.skipTest("Disabled for oio-swift")
def test_denied_DELETE_of_versioned_object(self):
self.skipTest("Disabled for oio-swift")
<|code_end|>
, generate the next line using the imports in this file:
import os.path
import sys
import test # noqa: E402, F401
from swift.common import swob
from swift.common.swob import Request
from oioswift.common.middleware import versioned_writes
from test.unit.common.middleware \
import test_versioned_writes as test_vw # noqa: E402
and context (functions, classes, or occasionally code) from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
# VERSIONING_SUFFIX = '+versioning'
# def swift3_versioned_object_name(object_name, version_id=None):
# def swift3_split_object_name_version(object_name):
# def get_unversioned_container(container):
# def is_deleted(obj):
# def handle_container_listing(self, env, start_response):
# def handle_container_request(self, env, start_response):
# def object_request(self, req, api_version, account, container, obj,
# allow_versioned_writes):
# def __call__(self, env, start_response):
# def filter_factory(global_conf, **local_conf):
# def obj_versions_filter(app):
# class OioVersionedWritesContext(vw.VersionedWritesContext):
# class OioVersionedWritesMiddleware(vw.VersionedWritesMiddleware):
. Output only the next line. | def test_list_no_versions_with_delimiter(self): |
Next line prediction: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
class Encrypter(OrigEncrypter):
def __call__(self, env, start_response):
if config_true_value(env.get('swift.crypto.override')):
return self.app(env, start_response)
req = Request(env)
if self.disable_encryption and req.method in ('PUT', 'POST'):
return self.app(env, start_response)
try:
req.split_path(4, 4, True)
except ValueError:
<|code_end|>
. Use current file imports:
(from swift.common.swob import HTTPException, Request
from swift.common.utils import config_true_value
from swift.common.middleware.crypto.crypto_utils import CRYPTO_KEY_CALLBACK
from swift.common.middleware.crypto.encrypter import Encrypter as OrigEncrypter
from oioswift.common.middleware.crypto.keymaster import MISSING_KEY_MSG)
and context including class names, function names, or small code snippets from other files:
# Path: oioswift/common/middleware/crypto/keymaster.py
# MISSING_KEY_MSG = 'Missing %s header' % crypto_utils.KEY_HEADER
. Output only the next line. | return self.app(env, start_response) |
Predict the next line for this snippet: <|code_start|> self.authorized.append(req)
if 'swift.authorize' not in req.environ:
req.environ['swift.authorize'] = authorize
req.headers.setdefault("User-Agent", "Melted Cheddar")
status = [None]
headers = [None]
def start_response(s, h, ei=None):
status[0] = s
headers[0] = h
body_iter = app(req.environ, start_response)
with utils.closing_if_possible(body_iter):
body = b''.join(body_iter)
return status[0], headers[0], body
def _check_conversion(self, path_in, path_out):
self.app.register('PUT', path_out, swob.HTTPCreated, {})
req = Request.blank(path_in, method='PUT')
resp = self.call_app(req, app=self.hc)
self.assertEqual(resp[0], "201 Created")
self.assertEqual(self.app.calls, [('PUT', path_out)])
def test_default_config(self):
self._check_conversion(
'/prefix/229/358493922_something',
<|code_end|>
with the help of current file imports:
import os.path
import sys
import unittest
from swift.common import swob, utils
from swift.common.swob import Request
from oioswift.common.middleware import hashedcontainer
from oio.cli.common import clientmanager
from test.unit.common.middleware.helpers import FakeSwift # noqa: E402
and context from other files:
# Path: oioswift/common/middleware/hashedcontainer.py
# class HashedContainerMiddleware(AutoContainerBase):
# BYPASS_QS = "bypass-autocontainer"
# BYPASS_HEADER = "X-bypass-autocontainer"
# TRUE_VALUES = ["true", "yes", "1"]
# EXTRA_KEYWORDS = ['offset', 'size', 'bits']
# def __init__(self, app, ns, acct, proxy=None,
# strip_v1=False, account_first=False,
# skip_metadata=False, **kwargs):
# def filter_factory(global_conf, **local_config):
# def factory(app):
, which may contain function names, class names, or code. Output only the next line. | '/v1/OPENIO/6C800/prefix/229/358493922_something') |
Predict the next line for this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
# Hack PYTHONPATH so "test" is swift's test directory
sys.path.insert(1, os.path.abspath(os.path.join(__file__,
'../../../../../..')))
class TestEncrypter(OrigTestEncrypter):
def setUp(self):
self.app = FakeSwift()
self.encrypter = encrypter.Encrypter(self.app, {})
self.encrypter.logger = FakeLogger()
def test_PUT_missing_key_in_header(self):
def raise_exc():
raise HTTPBadRequest(
<|code_end|>
with the help of current file imports:
import os
import sys
from swift.common.swob import HTTPBadRequest, HTTPCreated, Request
from swift.common.middleware.crypto.crypto_utils import CRYPTO_KEY_CALLBACK
from oioswift.common.middleware.crypto import encrypter
from test.unit import FakeLogger # noqa
from test.unit.common.middleware.helpers import FakeSwift # noqa
from test.unit.common.middleware.crypto.test_encrypter import \
TestEncrypter as OrigTestEncrypter # noqa
and context from other files:
# Path: oioswift/common/middleware/crypto/encrypter.py
# class Encrypter(OrigEncrypter):
# def __call__(self, env, start_response):
, which may contain function names, class names, or code. Output only the next line. | 'Missing X-Amz-Server-Side-Encryption-Customer-Key header') |
Given snippet: <|code_start|> self.assertEqual(resp[0], '200 OK')
def test_fallback_listing(self):
if self.filter_conf['stop_at_first_match'] == 'true':
self.skipTest("require openio-sds >= 4.2")
self.app.register('GET',
'/v1/a/11122249?prefix=/111/222/456/789/o',
swob.HTTPNotFound, {})
self.app.register('GET',
'/v1/a/11126?prefix=/111/222/456/789/o',
swob.HTTPOk, {})
req = Request.blank('/v1/a/c?prefix=/111/222/456/789/o', method='GET')
resp = self.call_rc(req)
self.assertEqual(resp[0], '200 OK')
self.assertEqual(
self.app.calls,
[('GET', '/v1/a/11122249?prefix=/111/222/456/789/o'),
('GET', '/v1/a/11126?prefix=/111/222/456/789/o')])
def test_swift3_mpu(self):
self.app.register('PUT',
'/v1/a/cloudff+segments/cloud/ff_object',
swob.HTTPOk, {})
req = Request.blank(
'/v1/a/c+segments/cloud/ff_object', method='PUT')
resp = self.call_rc(req)
self.assertEqual(resp[0], '200 OK')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os.path
import sys
import unittest
from swift.common import swob, utils
from swift.common.swob import Request
from oioswift.common.middleware import regexcontainer
from oio.common.autocontainer import ContainerBuilder
from test.unit.common.middleware.helpers import FakeSwift # noqa: E402
and context:
# Path: oioswift/common/middleware/regexcontainer.py
# class RegexContainerMiddleware(AutoContainerBase):
# BYPASS_QS = "bypass-autocontainer"
# BYPASS_HEADER = "X-bypass-autocontainer"
# def __init__(self, app, acct, patterns, failsafe=False,
# **kwargs):
# def _call(self, env, start_response):
# def filter_factory(global_conf, **local_config):
# def factory(app):
which might include code, classes, or functions. Output only the next line. | def test_copy(self): |
Continue the code snippet: <|code_start|># Copyright (c) 2015-2016 OpenStack Foundation
# Copyright (c) 2018 OpenIO SAS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
class TestModuleMethods(unittest.TestCase):
def test_decode_secret_too_long(self):
self.assertRaises(ValueError, crypto_utils.decode_secret, 'a' * 45)
def test_decode_secret_too_short(self):
self.assertRaises(ValueError, crypto_utils.decode_secret, 'a' * 4)
def test_decode_secret_not_base64(self):
self.assertRaises(ValueError, crypto_utils.decode_secret,
<|code_end|>
. Use current file imports:
import unittest
from oioswift.common.middleware.crypto import crypto_utils
and context (classes, functions, or code) from other files:
# Path: oioswift/common/middleware/crypto/crypto_utils.py
# ALGO_HEADER = 'X-Amz-Server-Side-Encryption-Customer-Algorithm'
# KEY_HEADER = 'X-Amz-Server-Side-Encryption-Customer-Key'
# KEY_MD5_HEADER = 'X-Amz-Server-Side-Encryption-Customer-Key-Md5'
# SRC_ALGO_HEADER = 'X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm'
# SRC_KEY_HEADER = 'X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key'
# SRC_KEY_MD5_HEADER = \
# 'X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5'
# ALGO_ENV_KEY = header_to_environ_key(ALGO_HEADER)
# KEY_ENV_KEY = header_to_environ_key(KEY_HEADER)
# KEY_MD5_ENV_KEY = header_to_environ_key(KEY_MD5_HEADER)
# SRC_ALGO_ENV_KEY = header_to_environ_key(SRC_ALGO_HEADER)
# SRC_KEY_ENV_KEY = header_to_environ_key(SRC_KEY_HEADER)
# SRC_KEY_MD5_ENV_KEY = header_to_environ_key(SRC_KEY_MD5_HEADER)
# def decode_secret(b64_secret):
. Output only the next line. | '-' + 'a' * 43) |
Given snippet: <|code_start|># implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
except ImportError:
# Before Queens
def get_response_headers(info):
resp_headers = {
'X-Account-Container-Count': info['containers'],
'X-Account-Object-Count': info['objects'],
'X-Account-Bytes-Used': info['bytes'],
'X-Timestamp': Timestamp(info['ctime']).normal,
}
for k, v in info['metadata'].iteritems():
if v != '':
resp_headers[k] = v
return resp_headers
def account_listing_bucket_response(account, req, response_content_type,
listing=None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
from xml.sax import saxutils
from swift.common.middleware.listing_formats import \
get_listing_content_type
from swift.common.request_helpers import get_listing_content_type
from swift.common.utils import public, Timestamp, json
from swift.common.constraints import check_metadata
from swift.common import constraints
from swift.common.swob import HTTPBadRequest, HTTPMethodNotAllowed
from swift.common.request_helpers import get_param, is_sys_or_user_meta
from swift.common.swob import HTTPNoContent, HTTPOk, HTTPPreconditionFailed, \
HTTPNotFound, HTTPCreated, HTTPAccepted
from swift.proxy.controllers.account import AccountController \
as SwiftAccountController
from swift.proxy.controllers.base import set_info_cache, clear_info_cache
from oio.common import exceptions
from oioswift.utils import handle_oio_timeout, handle_service_busy, \
REQID_HEADER
and context:
# Path: oioswift/utils.py
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
which might include code, classes, or functions. Output only the next line. | if response_content_type != 'application/json': |
Predict the next line for this snippet: <|code_start|> elif response_content_type.endswith('/xml'):
output_list = ['<?xml version="1.0" encoding="UTF-8"?>',
'<account name=%s>' % saxutils.quoteattr(account)]
for (name, object_count, bytes_used, is_subdir, mtime) in listing:
if is_subdir:
if not s3_buckets_only:
output_list.append(
'<subdir name=%s />' % saxutils.quoteattr(name))
else:
item = '<container><name>%s</name><count>%s</count>' \
'<bytes>%s</bytes><last_modified>%s</last_modified>' \
'</container>' % \
(saxutils.escape(name), object_count, bytes_used,
Timestamp(mtime).isoformat)
output_list.append(item)
output_list.append('</account>')
account_list = '\n'.join(output_list)
else:
if not listing:
resp = HTTPNoContent(request=req, headers=resp_headers)
resp.content_type = response_content_type
resp.charset = 'utf-8'
return resp
account_list = '\n'.join(r[0] for r in listing) + '\n'
ret = HTTPOk(body=account_list, request=req, headers=resp_headers)
ret.content_type = response_content_type
ret.charset = 'utf-8'
return ret
<|code_end|>
with the help of current file imports:
import time
from xml.sax import saxutils
from swift.common.middleware.listing_formats import \
get_listing_content_type
from swift.common.request_helpers import get_listing_content_type
from swift.common.utils import public, Timestamp, json
from swift.common.constraints import check_metadata
from swift.common import constraints
from swift.common.swob import HTTPBadRequest, HTTPMethodNotAllowed
from swift.common.request_helpers import get_param, is_sys_or_user_meta
from swift.common.swob import HTTPNoContent, HTTPOk, HTTPPreconditionFailed, \
HTTPNotFound, HTTPCreated, HTTPAccepted
from swift.proxy.controllers.account import AccountController \
as SwiftAccountController
from swift.proxy.controllers.base import set_info_cache, clear_info_cache
from oio.common import exceptions
from oioswift.utils import handle_oio_timeout, handle_service_busy, \
REQID_HEADER
and context from other files:
# Path: oioswift/utils.py
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
, which may contain function names, class names, or code. Output only the next line. | def handle_account_not_found_autocreate(fnc): |
Predict the next line for this snippet: <|code_start|> if response_content_type == 'application/json':
data = []
for (name, object_count, bytes_used, is_subdir, mtime) in listing:
if is_subdir:
if not s3_buckets_only:
data.append({'subdir': name})
else:
data.append({'name': name, 'count': object_count,
'bytes': bytes_used,
'last_modified': Timestamp(mtime).isoformat})
account_list = json.dumps(data)
elif response_content_type.endswith('/xml'):
output_list = ['<?xml version="1.0" encoding="UTF-8"?>',
'<account name=%s>' % saxutils.quoteattr(account)]
for (name, object_count, bytes_used, is_subdir, mtime) in listing:
if is_subdir:
if not s3_buckets_only:
output_list.append(
'<subdir name=%s />' % saxutils.quoteattr(name))
else:
item = '<container><name>%s</name><count>%s</count>' \
'<bytes>%s</bytes><last_modified>%s</last_modified>' \
'</container>' % \
(saxutils.escape(name), object_count, bytes_used,
Timestamp(mtime).isoformat)
output_list.append(item)
output_list.append('</account>')
account_list = '\n'.join(output_list)
else:
if not listing:
<|code_end|>
with the help of current file imports:
import time
from xml.sax import saxutils
from swift.common.middleware.listing_formats import \
get_listing_content_type
from swift.common.request_helpers import get_listing_content_type
from swift.common.utils import public, Timestamp, json
from swift.common.constraints import check_metadata
from swift.common import constraints
from swift.common.swob import HTTPBadRequest, HTTPMethodNotAllowed
from swift.common.request_helpers import get_param, is_sys_or_user_meta
from swift.common.swob import HTTPNoContent, HTTPOk, HTTPPreconditionFailed, \
HTTPNotFound, HTTPCreated, HTTPAccepted
from swift.proxy.controllers.account import AccountController \
as SwiftAccountController
from swift.proxy.controllers.base import set_info_cache, clear_info_cache
from oio.common import exceptions
from oioswift.utils import handle_oio_timeout, handle_service_busy, \
REQID_HEADER
and context from other files:
# Path: oioswift/utils.py
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
, which may contain function names, class names, or code. Output only the next line. | resp = HTTPNoContent(request=req, headers=resp_headers) |
Given the following code snippet before the placeholder: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
# supported only by 4.6.0
SUPPORT_VERSIONING = True
except ImportError:
SUPPORT_VERSIONING = False
SLO = 'x-static-large-object'
BUCKET_NAME_HEADER = 'X-Object-Sysmeta-Oio-Bucket-Name'
class ObjectControllerRouter(object):
def __getitem__(self, policy):
return ObjectController
<|code_end|>
, predict the next line using imports from the current file:
import json
import mimetypes
import time
import math
from swift import gettext_ as _
from swift.common.utils import (
clean_content_type, config_true_value, Timestamp, public,
close_if_possible, closing_if_possible)
from swift.common.constraints import check_metadata, check_object_creation
from swift.common.header_key_dict import HeaderKeyDict
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import HTTPAccepted, HTTPBadRequest, HTTPNotFound, \
HTTPConflict, HTTPPreconditionFailed, HTTPRequestTimeout, \
HTTPUnprocessableEntity, HTTPClientDisconnect, HTTPCreated, \
HTTPNoContent, Response, HTTPInternalServerError, multi_range_iterator, \
HTTPServiceUnavailable
from swift.common.request_helpers import is_sys_or_user_meta, \
is_object_transient_sysmeta, resolve_etag_is_at_header
from swift.common.wsgi import make_subrequest
from swift.proxy.controllers.base import set_object_info_cache, \
delay_denial, cors_validation, get_object_info
from swift.proxy.controllers.obj import check_content_type
from swift.proxy.controllers.obj import BaseObjectController as \
BaseObjectController
from oio.common import exceptions
from oio.common.constants import FORCEVERSIONING_HEADER
from oio.common.http import ranges_from_http_header
from oio.common.storage_method import STORAGE_METHODS
from oio.api.object_storage import _sort_chunks
from oio.common.exceptions import SourceReadTimeout
from oioswift.utils import check_if_none_match, \
handle_not_allowed, handle_oio_timeout, handle_service_busy, \
REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context including class names, function names, and sometimes code from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def check_if_none_match(fnc):
# """Check if object exists, and if etag matches."""
# @wraps(fnc)
# def _if_none_match_wrapper(self, req, *args, **kwargs):
# if req.if_none_match is None:
# return fnc(self, req, *args, **kwargs)
# oio_headers = {REQID_HEADER: self.trans_id}
# try:
# metadata = self.app.storage.object_get_properties(
# self.account_name, self.container_name, self.object_name,
# version=req.environ.get('oio.query', {}).get('version'),
# headers=oio_headers)
# except (NoSuchObject, NoSuchContainer):
# return fnc(self, req, *args, **kwargs)
# # req.if_none_match will check for '*'.
# if metadata.get('hash') in req.if_none_match:
# if req.method in ('HEAD', 'GET'):
# raise HTTPNotModified(request=req)
# else:
# raise HTTPPreconditionFailed(request=req)
# return fnc(self, req, *args, **kwargs)
# return _if_none_match_wrapper
#
# def handle_not_allowed(fnc):
# """Handle MethodNotAllowed ('405 Method not allowed') errors."""
# @wraps(fnc)
# def _not_allowed_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except MethodNotAllowed as exc:
# headers = dict()
# if 'worm' in exc.message.lower():
# headers['Allow'] = 'GET, HEAD, PUT'
# else:
# # TODO(FVE): load Allow header from exception attributes
# pass
# return HTTPMethodNotAllowed(request=req, headers=headers)
# return _not_allowed_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | class StreamRangeIterator(object): |
Given the code snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
# supported only by 4.6.0
SUPPORT_VERSIONING = True
except ImportError:
SUPPORT_VERSIONING = False
SLO = 'x-static-large-object'
BUCKET_NAME_HEADER = 'X-Object-Sysmeta-Oio-Bucket-Name'
class ObjectControllerRouter(object):
def __getitem__(self, policy):
return ObjectController
<|code_end|>
, generate the next line using the imports in this file:
import json
import mimetypes
import time
import math
from swift import gettext_ as _
from swift.common.utils import (
clean_content_type, config_true_value, Timestamp, public,
close_if_possible, closing_if_possible)
from swift.common.constraints import check_metadata, check_object_creation
from swift.common.header_key_dict import HeaderKeyDict
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import HTTPAccepted, HTTPBadRequest, HTTPNotFound, \
HTTPConflict, HTTPPreconditionFailed, HTTPRequestTimeout, \
HTTPUnprocessableEntity, HTTPClientDisconnect, HTTPCreated, \
HTTPNoContent, Response, HTTPInternalServerError, multi_range_iterator, \
HTTPServiceUnavailable
from swift.common.request_helpers import is_sys_or_user_meta, \
is_object_transient_sysmeta, resolve_etag_is_at_header
from swift.common.wsgi import make_subrequest
from swift.proxy.controllers.base import set_object_info_cache, \
delay_denial, cors_validation, get_object_info
from swift.proxy.controllers.obj import check_content_type
from swift.proxy.controllers.obj import BaseObjectController as \
BaseObjectController
from oio.common import exceptions
from oio.common.constants import FORCEVERSIONING_HEADER
from oio.common.http import ranges_from_http_header
from oio.common.storage_method import STORAGE_METHODS
from oio.api.object_storage import _sort_chunks
from oio.common.exceptions import SourceReadTimeout
from oioswift.utils import check_if_none_match, \
handle_not_allowed, handle_oio_timeout, handle_service_busy, \
REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context (functions, classes, or occasionally code) from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def check_if_none_match(fnc):
# """Check if object exists, and if etag matches."""
# @wraps(fnc)
# def _if_none_match_wrapper(self, req, *args, **kwargs):
# if req.if_none_match is None:
# return fnc(self, req, *args, **kwargs)
# oio_headers = {REQID_HEADER: self.trans_id}
# try:
# metadata = self.app.storage.object_get_properties(
# self.account_name, self.container_name, self.object_name,
# version=req.environ.get('oio.query', {}).get('version'),
# headers=oio_headers)
# except (NoSuchObject, NoSuchContainer):
# return fnc(self, req, *args, **kwargs)
# # req.if_none_match will check for '*'.
# if metadata.get('hash') in req.if_none_match:
# if req.method in ('HEAD', 'GET'):
# raise HTTPNotModified(request=req)
# else:
# raise HTTPPreconditionFailed(request=req)
# return fnc(self, req, *args, **kwargs)
# return _if_none_match_wrapper
#
# def handle_not_allowed(fnc):
# """Handle MethodNotAllowed ('405 Method not allowed') errors."""
# @wraps(fnc)
# def _not_allowed_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except MethodNotAllowed as exc:
# headers = dict()
# if 'worm' in exc.message.lower():
# headers['Allow'] = 'GET, HEAD, PUT'
# else:
# # TODO(FVE): load Allow header from exception attributes
# pass
# return HTTPMethodNotAllowed(request=req, headers=headers)
# return _not_allowed_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | class StreamRangeIterator(object): |
Continue the code snippet: <|code_start|># Copyright (c) 2010-2012 OpenStack Foundation
# Copyright (c) 2016-2020 OpenIO SAS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
try:
# supported only by 4.6.0
SUPPORT_VERSIONING = True
except ImportError:
<|code_end|>
. Use current file imports:
import json
import mimetypes
import time
import math
from swift import gettext_ as _
from swift.common.utils import (
clean_content_type, config_true_value, Timestamp, public,
close_if_possible, closing_if_possible)
from swift.common.constraints import check_metadata, check_object_creation
from swift.common.header_key_dict import HeaderKeyDict
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import HTTPAccepted, HTTPBadRequest, HTTPNotFound, \
HTTPConflict, HTTPPreconditionFailed, HTTPRequestTimeout, \
HTTPUnprocessableEntity, HTTPClientDisconnect, HTTPCreated, \
HTTPNoContent, Response, HTTPInternalServerError, multi_range_iterator, \
HTTPServiceUnavailable
from swift.common.request_helpers import is_sys_or_user_meta, \
is_object_transient_sysmeta, resolve_etag_is_at_header
from swift.common.wsgi import make_subrequest
from swift.proxy.controllers.base import set_object_info_cache, \
delay_denial, cors_validation, get_object_info
from swift.proxy.controllers.obj import check_content_type
from swift.proxy.controllers.obj import BaseObjectController as \
BaseObjectController
from oio.common import exceptions
from oio.common.constants import FORCEVERSIONING_HEADER
from oio.common.http import ranges_from_http_header
from oio.common.storage_method import STORAGE_METHODS
from oio.api.object_storage import _sort_chunks
from oio.common.exceptions import SourceReadTimeout
from oioswift.utils import check_if_none_match, \
handle_not_allowed, handle_oio_timeout, handle_service_busy, \
REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context (classes, functions, or code) from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def check_if_none_match(fnc):
# """Check if object exists, and if etag matches."""
# @wraps(fnc)
# def _if_none_match_wrapper(self, req, *args, **kwargs):
# if req.if_none_match is None:
# return fnc(self, req, *args, **kwargs)
# oio_headers = {REQID_HEADER: self.trans_id}
# try:
# metadata = self.app.storage.object_get_properties(
# self.account_name, self.container_name, self.object_name,
# version=req.environ.get('oio.query', {}).get('version'),
# headers=oio_headers)
# except (NoSuchObject, NoSuchContainer):
# return fnc(self, req, *args, **kwargs)
# # req.if_none_match will check for '*'.
# if metadata.get('hash') in req.if_none_match:
# if req.method in ('HEAD', 'GET'):
# raise HTTPNotModified(request=req)
# else:
# raise HTTPPreconditionFailed(request=req)
# return fnc(self, req, *args, **kwargs)
# return _if_none_match_wrapper
#
# def handle_not_allowed(fnc):
# """Handle MethodNotAllowed ('405 Method not allowed') errors."""
# @wraps(fnc)
# def _not_allowed_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except MethodNotAllowed as exc:
# headers = dict()
# if 'worm' in exc.message.lower():
# headers['Allow'] = 'GET, HEAD, PUT'
# else:
# # TODO(FVE): load Allow header from exception attributes
# pass
# return HTTPMethodNotAllowed(request=req, headers=headers)
# return _not_allowed_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | SUPPORT_VERSIONING = False |
Based on the snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
# supported only by 4.6.0
SUPPORT_VERSIONING = True
except ImportError:
SUPPORT_VERSIONING = False
SLO = 'x-static-large-object'
BUCKET_NAME_HEADER = 'X-Object-Sysmeta-Oio-Bucket-Name'
class ObjectControllerRouter(object):
def __getitem__(self, policy):
return ObjectController
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import mimetypes
import time
import math
from swift import gettext_ as _
from swift.common.utils import (
clean_content_type, config_true_value, Timestamp, public,
close_if_possible, closing_if_possible)
from swift.common.constraints import check_metadata, check_object_creation
from swift.common.header_key_dict import HeaderKeyDict
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import HTTPAccepted, HTTPBadRequest, HTTPNotFound, \
HTTPConflict, HTTPPreconditionFailed, HTTPRequestTimeout, \
HTTPUnprocessableEntity, HTTPClientDisconnect, HTTPCreated, \
HTTPNoContent, Response, HTTPInternalServerError, multi_range_iterator, \
HTTPServiceUnavailable
from swift.common.request_helpers import is_sys_or_user_meta, \
is_object_transient_sysmeta, resolve_etag_is_at_header
from swift.common.wsgi import make_subrequest
from swift.proxy.controllers.base import set_object_info_cache, \
delay_denial, cors_validation, get_object_info
from swift.proxy.controllers.obj import check_content_type
from swift.proxy.controllers.obj import BaseObjectController as \
BaseObjectController
from oio.common import exceptions
from oio.common.constants import FORCEVERSIONING_HEADER
from oio.common.http import ranges_from_http_header
from oio.common.storage_method import STORAGE_METHODS
from oio.api.object_storage import _sort_chunks
from oio.common.exceptions import SourceReadTimeout
from oioswift.utils import check_if_none_match, \
handle_not_allowed, handle_oio_timeout, handle_service_busy, \
REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context (classes, functions, sometimes code) from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def check_if_none_match(fnc):
# """Check if object exists, and if etag matches."""
# @wraps(fnc)
# def _if_none_match_wrapper(self, req, *args, **kwargs):
# if req.if_none_match is None:
# return fnc(self, req, *args, **kwargs)
# oio_headers = {REQID_HEADER: self.trans_id}
# try:
# metadata = self.app.storage.object_get_properties(
# self.account_name, self.container_name, self.object_name,
# version=req.environ.get('oio.query', {}).get('version'),
# headers=oio_headers)
# except (NoSuchObject, NoSuchContainer):
# return fnc(self, req, *args, **kwargs)
# # req.if_none_match will check for '*'.
# if metadata.get('hash') in req.if_none_match:
# if req.method in ('HEAD', 'GET'):
# raise HTTPNotModified(request=req)
# else:
# raise HTTPPreconditionFailed(request=req)
# return fnc(self, req, *args, **kwargs)
# return _if_none_match_wrapper
#
# def handle_not_allowed(fnc):
# """Handle MethodNotAllowed ('405 Method not allowed') errors."""
# @wraps(fnc)
# def _not_allowed_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except MethodNotAllowed as exc:
# headers = dict()
# if 'worm' in exc.message.lower():
# headers['Allow'] = 'GET, HEAD, PUT'
# else:
# # TODO(FVE): load Allow header from exception attributes
# pass
# return HTTPMethodNotAllowed(request=req, headers=headers)
# return _not_allowed_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | class StreamRangeIterator(object): |
Here is a snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
try:
# supported only by 4.6.0
SUPPORT_VERSIONING = True
except ImportError:
SUPPORT_VERSIONING = False
SLO = 'x-static-large-object'
BUCKET_NAME_HEADER = 'X-Object-Sysmeta-Oio-Bucket-Name'
class ObjectControllerRouter(object):
def __getitem__(self, policy):
<|code_end|>
. Write the next line using the current file imports:
import json
import mimetypes
import time
import math
from swift import gettext_ as _
from swift.common.utils import (
clean_content_type, config_true_value, Timestamp, public,
close_if_possible, closing_if_possible)
from swift.common.constraints import check_metadata, check_object_creation
from swift.common.header_key_dict import HeaderKeyDict
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import HTTPAccepted, HTTPBadRequest, HTTPNotFound, \
HTTPConflict, HTTPPreconditionFailed, HTTPRequestTimeout, \
HTTPUnprocessableEntity, HTTPClientDisconnect, HTTPCreated, \
HTTPNoContent, Response, HTTPInternalServerError, multi_range_iterator, \
HTTPServiceUnavailable
from swift.common.request_helpers import is_sys_or_user_meta, \
is_object_transient_sysmeta, resolve_etag_is_at_header
from swift.common.wsgi import make_subrequest
from swift.proxy.controllers.base import set_object_info_cache, \
delay_denial, cors_validation, get_object_info
from swift.proxy.controllers.obj import check_content_type
from swift.proxy.controllers.obj import BaseObjectController as \
BaseObjectController
from oio.common import exceptions
from oio.common.constants import FORCEVERSIONING_HEADER
from oio.common.http import ranges_from_http_header
from oio.common.storage_method import STORAGE_METHODS
from oio.api.object_storage import _sort_chunks
from oio.common.exceptions import SourceReadTimeout
from oioswift.utils import check_if_none_match, \
handle_not_allowed, handle_oio_timeout, handle_service_busy, \
REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def check_if_none_match(fnc):
# """Check if object exists, and if etag matches."""
# @wraps(fnc)
# def _if_none_match_wrapper(self, req, *args, **kwargs):
# if req.if_none_match is None:
# return fnc(self, req, *args, **kwargs)
# oio_headers = {REQID_HEADER: self.trans_id}
# try:
# metadata = self.app.storage.object_get_properties(
# self.account_name, self.container_name, self.object_name,
# version=req.environ.get('oio.query', {}).get('version'),
# headers=oio_headers)
# except (NoSuchObject, NoSuchContainer):
# return fnc(self, req, *args, **kwargs)
# # req.if_none_match will check for '*'.
# if metadata.get('hash') in req.if_none_match:
# if req.method in ('HEAD', 'GET'):
# raise HTTPNotModified(request=req)
# else:
# raise HTTPPreconditionFailed(request=req)
# return fnc(self, req, *args, **kwargs)
# return _if_none_match_wrapper
#
# def handle_not_allowed(fnc):
# """Handle MethodNotAllowed ('405 Method not allowed') errors."""
# @wraps(fnc)
# def _not_allowed_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except MethodNotAllowed as exc:
# headers = dict()
# if 'worm' in exc.message.lower():
# headers['Allow'] = 'GET, HEAD, PUT'
# else:
# # TODO(FVE): load Allow header from exception attributes
# pass
# return HTTPMethodNotAllowed(request=req, headers=headers)
# return _not_allowed_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
, which may include functions, classes, or code. Output only the next line. | return ObjectController |
Given the code snippet: <|code_start|># Copyright (c) 2010-2012 OpenStack Foundation
# Copyright (c) 2016-2020 OpenIO SAS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
try:
# supported only by 4.6.0
SUPPORT_VERSIONING = True
except ImportError:
<|code_end|>
, generate the next line using the imports in this file:
import json
import mimetypes
import time
import math
from swift import gettext_ as _
from swift.common.utils import (
clean_content_type, config_true_value, Timestamp, public,
close_if_possible, closing_if_possible)
from swift.common.constraints import check_metadata, check_object_creation
from swift.common.header_key_dict import HeaderKeyDict
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import HTTPAccepted, HTTPBadRequest, HTTPNotFound, \
HTTPConflict, HTTPPreconditionFailed, HTTPRequestTimeout, \
HTTPUnprocessableEntity, HTTPClientDisconnect, HTTPCreated, \
HTTPNoContent, Response, HTTPInternalServerError, multi_range_iterator, \
HTTPServiceUnavailable
from swift.common.request_helpers import is_sys_or_user_meta, \
is_object_transient_sysmeta, resolve_etag_is_at_header
from swift.common.wsgi import make_subrequest
from swift.proxy.controllers.base import set_object_info_cache, \
delay_denial, cors_validation, get_object_info
from swift.proxy.controllers.obj import check_content_type
from swift.proxy.controllers.obj import BaseObjectController as \
BaseObjectController
from oio.common import exceptions
from oio.common.constants import FORCEVERSIONING_HEADER
from oio.common.http import ranges_from_http_header
from oio.common.storage_method import STORAGE_METHODS
from oio.api.object_storage import _sort_chunks
from oio.common.exceptions import SourceReadTimeout
from oioswift.utils import check_if_none_match, \
handle_not_allowed, handle_oio_timeout, handle_service_busy, \
REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context (functions, classes, or occasionally code) from other files:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def check_if_none_match(fnc):
# """Check if object exists, and if etag matches."""
# @wraps(fnc)
# def _if_none_match_wrapper(self, req, *args, **kwargs):
# if req.if_none_match is None:
# return fnc(self, req, *args, **kwargs)
# oio_headers = {REQID_HEADER: self.trans_id}
# try:
# metadata = self.app.storage.object_get_properties(
# self.account_name, self.container_name, self.object_name,
# version=req.environ.get('oio.query', {}).get('version'),
# headers=oio_headers)
# except (NoSuchObject, NoSuchContainer):
# return fnc(self, req, *args, **kwargs)
# # req.if_none_match will check for '*'.
# if metadata.get('hash') in req.if_none_match:
# if req.method in ('HEAD', 'GET'):
# raise HTTPNotModified(request=req)
# else:
# raise HTTPPreconditionFailed(request=req)
# return fnc(self, req, *args, **kwargs)
# return _if_none_match_wrapper
#
# def handle_not_allowed(fnc):
# """Handle MethodNotAllowed ('405 Method not allowed') errors."""
# @wraps(fnc)
# def _not_allowed_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except MethodNotAllowed as exc:
# headers = dict()
# if 'worm' in exc.message.lower():
# headers['Allow'] = 'GET, HEAD, PUT'
# else:
# # TODO(FVE): load Allow header from exception attributes
# pass
# return HTTPMethodNotAllowed(request=req, headers=headers)
# return _not_allowed_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
. Output only the next line. | SUPPORT_VERSIONING = False |
Given snippet: <|code_start|># Copyright (c) 2010-2012 OpenStack Foundation
# Copyright (c) 2016-2020 OpenIO SAS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 License.
try:
# supported only by 4.6.0
SUPPORT_VERSIONING = True
except ImportError:
SUPPORT_VERSIONING = False
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import mimetypes
import time
import math
from swift import gettext_ as _
from swift.common.utils import (
clean_content_type, config_true_value, Timestamp, public,
close_if_possible, closing_if_possible)
from swift.common.constraints import check_metadata, check_object_creation
from swift.common.header_key_dict import HeaderKeyDict
from oioswift.common.middleware.versioned_writes import \
DELETE_MARKER_CONTENT_TYPE
from swift.common.swob import HTTPAccepted, HTTPBadRequest, HTTPNotFound, \
HTTPConflict, HTTPPreconditionFailed, HTTPRequestTimeout, \
HTTPUnprocessableEntity, HTTPClientDisconnect, HTTPCreated, \
HTTPNoContent, Response, HTTPInternalServerError, multi_range_iterator, \
HTTPServiceUnavailable
from swift.common.request_helpers import is_sys_or_user_meta, \
is_object_transient_sysmeta, resolve_etag_is_at_header
from swift.common.wsgi import make_subrequest
from swift.proxy.controllers.base import set_object_info_cache, \
delay_denial, cors_validation, get_object_info
from swift.proxy.controllers.obj import check_content_type
from swift.proxy.controllers.obj import BaseObjectController as \
BaseObjectController
from oio.common import exceptions
from oio.common.constants import FORCEVERSIONING_HEADER
from oio.common.http import ranges_from_http_header
from oio.common.storage_method import STORAGE_METHODS
from oio.api.object_storage import _sort_chunks
from oio.common.exceptions import SourceReadTimeout
from oioswift.utils import check_if_none_match, \
handle_not_allowed, handle_oio_timeout, handle_service_busy, \
REQID_HEADER, BUCKET_NAME_PROP, MULTIUPLOAD_SUFFIX
and context:
# Path: oioswift/common/middleware/versioned_writes.py
# DELETE_MARKER_CONTENT_TYPE = vw.DELETE_MARKER_CONTENT_TYPE
#
# Path: oioswift/utils.py
# def check_if_none_match(fnc):
# """Check if object exists, and if etag matches."""
# @wraps(fnc)
# def _if_none_match_wrapper(self, req, *args, **kwargs):
# if req.if_none_match is None:
# return fnc(self, req, *args, **kwargs)
# oio_headers = {REQID_HEADER: self.trans_id}
# try:
# metadata = self.app.storage.object_get_properties(
# self.account_name, self.container_name, self.object_name,
# version=req.environ.get('oio.query', {}).get('version'),
# headers=oio_headers)
# except (NoSuchObject, NoSuchContainer):
# return fnc(self, req, *args, **kwargs)
# # req.if_none_match will check for '*'.
# if metadata.get('hash') in req.if_none_match:
# if req.method in ('HEAD', 'GET'):
# raise HTTPNotModified(request=req)
# else:
# raise HTTPPreconditionFailed(request=req)
# return fnc(self, req, *args, **kwargs)
# return _if_none_match_wrapper
#
# def handle_not_allowed(fnc):
# """Handle MethodNotAllowed ('405 Method not allowed') errors."""
# @wraps(fnc)
# def _not_allowed_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except MethodNotAllowed as exc:
# headers = dict()
# if 'worm' in exc.message.lower():
# headers['Allow'] = 'GET, HEAD, PUT'
# else:
# # TODO(FVE): load Allow header from exception attributes
# pass
# return HTTPMethodNotAllowed(request=req, headers=headers)
# return _not_allowed_wrapper
#
# def handle_oio_timeout(fnc):
# """
# Catch DeadlineReached and OioTimeout errors
# and return '503 Service Unavailable'.
# """
# @wraps(fnc)
# def _oio_timeout_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (DeadlineReached, OioTimeout) as exc:
# headers = dict()
# # TODO(FVE): choose the value according to the timeout
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=str(exc))
# return _oio_timeout_wrapper
#
# def handle_service_busy(fnc):
# @wraps(fnc)
# def _service_busy_wrapper(self, req, *args, **kwargs):
# try:
# return fnc(self, req, *args, **kwargs)
# except (ServiceBusy, ServiceUnavailable) as err:
# headers = dict()
# headers['Retry-After'] = '1'
# return HTTPServiceUnavailable(request=req, headers=headers,
# body=err.message)
# return _service_busy_wrapper
#
# REQID_HEADER = 'x-oio-req-id'
#
# BUCKET_NAME_PROP = "sys.m2.bucket.name"
#
# MULTIUPLOAD_SUFFIX = '+segments'
which might include code, classes, or functions. Output only the next line. | SLO = 'x-static-large-object' |
Predict the next line for this snippet: <|code_start|> return '.'.join(parts)
def _make_cookie_domain(domain):
if domain is None:
return None
domain = _encode_idna(domain)
if b':' in domain:
domain = domain.split(b':', 1)[0]
if b'.' in domain:
return domain
raise ValueError(
'Setting \'domain\' for a cookie on a server running localy (ex: '
'localhost) is not supportted by complying browsers. You should '
'have something like: \'127.0.0.1 localhost dev.localhost\' on '
'your hosts file and then point your server to run on '
'\'dev.localhost\' and also set \'domain\' for \'dev.localhost\''
)
def _easteregg(app=None):
"""Like the name says. But who knows how it works?"""
def bzzzzzzz(gyver):
return zlib.decompress(base64.b64decode(gyver)).decode('ascii')
gyver = u'\n'.join([x + (77 - len(x)) * u' ' for x in bzzzzzzz(b'''
eJyFlzuOJDkMRP06xRjymKgDJCDQStBYT8BCgK4gTwfQ2fcFs2a2FzvZk+hvlcRvRJD148efHt9m
9Xz94dRY5hGt1nrYcXx7us9qlcP9HHNh28rz8dZj+q4rynVFFPdlY4zH873NKCexrDM6zxxRymzz
4QIxzK4bth1PV7+uHn6WXZ5C4ka/+prFzx3zWLMHAVZb8RRUxtFXI5DTQ2n3Hi2sNI+HK43AOWSY
jmEzE4naFp58PdzhPMdslLVWHTGUVpSxImw+pS/D+JhzLfdS1j7PzUMxij+mc2U0I9zcbZ/HcZxc
q1QjvvcThMYFnp93agEx392ZdLJWXbi/Ca4Oivl4h/Y1ErEqP+lrg7Xa4qnUKu5UE9UUA4xeqLJ5
<|code_end|>
with the help of current file imports:
import re
import string
import inspect
import logging
import base64
import zlib
from weakref import WeakKeyDictionary
from datetime import datetime, date
from itertools import chain
from werkzeug._compat import iter_bytes, text_type, BytesIO, int_to_byte, \
range_type, to_native
and context from other files:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
, which may contain function names, class names, or code. Output only the next line. | jWlPKJvR2yhRI7xFPdzPuc6adXu6ovwXwRPXXnZHxlPtkSkqWHilsOrGrvcVWXgGP3daXomCj317 |
Given the code snippet: <|code_start|>
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
:param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given as
unicode string.
"""
scheme, netloc, path, qs, anchor = url_parse(to_unicode(s, charset, 'replace'))
path = url_quote(path, charset, safe='/%+$!*\'(),')
qs = url_quote_plus(qs, charset, safe=':&%=+$!*\'(),')
return to_native(url_unparse((scheme, netloc, path, qs, anchor)))
def uri_to_iri(uri, charset='utf-8', errors='replace'):
r"""
Converts a URI in a given charset to a IRI.
Examples for URI versus IRI:
>>> uri_to_iri(b'http://xn--n3h.net/')
u'http://\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
<|code_end|>
, generate the next line using the imports in this file:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context (functions, classes, or occasionally code) from other files:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
. Output only the next line. | u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th' |
Here is a snippet: <|code_start|> :license: BSD, see LICENSE for more details.
"""
# A regular expression for what a valid schema looks like
_scheme_re = re.compile(r'^[a-zA-Z0-9+-.]+$')
# Characters that are safe in any part of an URL.
_always_safe = (b'abcdefghijklmnopqrstuvwxyz'
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-+')
_hexdigits = '0123456789ABCDEFabcdef'
_hextobyte = dict(
((a + b).encode(), int(a + b, 16))
for a in _hexdigits for b in _hexdigits
)
_URLTuple = fix_tuple_repr(namedtuple('_URLTuple',
['scheme', 'netloc', 'path', 'query', 'fragment']))
class _URLMixin(object):
__slots__ = ()
def replace(self, **kwargs):
"""Return an URL with the same values, except for those parameters
given new values by whichever keyword arguments are specified."""
return self._replace(**kwargs)
<|code_end|>
. Write the next line using the current file imports:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context from other files:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
, which may include functions, classes, or code. Output only the next line. | @property |
Using the snippet: <|code_start|> u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
Query strings are left unchanged:
>>> uri_to_iri('/?foo=24&x=%26%2f')
u'/?foo=24&x=%26%2f'
.. versionadded:: 0.6
:param uri: The URI to convert.
:param charset: The charset of the URI.
:param errors: The error handling on decode.
"""
if isinstance(uri, tuple):
uri = url_unparse(uri)
uri = url_parse(to_unicode(uri, charset))
path = url_unquote(uri.path, charset, errors, '/;?')
query = url_unquote(uri.query, charset, errors, ';/?:@&=+,$')
fragment = url_unquote(uri.fragment, charset, errors, ';/?:@&=+,$')
return url_unparse((uri.scheme, uri.decode_netloc(),
path, query, fragment))
def iri_to_uri(iri, charset='utf-8', errors='strict'):
r"""
Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always
uses utf-8 URLs internally because this is what browsers and HTTP do as
well. In some places where it accepts an URL it also accepts a unicode IRI
and converts it into a URI.
<|code_end|>
, determine the next line of code. You have imports:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context (class names, function names, or code) available:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
. Output only the next line. | Examples for IRI versus URI: |
Given snippet: <|code_start|> :param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given as
unicode string.
"""
scheme, netloc, path, qs, anchor = url_parse(to_unicode(s, charset, 'replace'))
path = url_quote(path, charset, safe='/%+$!*\'(),')
qs = url_quote_plus(qs, charset, safe=':&%=+$!*\'(),')
return to_native(url_unparse((scheme, netloc, path, qs, anchor)))
def uri_to_iri(uri, charset='utf-8', errors='replace'):
r"""
Converts a URI in a given charset to a IRI.
Examples for URI versus IRI:
>>> uri_to_iri(b'http://xn--n3h.net/')
u'http://\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
Query strings are left unchanged:
>>> uri_to_iri('/?foo=24&x=%26%2f')
u'/?foo=24&x=%26%2f'
.. versionadded:: 0.6
:param uri: The URI to convert.
:param charset: The charset of the URI.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
which might include code, classes, or functions. Output only the next line. | :param errors: The error handling on decode. |
Given snippet: <|code_start|> .. versionadded:: 0.6
:param uri: The URI to convert.
:param charset: The charset of the URI.
:param errors: The error handling on decode.
"""
if isinstance(uri, tuple):
uri = url_unparse(uri)
uri = url_parse(to_unicode(uri, charset))
path = url_unquote(uri.path, charset, errors, '/;?')
query = url_unquote(uri.query, charset, errors, ';/?:@&=+,$')
fragment = url_unquote(uri.fragment, charset, errors, ';/?:@&=+,$')
return url_unparse((uri.scheme, uri.decode_netloc(),
path, query, fragment))
def iri_to_uri(iri, charset='utf-8', errors='strict'):
r"""
Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always
uses utf-8 URLs internally because this is what browsers and HTTP do as
well. In some places where it accepts an URL it also accepts a unicode IRI
and converts it into a URI.
Examples for IRI versus URI:
>>> iri_to_uri(u'http://☃.net/')
'http://xn--n3h.net/'
>>> iri_to_uri(u'http://üser:pässword@☃.net/påth')
'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
which might include code, classes, or functions. Output only the next line. | .. versionadded:: 0.6 |
Predict the next line after this snippet: <|code_start|> u'http://\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
Query strings are left unchanged:
>>> uri_to_iri('/?foo=24&x=%26%2f')
u'/?foo=24&x=%26%2f'
.. versionadded:: 0.6
:param uri: The URI to convert.
:param charset: The charset of the URI.
:param errors: The error handling on decode.
"""
if isinstance(uri, tuple):
uri = url_unparse(uri)
uri = url_parse(to_unicode(uri, charset))
path = url_unquote(uri.path, charset, errors, '/;?')
query = url_unquote(uri.query, charset, errors, ';/?:@&=+,$')
fragment = url_unquote(uri.fragment, charset, errors, ';/?:@&=+,$')
return url_unparse((uri.scheme, uri.decode_netloc(),
path, query, fragment))
def iri_to_uri(iri, charset='utf-8', errors='strict'):
r"""
Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always
uses utf-8 URLs internally because this is what browsers and HTTP do as
well. In some places where it accepts an URL it also accepts a unicode IRI
<|code_end|>
using the current file's imports:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and any relevant context from other files:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
. Output only the next line. | and converts it into a URI. |
Given the following code snippet before the placeholder: <|code_start|> 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
:param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given as
unicode string.
"""
scheme, netloc, path, qs, anchor = url_parse(to_unicode(s, charset, 'replace'))
path = url_quote(path, charset, safe='/%+$!*\'(),')
qs = url_quote_plus(qs, charset, safe=':&%=+$!*\'(),')
return to_native(url_unparse((scheme, netloc, path, qs, anchor)))
def uri_to_iri(uri, charset='utf-8', errors='replace'):
r"""
Converts a URI in a given charset to a IRI.
Examples for URI versus IRI:
>>> uri_to_iri(b'http://xn--n3h.net/')
u'http://\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
Query strings are left unchanged:
>>> uri_to_iri('/?foo=24&x=%26%2f')
u'/?foo=24&x=%26%2f'
.. versionadded:: 0.6
<|code_end|>
, predict the next line using imports from the current file:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context including class names, function names, and sometimes code from other files:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
. Output only the next line. | :param uri: The URI to convert. |
Using the snippet: <|code_start|>
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
:param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given as
unicode string.
"""
scheme, netloc, path, qs, anchor = url_parse(to_unicode(s, charset, 'replace'))
path = url_quote(path, charset, safe='/%+$!*\'(),')
qs = url_quote_plus(qs, charset, safe=':&%=+$!*\'(),')
return to_native(url_unparse((scheme, netloc, path, qs, anchor)))
def uri_to_iri(uri, charset='utf-8', errors='replace'):
r"""
Converts a URI in a given charset to a IRI.
Examples for URI versus IRI:
>>> uri_to_iri(b'http://xn--n3h.net/')
u'http://\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
Query strings are left unchanged:
>>> uri_to_iri('/?foo=24&x=%26%2f')
u'/?foo=24&x=%26%2f'
<|code_end|>
, determine the next line of code. You have imports:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context (class names, function names, or code) available:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
. Output only the next line. | .. versionadded:: 0.6 |
Next line prediction: <|code_start|> if isinstance(s, text_type):
s = s.replace(u'+', u' ')
else:
s = s.replace(b'+', b' ')
return url_unquote(s, charset, errors)
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
:param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given as
unicode string.
"""
scheme, netloc, path, qs, anchor = url_parse(to_unicode(s, charset, 'replace'))
path = url_quote(path, charset, safe='/%+$!*\'(),')
qs = url_quote_plus(qs, charset, safe=':&%=+$!*\'(),')
return to_native(url_unparse((scheme, netloc, path, qs, anchor)))
def uri_to_iri(uri, charset='utf-8', errors='replace'):
r"""
Converts a URI in a given charset to a IRI.
<|code_end|>
. Use current file imports:
(import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter)
and context including class names, function names, or small code snippets from other files:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
. Output only the next line. | Examples for URI versus IRI: |
Given the following code snippet before the placeholder: <|code_start|> u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
Query strings are left unchanged:
>>> uri_to_iri('/?foo=24&x=%26%2f')
u'/?foo=24&x=%26%2f'
.. versionadded:: 0.6
:param uri: The URI to convert.
:param charset: The charset of the URI.
:param errors: The error handling on decode.
"""
if isinstance(uri, tuple):
uri = url_unparse(uri)
uri = url_parse(to_unicode(uri, charset))
path = url_unquote(uri.path, charset, errors, '/;?')
query = url_unquote(uri.query, charset, errors, ';/?:@&=+,$')
fragment = url_unquote(uri.fragment, charset, errors, ';/?:@&=+,$')
return url_unparse((uri.scheme, uri.decode_netloc(),
path, query, fragment))
def iri_to_uri(iri, charset='utf-8', errors='strict'):
r"""
Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always
uses utf-8 URLs internally because this is what browsers and HTTP do as
well. In some places where it accepts an URL it also accepts a unicode IRI
and converts it into a URI.
<|code_end|>
, predict the next line using imports from the current file:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context including class names, function names, and sometimes code from other files:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
. Output only the next line. | Examples for IRI versus URI: |
Using the snippet: <|code_start|> u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
Query strings are left unchanged:
>>> uri_to_iri('/?foo=24&x=%26%2f')
u'/?foo=24&x=%26%2f'
.. versionadded:: 0.6
:param uri: The URI to convert.
:param charset: The charset of the URI.
:param errors: The error handling on decode.
"""
if isinstance(uri, tuple):
uri = url_unparse(uri)
uri = url_parse(to_unicode(uri, charset))
path = url_unquote(uri.path, charset, errors, '/;?')
query = url_unquote(uri.query, charset, errors, ';/?:@&=+,$')
fragment = url_unquote(uri.fragment, charset, errors, ';/?:@&=+,$')
return url_unparse((uri.scheme, uri.decode_netloc(),
path, query, fragment))
def iri_to_uri(iri, charset='utf-8', errors='strict'):
r"""
Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always
uses utf-8 URLs internally because this is what browsers and HTTP do as
well. In some places where it accepts an URL it also accepts a unicode IRI
and converts it into a URI.
<|code_end|>
, determine the next line of code. You have imports:
import re
from werkzeug._compat import text_type, PY2, to_unicode, \
to_native, implements_to_string, try_coerce_native, \
normalize_string_tuple, make_literal_wrapper, \
fix_tuple_repr
from werkzeug._internal import _encode_idna, _decode_idna
from werkzeug.datastructures import MultiDict, iter_multi_items
from collections import namedtuple
from werkzeug.wsgi import make_chunk_iter
and context (class names, function names, or code) available:
# Path: werkzeug/_compat.py
# PY2 = sys.version_info[0] == 2
# def fix_tuple_repr(obj):
# def __repr__(self):
# def implements_iterator(cls):
# def implements_to_string(cls):
# def native_string_result(func):
# def wrapper(*args, **kwargs):
# def implements_bool(cls):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def try_coerce_native(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def iter_bytes(b):
# def reraise(tp, value, tb=None):
# def make_literal_wrapper(reference):
# def normalize_string_tuple(tup):
# def wsgi_get_bytes(s):
# def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
# def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
# def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
# def to_unicode(x, charset=sys.getdefaultencoding(), errors='strict',
# allow_none_charset=False):
#
# Path: werkzeug/_internal.py
# def _encode_idna(domain):
# # If we're given bytes, make sure they fit into ASCII
# if not isinstance(domain, text_type):
# domain.decode('ascii')
# return domain
#
# # Otherwise check if it's already ascii, then return
# try:
# return domain.encode('ascii')
# except UnicodeError:
# pass
#
# # Otherwise encode each part separately
# parts = domain.split('.')
# for idx, part in enumerate(parts):
# parts[idx] = part.encode('idna')
# return b'.'.join(parts)
#
# def _decode_idna(domain):
# # If the input is a string try to encode it to ascii to
# # do the idna decoding. if that fails because of an
# # unicode error, then we already have a decoded idna domain
# if isinstance(domain, text_type):
# try:
# domain = domain.encode('ascii')
# except UnicodeError:
# return domain
#
# # Decode each part separately. If a part fails, try to
# # decode it with ascii and silently ignore errors. This makes
# # most sense because the idna codec does not have error handling
# parts = domain.split(b'.')
# for idx, part in enumerate(parts):
# try:
# parts[idx] = part.decode('idna')
# except UnicodeError:
# parts[idx] = part.decode('ascii', 'ignore')
#
# return '.'.join(parts)
. Output only the next line. | Examples for IRI versus URI: |
Based on the snippet: <|code_start|># -*- python -*-
# pylogsparser - Logs parsers python library
#
# Copyright (C) 2011 Wallix Inc.
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
def get_sensible_year(*args):
"""args is a list of ordered date elements, from month and day (both
mandatory) to eventual second. The function gives the most sensible
year for that set of values, so that the date is not set in the future."""
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import unittest
from datetime import datetime, timedelta
from logsparser.normalizer import get_generic_tagTypes
from logsparser.normalizer import get_generic_callBacks
and context (classes, functions, sometimes code) from other files:
# Path: logsparser/normalizer.py
# def get_generic_tagTypes(path = 'normalizers/common_tagTypes.xml'):
# """Imports the common tag types.
#
# @return: a dictionary of tag types."""
# generic = {}
# try:
# tagTypes = parse(open(path, 'r')).getroot()
# for tagType in tagTypes:
# tt_name = tagType.get('name')
# tt_type = tagType.get('ttype') or 'basestring'
# tt_desc = {}
# for child in tagType:
# if child.tag == 'description':
# for desc in child:
# lang = desc.get('language') or 'en'
# tt_desc[lang] = child.text
# elif child.tag == 'regexp':
# tt_regexp = child.text
# generic[tt_name] = TagType(tt_name, tt_type, tt_regexp, tt_desc)
# return generic
# except StandardError, err:
# warnings.warn("Could not load generic tags definition file : %s \
# - generic tags will not be available." % err)
# return {}
#
# Path: logsparser/normalizer.py
# def get_generic_callBacks(path = 'normalizers/common_callBacks.xml'):
# """Imports the common callbacks.
#
# @return a dictionnary of callbacks."""
# generic = {}
# try:
# callBacks = parse(open(path, 'r')).getroot()
# for callBack in callBacks:
# cb_name = callBack.get('name')
# # cb_desc = {}
# for child in callBack:
# if child.tag == 'code':
# cb_code = child.text
# # descriptions are not used yet but implemented in xml and dtd files for later use
# # elif child.tag == 'description':
# # for desc in child:
# # lang = desc.get('language')
# # cb_desc[lang] = desc.text
# generic[cb_name] = CallbackFunction(cb_code, cb_name)
# return generic
# except StandardError, err:
# warnings.warn("Could not load generic callbacks definition file : %s \
# - generic callbacks will not be available." % err)
# return {}
. Output only the next line. | year = int(datetime.now().year) |
Next line prediction: <|code_start|># -*- python -*-
# pylogsparser - Logs parsers python library
#
# Copyright (C) 2011 Wallix Inc.
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
def get_sensible_year(*args):
"""args is a list of ordered date elements, from month and day (both
mandatory) to eventual second. The function gives the most sensible
year for that set of values, so that the date is not set in the future."""
year = int(datetime.now().year)
<|code_end|>
. Use current file imports:
(import os
import unittest
from datetime import datetime, timedelta
from logsparser.normalizer import get_generic_tagTypes
from logsparser.normalizer import get_generic_callBacks)
and context including class names, function names, or small code snippets from other files:
# Path: logsparser/normalizer.py
# def get_generic_tagTypes(path = 'normalizers/common_tagTypes.xml'):
# """Imports the common tag types.
#
# @return: a dictionary of tag types."""
# generic = {}
# try:
# tagTypes = parse(open(path, 'r')).getroot()
# for tagType in tagTypes:
# tt_name = tagType.get('name')
# tt_type = tagType.get('ttype') or 'basestring'
# tt_desc = {}
# for child in tagType:
# if child.tag == 'description':
# for desc in child:
# lang = desc.get('language') or 'en'
# tt_desc[lang] = child.text
# elif child.tag == 'regexp':
# tt_regexp = child.text
# generic[tt_name] = TagType(tt_name, tt_type, tt_regexp, tt_desc)
# return generic
# except StandardError, err:
# warnings.warn("Could not load generic tags definition file : %s \
# - generic tags will not be available." % err)
# return {}
#
# Path: logsparser/normalizer.py
# def get_generic_callBacks(path = 'normalizers/common_callBacks.xml'):
# """Imports the common callbacks.
#
# @return a dictionnary of callbacks."""
# generic = {}
# try:
# callBacks = parse(open(path, 'r')).getroot()
# for callBack in callBacks:
# cb_name = callBack.get('name')
# # cb_desc = {}
# for child in callBack:
# if child.tag == 'code':
# cb_code = child.text
# # descriptions are not used yet but implemented in xml and dtd files for later use
# # elif child.tag == 'description':
# # for desc in child:
# # lang = desc.get('language')
# # cb_desc[lang] = desc.text
# generic[cb_name] = CallbackFunction(cb_code, cb_name)
# return generic
# except StandardError, err:
# warnings.warn("Could not load generic callbacks definition file : %s \
# - generic callbacks will not be available." % err)
# return {}
. Output only the next line. | d = datetime(year, *args) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Module tests."""
from __future__ import absolute_import, print_function
def _check_template():
"""Check template."""
extended = """
{% extends 'invenio_deposit/edit.html' %}
{% block javascript %}{% endblock %}
{% block css %}{% endblock %}
<|code_end|>
. Write the next line using the current file imports:
from copy import deepcopy
from flask import Flask, render_template_string
from invenio_records_rest import InvenioRecordsREST
from invenio_records_rest.utils import PIDConverter
from invenio_deposit import InvenioDeposit, InvenioDepositREST, bundles
from invenio_deposit.proxies import current_deposit
from invenio_deposit import __version__
import pytest
and context from other files:
# Path: invenio_deposit/bundles.py
#
# Path: invenio_deposit/ext.py
# class InvenioDeposit(object):
# """Invenio-Deposit extension."""
#
# def __init__(self, app=None):
# """Extension initialization."""
# if app:
# self.init_app(app)
#
# def init_app(self, app):
# """Flask application initialization.
#
# Initialize the UI endpoints. Connect all signals if
# `DEPOSIT_REGISTER_SIGNALS` is ``True``.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# self.init_config(app)
# app.register_blueprint(ui.create_blueprint(
# app.config['DEPOSIT_RECORDS_UI_ENDPOINTS']
# ))
# app.extensions['invenio-deposit'] = _DepositState(app)
# if app.config['DEPOSIT_REGISTER_SIGNALS']:
# post_action.connect(index_deposit_after_publish, sender=app,
# weak=False)
#
# def init_config(self, app):
# """Initialize configuration.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# app.config.setdefault(
# 'DEPOSIT_BASE_TEMPLATE',
# app.config.get('BASE_TEMPLATE',
# 'invenio_deposit/base.html'))
# for k in dir(config):
# if k.startswith('DEPOSIT_'):
# app.config.setdefault(k, getattr(config, k))
#
# class InvenioDepositREST(object):
# """Invenio-Deposit REST extension."""
#
# def __init__(self, app=None):
# """Extension initialization.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# if app:
# self.init_app(app)
#
# def init_app(self, app):
# """Flask application initialization.
#
# Initialize the REST endpoints. Connect all signals if
# `DEPOSIT_REGISTER_SIGNALS` is True.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# self.init_config(app)
# blueprint = rest.create_blueprint(
# app.config['DEPOSIT_REST_ENDPOINTS']
# )
#
# # FIXME: This is a temporary fix. This means that
# # invenio-records-rest's endpoint_prefixes cannot be used before
# # the first request or in other processes, ex: Celery tasks.
# @app.before_first_request
# def extend_default_endpoint_prefixes():
# """Extend redirects between PID types."""
# endpoint_prefixes = utils.build_default_endpoint_prefixes(
# dict(app.config['DEPOSIT_REST_ENDPOINTS'])
# )
# current_records_rest = app.extensions['invenio-records-rest']
# overlap = set(endpoint_prefixes.keys()) & set(
# current_records_rest.default_endpoint_prefixes
# )
# if overlap:
# raise RuntimeError(
# 'Deposit wants to override endpoint prefixes {0}.'.format(
# ', '.join(overlap)
# )
# )
# current_records_rest.default_endpoint_prefixes.update(
# endpoint_prefixes
# )
#
# app.register_blueprint(blueprint)
# app.extensions['invenio-deposit-rest'] = _DepositState(app)
# if app.config['DEPOSIT_REGISTER_SIGNALS']:
# post_action.connect(index_deposit_after_publish, sender=app,
# weak=False)
#
# def init_config(self, app):
# """Initialize configuration.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# for k in dir(config):
# if k.startswith('DEPOSIT_'):
# app.config.setdefault(k, getattr(config, k))
#
# Path: invenio_deposit/proxies.py
, which may include functions, classes, or code. Output only the next line. | {% block page_body %}{{ super() }}{% endblock %} |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Module tests."""
from __future__ import absolute_import, print_function
def _check_template():
"""Check template."""
extended = """
{% extends 'invenio_deposit/edit.html' %}
{% block javascript %}{% endblock %}
<|code_end|>
. Use current file imports:
(from copy import deepcopy
from flask import Flask, render_template_string
from invenio_records_rest import InvenioRecordsREST
from invenio_records_rest.utils import PIDConverter
from invenio_deposit import InvenioDeposit, InvenioDepositREST, bundles
from invenio_deposit.proxies import current_deposit
from invenio_deposit import __version__
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: invenio_deposit/bundles.py
#
# Path: invenio_deposit/ext.py
# class InvenioDeposit(object):
# """Invenio-Deposit extension."""
#
# def __init__(self, app=None):
# """Extension initialization."""
# if app:
# self.init_app(app)
#
# def init_app(self, app):
# """Flask application initialization.
#
# Initialize the UI endpoints. Connect all signals if
# `DEPOSIT_REGISTER_SIGNALS` is ``True``.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# self.init_config(app)
# app.register_blueprint(ui.create_blueprint(
# app.config['DEPOSIT_RECORDS_UI_ENDPOINTS']
# ))
# app.extensions['invenio-deposit'] = _DepositState(app)
# if app.config['DEPOSIT_REGISTER_SIGNALS']:
# post_action.connect(index_deposit_after_publish, sender=app,
# weak=False)
#
# def init_config(self, app):
# """Initialize configuration.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# app.config.setdefault(
# 'DEPOSIT_BASE_TEMPLATE',
# app.config.get('BASE_TEMPLATE',
# 'invenio_deposit/base.html'))
# for k in dir(config):
# if k.startswith('DEPOSIT_'):
# app.config.setdefault(k, getattr(config, k))
#
# class InvenioDepositREST(object):
# """Invenio-Deposit REST extension."""
#
# def __init__(self, app=None):
# """Extension initialization.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# if app:
# self.init_app(app)
#
# def init_app(self, app):
# """Flask application initialization.
#
# Initialize the REST endpoints. Connect all signals if
# `DEPOSIT_REGISTER_SIGNALS` is True.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# self.init_config(app)
# blueprint = rest.create_blueprint(
# app.config['DEPOSIT_REST_ENDPOINTS']
# )
#
# # FIXME: This is a temporary fix. This means that
# # invenio-records-rest's endpoint_prefixes cannot be used before
# # the first request or in other processes, ex: Celery tasks.
# @app.before_first_request
# def extend_default_endpoint_prefixes():
# """Extend redirects between PID types."""
# endpoint_prefixes = utils.build_default_endpoint_prefixes(
# dict(app.config['DEPOSIT_REST_ENDPOINTS'])
# )
# current_records_rest = app.extensions['invenio-records-rest']
# overlap = set(endpoint_prefixes.keys()) & set(
# current_records_rest.default_endpoint_prefixes
# )
# if overlap:
# raise RuntimeError(
# 'Deposit wants to override endpoint prefixes {0}.'.format(
# ', '.join(overlap)
# )
# )
# current_records_rest.default_endpoint_prefixes.update(
# endpoint_prefixes
# )
#
# app.register_blueprint(blueprint)
# app.extensions['invenio-deposit-rest'] = _DepositState(app)
# if app.config['DEPOSIT_REGISTER_SIGNALS']:
# post_action.connect(index_deposit_after_publish, sender=app,
# weak=False)
#
# def init_config(self, app):
# """Initialize configuration.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# for k in dir(config):
# if k.startswith('DEPOSIT_'):
# app.config.setdefault(k, getattr(config, k))
#
# Path: invenio_deposit/proxies.py
. Output only the next line. | {% block css %}{% endblock %} |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Module tests."""
from __future__ import absolute_import, print_function
def _check_template():
"""Check template."""
extended = """
{% extends 'invenio_deposit/edit.html' %}
{% block javascript %}{% endblock %}
{% block css %}{% endblock %}
<|code_end|>
, predict the immediate next line with the help of imports:
from copy import deepcopy
from flask import Flask, render_template_string
from invenio_records_rest import InvenioRecordsREST
from invenio_records_rest.utils import PIDConverter
from invenio_deposit import InvenioDeposit, InvenioDepositREST, bundles
from invenio_deposit.proxies import current_deposit
from invenio_deposit import __version__
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: invenio_deposit/bundles.py
#
# Path: invenio_deposit/ext.py
# class InvenioDeposit(object):
# """Invenio-Deposit extension."""
#
# def __init__(self, app=None):
# """Extension initialization."""
# if app:
# self.init_app(app)
#
# def init_app(self, app):
# """Flask application initialization.
#
# Initialize the UI endpoints. Connect all signals if
# `DEPOSIT_REGISTER_SIGNALS` is ``True``.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# self.init_config(app)
# app.register_blueprint(ui.create_blueprint(
# app.config['DEPOSIT_RECORDS_UI_ENDPOINTS']
# ))
# app.extensions['invenio-deposit'] = _DepositState(app)
# if app.config['DEPOSIT_REGISTER_SIGNALS']:
# post_action.connect(index_deposit_after_publish, sender=app,
# weak=False)
#
# def init_config(self, app):
# """Initialize configuration.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# app.config.setdefault(
# 'DEPOSIT_BASE_TEMPLATE',
# app.config.get('BASE_TEMPLATE',
# 'invenio_deposit/base.html'))
# for k in dir(config):
# if k.startswith('DEPOSIT_'):
# app.config.setdefault(k, getattr(config, k))
#
# class InvenioDepositREST(object):
# """Invenio-Deposit REST extension."""
#
# def __init__(self, app=None):
# """Extension initialization.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# if app:
# self.init_app(app)
#
# def init_app(self, app):
# """Flask application initialization.
#
# Initialize the REST endpoints. Connect all signals if
# `DEPOSIT_REGISTER_SIGNALS` is True.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# self.init_config(app)
# blueprint = rest.create_blueprint(
# app.config['DEPOSIT_REST_ENDPOINTS']
# )
#
# # FIXME: This is a temporary fix. This means that
# # invenio-records-rest's endpoint_prefixes cannot be used before
# # the first request or in other processes, ex: Celery tasks.
# @app.before_first_request
# def extend_default_endpoint_prefixes():
# """Extend redirects between PID types."""
# endpoint_prefixes = utils.build_default_endpoint_prefixes(
# dict(app.config['DEPOSIT_REST_ENDPOINTS'])
# )
# current_records_rest = app.extensions['invenio-records-rest']
# overlap = set(endpoint_prefixes.keys()) & set(
# current_records_rest.default_endpoint_prefixes
# )
# if overlap:
# raise RuntimeError(
# 'Deposit wants to override endpoint prefixes {0}.'.format(
# ', '.join(overlap)
# )
# )
# current_records_rest.default_endpoint_prefixes.update(
# endpoint_prefixes
# )
#
# app.register_blueprint(blueprint)
# app.extensions['invenio-deposit-rest'] = _DepositState(app)
# if app.config['DEPOSIT_REGISTER_SIGNALS']:
# post_action.connect(index_deposit_after_publish, sender=app,
# weak=False)
#
# def init_config(self, app):
# """Initialize configuration.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# for k in dir(config):
# if k.startswith('DEPOSIT_'):
# app.config.setdefault(k, getattr(config, k))
#
# Path: invenio_deposit/proxies.py
. Output only the next line. | {% block page_body %}{{ super() }}{% endblock %} |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Module tests."""
from __future__ import absolute_import, print_function
def _check_template():
"""Check template."""
extended = """
<|code_end|>
with the help of current file imports:
from copy import deepcopy
from flask import Flask, render_template_string
from invenio_records_rest import InvenioRecordsREST
from invenio_records_rest.utils import PIDConverter
from invenio_deposit import InvenioDeposit, InvenioDepositREST, bundles
from invenio_deposit.proxies import current_deposit
from invenio_deposit import __version__
import pytest
and context from other files:
# Path: invenio_deposit/bundles.py
#
# Path: invenio_deposit/ext.py
# class InvenioDeposit(object):
# """Invenio-Deposit extension."""
#
# def __init__(self, app=None):
# """Extension initialization."""
# if app:
# self.init_app(app)
#
# def init_app(self, app):
# """Flask application initialization.
#
# Initialize the UI endpoints. Connect all signals if
# `DEPOSIT_REGISTER_SIGNALS` is ``True``.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# self.init_config(app)
# app.register_blueprint(ui.create_blueprint(
# app.config['DEPOSIT_RECORDS_UI_ENDPOINTS']
# ))
# app.extensions['invenio-deposit'] = _DepositState(app)
# if app.config['DEPOSIT_REGISTER_SIGNALS']:
# post_action.connect(index_deposit_after_publish, sender=app,
# weak=False)
#
# def init_config(self, app):
# """Initialize configuration.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# app.config.setdefault(
# 'DEPOSIT_BASE_TEMPLATE',
# app.config.get('BASE_TEMPLATE',
# 'invenio_deposit/base.html'))
# for k in dir(config):
# if k.startswith('DEPOSIT_'):
# app.config.setdefault(k, getattr(config, k))
#
# class InvenioDepositREST(object):
# """Invenio-Deposit REST extension."""
#
# def __init__(self, app=None):
# """Extension initialization.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# if app:
# self.init_app(app)
#
# def init_app(self, app):
# """Flask application initialization.
#
# Initialize the REST endpoints. Connect all signals if
# `DEPOSIT_REGISTER_SIGNALS` is True.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# self.init_config(app)
# blueprint = rest.create_blueprint(
# app.config['DEPOSIT_REST_ENDPOINTS']
# )
#
# # FIXME: This is a temporary fix. This means that
# # invenio-records-rest's endpoint_prefixes cannot be used before
# # the first request or in other processes, ex: Celery tasks.
# @app.before_first_request
# def extend_default_endpoint_prefixes():
# """Extend redirects between PID types."""
# endpoint_prefixes = utils.build_default_endpoint_prefixes(
# dict(app.config['DEPOSIT_REST_ENDPOINTS'])
# )
# current_records_rest = app.extensions['invenio-records-rest']
# overlap = set(endpoint_prefixes.keys()) & set(
# current_records_rest.default_endpoint_prefixes
# )
# if overlap:
# raise RuntimeError(
# 'Deposit wants to override endpoint prefixes {0}.'.format(
# ', '.join(overlap)
# )
# )
# current_records_rest.default_endpoint_prefixes.update(
# endpoint_prefixes
# )
#
# app.register_blueprint(blueprint)
# app.extensions['invenio-deposit-rest'] = _DepositState(app)
# if app.config['DEPOSIT_REGISTER_SIGNALS']:
# post_action.connect(index_deposit_after_publish, sender=app,
# weak=False)
#
# def init_config(self, app):
# """Initialize configuration.
#
# :param app: An instance of :class:`flask.Flask`.
# """
# for k in dir(config):
# if k.startswith('DEPOSIT_'):
# app.config.setdefault(k, getattr(config, k))
#
# Path: invenio_deposit/proxies.py
, which may contain function names, class names, or code. Output only the next line. | {% extends 'invenio_deposit/edit.html' %} |
Here is a snippet: <|code_start|>
if self._label_encoder is None or self._onehot_encoder is None:
self._label_encoder = [None] * len(Xenc.columns)
self._onehot_encoder = [None] * len(Xenc.columns)
del_columns = []
for i in range(len(Xenc.columns)):
if Xenc.dtypes[i] == np.dtype('O'):
if self._label_encoder[i] is None:
self._label_encoder[i] = LabelEncoder().fit(Xenc.iloc[:,i])
col_enc = self._label_encoder[i].transform(Xenc.iloc[:,i])
if self._onehot_encoder[i] is None:
self._onehot_encoder[i] = OneHotEncoder(categories='auto').fit(
col_enc.reshape(-1, 1))
col_onehot = np.array(self._onehot_encoder[i].transform(
col_enc.reshape(-1, 1)).todense())
col_names = [str(Xenc.columns[i]) + '_' + c
for c in self._label_encoder[i].classes_]
col_onehot = pd.DataFrame(col_onehot, columns=col_names,
index=Xenc.index)
Xenc = pd.concat([Xenc, col_onehot], axis=1)
del_columns.append(Xenc.columns[i])
for col in del_columns:
del Xenc[col]
return Xenc, del_columns
def __standardize(self, X):
X = X.astype('float64')
if self._standardizer is None:
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import pandas as pd
from sklearn.utils import shuffle as sk_shuffle
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.preprocessing import StandardScaler
from .rfpimp import oob_importances
and context from other files:
# Path: malss/rfpimp.py
# def oob_importances(rf, X_train, y_train, n_samples=5000):
# """
# Compute permutation feature importances for scikit-learn
# RandomForestClassifier or RandomForestRegressor in arg rf.
#
# Given training X and y data, return a data frame with columns
# Feature and Importance sorted in reverse order by importance.
# The training data is needed to compute out of bag (OOB)
# model performance measures (accuracy or R^2). The model
# is not retrained.
#
# By default, sample up to 5000 observations to compute feature importances.
#
# return: A data frame with Feature, Importance columns
#
# SAMPLE CODE
#
# rf = RandomForestRegressor(n_estimators=100, n_jobs=-1, oob_score=True)
# X_train, y_train = ..., ...
# rf.fit(X_train, y_train)
# imp = oob_importances(rf, X_train, y_train)
# """
# if isinstance(rf, RandomForestClassifier):
# return permutation_importances(rf, X_train, y_train, oob_classifier_accuracy, n_samples)
# elif isinstance(rf, RandomForestRegressor):
# return permutation_importances(rf, X_train, y_train, oob_regression_r2_score, n_samples)
# return None
, which may include functions, classes, or code. Output only the next line. | self._standardizer = StandardScaler().fit(X) |
Here is a snippet: <|code_start|># coding: utf-8
class Introduction(Content):
def __init__(self, parent=None, button_func=None, params=None):
super().__init__(parent, 'Introduction', params)
self.button_func = button_func
path = os.path.abspath(os.path.dirname(__file__)) + '/static/'
path += 'introduction'
text = self.get_text(path)
self.set_paragraph('MALSS interactive', text=text)
btn = QPushButton('Next', self.inner)
btn.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};')
<|code_end|>
. Write the next line using the current file imports:
import os
from PyQt5.QtWidgets import QPushButton
from .content import Content
and context from other files:
# Path: malss/app/content.py
# class Content(QScrollArea):
#
# def __init__(self, parent=None, title='', params=None):
# super().__init__(parent)
#
# self.params = params
#
# self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
#
# self.lbl_img_list = []
# self.pixmap_list = []
#
# self.H1_HEIGHT = 50
# self.H2_HEIGHT = 50
# self.SIDE_MARGIN = 5
# self.H1_FONT_SIZE = 18
# self.H2_FONT_SIZE = 18
# self.H3_FONT_SIZE = 16
# self.TEXT_FONT_SIZE = 14
#
# self.inner = QWidget(self)
#
# self.vbox = QVBoxLayout(self.inner)
# self.vbox.setSpacing(10)
# self.vbox.setContentsMargins(0, 0, 0, 0)
#
# topframe = QFrame()
# topframe.setStyleSheet('background-color: white')
# topframe.setFixedHeight(self.H1_HEIGHT)
#
# self.title = title
# lbl_h1 = QLabel(title, topframe)
# fnt = lbl_h1.font()
# fnt.setPointSize(self.H1_FONT_SIZE)
# lbl_h1.setFont(fnt)
# lbl_h1.setFixedHeight(self.H1_HEIGHT)
# lbl_h1.setMargin(self.SIDE_MARGIN)
#
# self.vbox.addWidget(topframe)
#
# self.inner.setLayout(self.vbox)
#
# self.setWidget(self.inner)
#
# def set_paragraph(self, h2='', h3='', text='', img=None):
# if h2 != '':
# lbl_h2 = QLabel(h2, self.inner)
# fnt = lbl_h2.font()
# fnt.setPointSize(self.H2_FONT_SIZE)
# lbl_h2.setFont(fnt)
# lbl_h2.setFixedHeight(self.H2_HEIGHT)
# lbl_h2.setAlignment(Qt.AlignBottom)
# lbl_h2.setMargin(self.SIDE_MARGIN)
# self.vbox.addWidget(lbl_h2)
#
# frm = QFrame(self.inner)
# frm.setFrameShape(QFrame.HLine)
# frm.setContentsMargins(self.SIDE_MARGIN, 0, self.SIDE_MARGIN, 0)
# plt = frm.palette()
# plt.setColor(QPalette.WindowText, Qt.darkGray)
# frm.setPalette(plt)
# self.vbox.addWidget(frm)
#
# if text != '':
# lbl_txt = QLabel(text, self.inner)
# lbl_txt.setWordWrap(True)
# fnt = lbl_txt.font()
# fnt.setPointSize(self.TEXT_FONT_SIZE)
# lbl_txt.setFont(fnt)
# lbl_txt.setMargin(self.SIDE_MARGIN)
# self.vbox.addWidget(lbl_txt)
#
# if img is not None:
# if self.params.lang == 'en':
# img += '_en.png'
# else:
# img += '_jp.png'
# pixmap = QPixmap(img)
# if not pixmap.isNull():
# lbl_img = QLabel(self.inner)
# lbl_img.setPixmap(pixmap)
# self.lbl_img_list.append(lbl_img)
# self.pixmap_list.append(pixmap.scaledToWidth(pixmap.width()))
# self.vbox.addWidget(lbl_img)
#
# self.inner.setLayout(self.vbox)
#
# def get_text(self, path):
# if self.params.lang == 'en':
# path += '_en.txt'
# else:
# path += '_jp.txt'
#
# try:
# text = open(path, encoding='utf8').read()
# except FileNotFoundError:
# text = 'No text available'
# return text
#
# def make_dtype(self, columns, dtypes):
# if columns is None or dtypes is None:
# return None
#
# dic = {}
# for c, d in zip(columns, dtypes):
# dic[c] = d
# return dic
#
# def resizeEvent(self, event):
# # Resize images only if the width of the scroll area
# # is shorter than that of images
# for i, lbl in enumerate(self.lbl_img_list):
# w = self.width() - QStyle.PM_ScrollBarExtent
# if w < self.pixmap_list[i].width():
# lbl.setPixmap(
# self.pixmap_list[i].scaledToWidth(
# w, Qt.SmoothTransformation))
# else:
# lbl.setPixmap(
# self.pixmap_list[i].scaledToWidth(
# self.pixmap_list[i].width()))
# return super().resizeEvent(event)
, which may include functions, classes, or code. Output only the next line. | if self.params.lang == 'en':
|
Next line prediction: <|code_start|># coding: utf-8
class TypeOfTask(Content):
def __init__(self, parent=None, button_func=None, params=None):
super().__init__(parent, 'Task', params)
self.button_func = button_func
path = os.path.abspath(os.path.dirname(__file__)) + '/static/'
# Text for machine learning tasks
path1 = path + 'task'
text = self.get_text(path1)
<|code_end|>
. Use current file imports:
(import os
from PyQt5.QtWidgets import (QVBoxLayout, QHBoxLayout, QPushButton,
QRadioButton, QButtonGroup)
from .content import Content
)
and context including class names, function names, or small code snippets from other files:
# Path: malss/app/content.py
# class Content(QScrollArea):
#
# def __init__(self, parent=None, title='', params=None):
# super().__init__(parent)
#
# self.params = params
#
# self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
#
# self.lbl_img_list = []
# self.pixmap_list = []
#
# self.H1_HEIGHT = 50
# self.H2_HEIGHT = 50
# self.SIDE_MARGIN = 5
# self.H1_FONT_SIZE = 18
# self.H2_FONT_SIZE = 18
# self.H3_FONT_SIZE = 16
# self.TEXT_FONT_SIZE = 14
#
# self.inner = QWidget(self)
#
# self.vbox = QVBoxLayout(self.inner)
# self.vbox.setSpacing(10)
# self.vbox.setContentsMargins(0, 0, 0, 0)
#
# topframe = QFrame()
# topframe.setStyleSheet('background-color: white')
# topframe.setFixedHeight(self.H1_HEIGHT)
#
# self.title = title
# lbl_h1 = QLabel(title, topframe)
# fnt = lbl_h1.font()
# fnt.setPointSize(self.H1_FONT_SIZE)
# lbl_h1.setFont(fnt)
# lbl_h1.setFixedHeight(self.H1_HEIGHT)
# lbl_h1.setMargin(self.SIDE_MARGIN)
#
# self.vbox.addWidget(topframe)
#
# self.inner.setLayout(self.vbox)
#
# self.setWidget(self.inner)
#
# def set_paragraph(self, h2='', h3='', text='', img=None):
# if h2 != '':
# lbl_h2 = QLabel(h2, self.inner)
# fnt = lbl_h2.font()
# fnt.setPointSize(self.H2_FONT_SIZE)
# lbl_h2.setFont(fnt)
# lbl_h2.setFixedHeight(self.H2_HEIGHT)
# lbl_h2.setAlignment(Qt.AlignBottom)
# lbl_h2.setMargin(self.SIDE_MARGIN)
# self.vbox.addWidget(lbl_h2)
#
# frm = QFrame(self.inner)
# frm.setFrameShape(QFrame.HLine)
# frm.setContentsMargins(self.SIDE_MARGIN, 0, self.SIDE_MARGIN, 0)
# plt = frm.palette()
# plt.setColor(QPalette.WindowText, Qt.darkGray)
# frm.setPalette(plt)
# self.vbox.addWidget(frm)
#
# if text != '':
# lbl_txt = QLabel(text, self.inner)
# lbl_txt.setWordWrap(True)
# fnt = lbl_txt.font()
# fnt.setPointSize(self.TEXT_FONT_SIZE)
# lbl_txt.setFont(fnt)
# lbl_txt.setMargin(self.SIDE_MARGIN)
# self.vbox.addWidget(lbl_txt)
#
# if img is not None:
# if self.params.lang == 'en':
# img += '_en.png'
# else:
# img += '_jp.png'
# pixmap = QPixmap(img)
# if not pixmap.isNull():
# lbl_img = QLabel(self.inner)
# lbl_img.setPixmap(pixmap)
# self.lbl_img_list.append(lbl_img)
# self.pixmap_list.append(pixmap.scaledToWidth(pixmap.width()))
# self.vbox.addWidget(lbl_img)
#
# self.inner.setLayout(self.vbox)
#
# def get_text(self, path):
# if self.params.lang == 'en':
# path += '_en.txt'
# else:
# path += '_jp.txt'
#
# try:
# text = open(path, encoding='utf8').read()
# except FileNotFoundError:
# text = 'No text available'
# return text
#
# def make_dtype(self, columns, dtypes):
# if columns is None or dtypes is None:
# return None
#
# dic = {}
# for c, d in zip(columns, dtypes):
# dic[c] = d
# return dic
#
# def resizeEvent(self, event):
# # Resize images only if the width of the scroll area
# # is shorter than that of images
# for i, lbl in enumerate(self.lbl_img_list):
# w = self.width() - QStyle.PM_ScrollBarExtent
# if w < self.pixmap_list[i].width():
# lbl.setPixmap(
# self.pixmap_list[i].scaledToWidth(
# w, Qt.SmoothTransformation))
# else:
# lbl.setPixmap(
# self.pixmap_list[i].scaledToWidth(
# self.pixmap_list[i].width()))
# return super().resizeEvent(event)
. Output only the next line. | if self.params.lang == 'en':
|
Using the snippet: <|code_start|> (dname, algorithm.estimator.__class__.__name__),
bbox_inches='tight', dpi=75)
plt.close()
@classmethod
def calc_scores(cls, model, data, min_clusters, max_clusters, random_state=0):
silhouettes = []
davieses = []
calinskies = []
if model.__class__.__name__ == 'HierarchicalClustering':
linkage_matrix = model.fit(data)
else:
linkage_matrix = None
for nc in range(min_clusters, max_clusters + 1):
model.n_clusters = nc
model.random_state = random_state
pred_labels = model.fit_predict(data)
silhouettes.append(silhouette_score(data, pred_labels, random_state=random_state))
davieses.append(davies_bouldin_score(data, pred_labels))
calinskies.append(calinski_harabasz_score(data, pred_labels))
sil_nc = np.argmax(silhouettes) + min_clusters
dav_nc = np.argmin(davieses) + min_clusters
cal_nc = np.argmax(calinskies) + min_clusters
return silhouettes, sil_nc, davieses, dav_nc, calinskies, cal_nc, linkage_matrix
@classmethod
def plot_silhouette(cls, algorithm, dname):
if dname is None:
<|code_end|>
, determine the next line of code. You have imports:
import os
import io
import shutil
import numpy as np
import pandas
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score
from jinja2 import Environment, FileSystemLoader
from .algorithm import Algorithm
from .hierarchy import HierarchicalClustering
and context (class names, function names, or code) available:
# Path: malss/algorithm.py
# class Algorithm(object):
# def __init__(self, estimator, parameters, name, link=None):
# self.estimator = estimator
# self.parameters = parameters
# self.best_score = None
# self.best_params = None
# self.is_best_algorithm = False
# self.grid_scores = None
# self.classification_report = None
# self.name = name
# self.link = link
# self.results = {}
#
# Path: malss/hierarchy.py
# class HierarchicalClustering(object):
# def __init__(self, n_clusters=3, random_state=None, method='complete', metric='euclidean'):
# self.n_clusters = n_clusters
# self.random_state = random_state
# self.method = method
# self.metric = metric
# self.model = None
#
# def fit_predict(self, X, y=None):
# self.model = linkage(X, method=self.method, metric=self.metric)
# return fcluster(self.model, t=self.n_clusters, criterion='maxclust') - 1
#
# def fit(self, X, y=None):
# self.model = linkage(X, method=self.method, metric=self.metric)
# return self.model
#
# def dendrogram(self):
# return dendrogram(self.model, truncate_mode='lastp', p=min(12, len(self.model)))
. Output only the next line. | return
|
Based on the snippet: <|code_start|> return inertia
@classmethod
def calc_gap(cls, model, data, min_clusters, max_clusters, num_iter=50, random_state=0, svd=True):
if svd:
U, s, V = np.linalg.svd(data, full_matrices=True)
X = np.dot(data, V)
else:
X = data
X_max = X.max(axis=0)
X_min = X.min(axis=0)
gap = []
sk = []
gap_star = []
sk_star = []
for nc in range(min_clusters, max_clusters+1):
model.n_clusters = nc
model.random_state = random_state
pred_labels = model.fit_predict(data)
if hasattr(model, 'inertia_'):
dispersion = model.inertia_
else:
dispersion = Clustering.calc_inertia(data, pred_labels)
ref_dispersions = []
for iter in range(num_iter):
np.random.seed(random_state + iter)
ref = np.random.rand(*data.shape)
ref = (ref * (X_max - X_min)) + X_min
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import io
import shutil
import numpy as np
import pandas
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score
from jinja2 import Environment, FileSystemLoader
from .algorithm import Algorithm
from .hierarchy import HierarchicalClustering
and context (classes, functions, sometimes code) from other files:
# Path: malss/algorithm.py
# class Algorithm(object):
# def __init__(self, estimator, parameters, name, link=None):
# self.estimator = estimator
# self.parameters = parameters
# self.best_score = None
# self.best_params = None
# self.is_best_algorithm = False
# self.grid_scores = None
# self.classification_report = None
# self.name = name
# self.link = link
# self.results = {}
#
# Path: malss/hierarchy.py
# class HierarchicalClustering(object):
# def __init__(self, n_clusters=3, random_state=None, method='complete', metric='euclidean'):
# self.n_clusters = n_clusters
# self.random_state = random_state
# self.method = method
# self.metric = metric
# self.model = None
#
# def fit_predict(self, X, y=None):
# self.model = linkage(X, method=self.method, metric=self.metric)
# return fcluster(self.model, t=self.n_clusters, criterion='maxclust') - 1
#
# def fit(self, X, y=None):
# self.model = linkage(X, method=self.method, metric=self.metric)
# return self.model
#
# def dendrogram(self):
# return dendrogram(self.model, truncate_mode='lastp', p=min(12, len(self.model)))
. Output only the next line. | if svd:
|
Given snippet: <|code_start|># coding: utf-8
class Error(Content):
def __init__(self, parent=None, button_func=None, params=None):
super().__init__(parent, 'Error', params)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from PyQt5.QtWidgets import (QHBoxLayout, QPushButton)
from PyQt5.QtCore import QCoreApplication
from .content import Content
and context:
# Path: malss/app/content.py
# class Content(QScrollArea):
#
# def __init__(self, parent=None, title='', params=None):
# super().__init__(parent)
#
# self.params = params
#
# self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
#
# self.lbl_img_list = []
# self.pixmap_list = []
#
# self.H1_HEIGHT = 50
# self.H2_HEIGHT = 50
# self.SIDE_MARGIN = 5
# self.H1_FONT_SIZE = 18
# self.H2_FONT_SIZE = 18
# self.H3_FONT_SIZE = 16
# self.TEXT_FONT_SIZE = 14
#
# self.inner = QWidget(self)
#
# self.vbox = QVBoxLayout(self.inner)
# self.vbox.setSpacing(10)
# self.vbox.setContentsMargins(0, 0, 0, 0)
#
# topframe = QFrame()
# topframe.setStyleSheet('background-color: white')
# topframe.setFixedHeight(self.H1_HEIGHT)
#
# self.title = title
# lbl_h1 = QLabel(title, topframe)
# fnt = lbl_h1.font()
# fnt.setPointSize(self.H1_FONT_SIZE)
# lbl_h1.setFont(fnt)
# lbl_h1.setFixedHeight(self.H1_HEIGHT)
# lbl_h1.setMargin(self.SIDE_MARGIN)
#
# self.vbox.addWidget(topframe)
#
# self.inner.setLayout(self.vbox)
#
# self.setWidget(self.inner)
#
# def set_paragraph(self, h2='', h3='', text='', img=None):
# if h2 != '':
# lbl_h2 = QLabel(h2, self.inner)
# fnt = lbl_h2.font()
# fnt.setPointSize(self.H2_FONT_SIZE)
# lbl_h2.setFont(fnt)
# lbl_h2.setFixedHeight(self.H2_HEIGHT)
# lbl_h2.setAlignment(Qt.AlignBottom)
# lbl_h2.setMargin(self.SIDE_MARGIN)
# self.vbox.addWidget(lbl_h2)
#
# frm = QFrame(self.inner)
# frm.setFrameShape(QFrame.HLine)
# frm.setContentsMargins(self.SIDE_MARGIN, 0, self.SIDE_MARGIN, 0)
# plt = frm.palette()
# plt.setColor(QPalette.WindowText, Qt.darkGray)
# frm.setPalette(plt)
# self.vbox.addWidget(frm)
#
# if text != '':
# lbl_txt = QLabel(text, self.inner)
# lbl_txt.setWordWrap(True)
# fnt = lbl_txt.font()
# fnt.setPointSize(self.TEXT_FONT_SIZE)
# lbl_txt.setFont(fnt)
# lbl_txt.setMargin(self.SIDE_MARGIN)
# self.vbox.addWidget(lbl_txt)
#
# if img is not None:
# if self.params.lang == 'en':
# img += '_en.png'
# else:
# img += '_jp.png'
# pixmap = QPixmap(img)
# if not pixmap.isNull():
# lbl_img = QLabel(self.inner)
# lbl_img.setPixmap(pixmap)
# self.lbl_img_list.append(lbl_img)
# self.pixmap_list.append(pixmap.scaledToWidth(pixmap.width()))
# self.vbox.addWidget(lbl_img)
#
# self.inner.setLayout(self.vbox)
#
# def get_text(self, path):
# if self.params.lang == 'en':
# path += '_en.txt'
# else:
# path += '_jp.txt'
#
# try:
# text = open(path, encoding='utf8').read()
# except FileNotFoundError:
# text = 'No text available'
# return text
#
# def make_dtype(self, columns, dtypes):
# if columns is None or dtypes is None:
# return None
#
# dic = {}
# for c, d in zip(columns, dtypes):
# dic[c] = d
# return dic
#
# def resizeEvent(self, event):
# # Resize images only if the width of the scroll area
# # is shorter than that of images
# for i, lbl in enumerate(self.lbl_img_list):
# w = self.width() - QStyle.PM_ScrollBarExtent
# if w < self.pixmap_list[i].width():
# lbl.setPixmap(
# self.pixmap_list[i].scaledToWidth(
# w, Qt.SmoothTransformation))
# else:
# lbl.setPixmap(
# self.pixmap_list[i].scaledToWidth(
# self.pixmap_list[i].width()))
# return super().resizeEvent(event)
which might include code, classes, or functions. Output only the next line. | if self.params.lang == 'en':
|
Predict the next line after this snippet: <|code_start|># coding: utf-8
class BiasVariance(Content):
def __init__(self, parent=None, button_func=None, params=None):
super().__init__(parent, 'Bias and Variance', params)
self.button_func = button_func
path = os.path.abspath(os.path.dirname(__file__)) + '/static/'
# Text for learning curve
path1 = path + 'learning_curve'
text = self.get_text(path1)
<|code_end|>
using the current file's imports:
import os
from PyQt5.QtWidgets import QHBoxLayout, QPushButton
from .content import Content
and any relevant context from other files:
# Path: malss/app/content.py
# class Content(QScrollArea):
#
# def __init__(self, parent=None, title='', params=None):
# super().__init__(parent)
#
# self.params = params
#
# self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
#
# self.lbl_img_list = []
# self.pixmap_list = []
#
# self.H1_HEIGHT = 50
# self.H2_HEIGHT = 50
# self.SIDE_MARGIN = 5
# self.H1_FONT_SIZE = 18
# self.H2_FONT_SIZE = 18
# self.H3_FONT_SIZE = 16
# self.TEXT_FONT_SIZE = 14
#
# self.inner = QWidget(self)
#
# self.vbox = QVBoxLayout(self.inner)
# self.vbox.setSpacing(10)
# self.vbox.setContentsMargins(0, 0, 0, 0)
#
# topframe = QFrame()
# topframe.setStyleSheet('background-color: white')
# topframe.setFixedHeight(self.H1_HEIGHT)
#
# self.title = title
# lbl_h1 = QLabel(title, topframe)
# fnt = lbl_h1.font()
# fnt.setPointSize(self.H1_FONT_SIZE)
# lbl_h1.setFont(fnt)
# lbl_h1.setFixedHeight(self.H1_HEIGHT)
# lbl_h1.setMargin(self.SIDE_MARGIN)
#
# self.vbox.addWidget(topframe)
#
# self.inner.setLayout(self.vbox)
#
# self.setWidget(self.inner)
#
# def set_paragraph(self, h2='', h3='', text='', img=None):
# if h2 != '':
# lbl_h2 = QLabel(h2, self.inner)
# fnt = lbl_h2.font()
# fnt.setPointSize(self.H2_FONT_SIZE)
# lbl_h2.setFont(fnt)
# lbl_h2.setFixedHeight(self.H2_HEIGHT)
# lbl_h2.setAlignment(Qt.AlignBottom)
# lbl_h2.setMargin(self.SIDE_MARGIN)
# self.vbox.addWidget(lbl_h2)
#
# frm = QFrame(self.inner)
# frm.setFrameShape(QFrame.HLine)
# frm.setContentsMargins(self.SIDE_MARGIN, 0, self.SIDE_MARGIN, 0)
# plt = frm.palette()
# plt.setColor(QPalette.WindowText, Qt.darkGray)
# frm.setPalette(plt)
# self.vbox.addWidget(frm)
#
# if text != '':
# lbl_txt = QLabel(text, self.inner)
# lbl_txt.setWordWrap(True)
# fnt = lbl_txt.font()
# fnt.setPointSize(self.TEXT_FONT_SIZE)
# lbl_txt.setFont(fnt)
# lbl_txt.setMargin(self.SIDE_MARGIN)
# self.vbox.addWidget(lbl_txt)
#
# if img is not None:
# if self.params.lang == 'en':
# img += '_en.png'
# else:
# img += '_jp.png'
# pixmap = QPixmap(img)
# if not pixmap.isNull():
# lbl_img = QLabel(self.inner)
# lbl_img.setPixmap(pixmap)
# self.lbl_img_list.append(lbl_img)
# self.pixmap_list.append(pixmap.scaledToWidth(pixmap.width()))
# self.vbox.addWidget(lbl_img)
#
# self.inner.setLayout(self.vbox)
#
# def get_text(self, path):
# if self.params.lang == 'en':
# path += '_en.txt'
# else:
# path += '_jp.txt'
#
# try:
# text = open(path, encoding='utf8').read()
# except FileNotFoundError:
# text = 'No text available'
# return text
#
# def make_dtype(self, columns, dtypes):
# if columns is None or dtypes is None:
# return None
#
# dic = {}
# for c, d in zip(columns, dtypes):
# dic[c] = d
# return dic
#
# def resizeEvent(self, event):
# # Resize images only if the width of the scroll area
# # is shorter than that of images
# for i, lbl in enumerate(self.lbl_img_list):
# w = self.width() - QStyle.PM_ScrollBarExtent
# if w < self.pixmap_list[i].width():
# lbl.setPixmap(
# self.pixmap_list[i].scaledToWidth(
# w, Qt.SmoothTransformation))
# else:
# lbl.setPixmap(
# self.pixmap_list[i].scaledToWidth(
# self.pixmap_list[i].width()))
# return super().resizeEvent(event)
. Output only the next line. | if self.params.lang == 'en':
|
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
# TODO write it with pytest...
def exception():
raise ValueError, "Test Test ä"
def exception2():
raise ValueError, u"Test Test ä"
def exception3():
raise ValueError, u"Test Test"
def exception4():
raise ValueError, "Test Test"
app = QtGui.QApplication([])
sys.excepthook = excepthook
widget = QtGui.QPushButton("raise exceptions")
widget.move(100, 100)
widget.resize(100, 100)
widget.show()
<|code_end|>
, predict the immediate next line with the help of imports:
from pandasqt.compat import Qt, QtCore, QtGui
from pandasqt.excepthook import excepthook
import pytest
import pytestqt
import sys
and context (classes, functions, sometimes code) from other files:
# Path: pandasqt/compat.py
#
# Path: pandasqt/excepthook.py
# def excepthook(excType, excValue, tracebackobj):
# """
# Global function to catch unhandled exceptions.
#
# @param excType exception type
# @param excValue exception value
# @param tracebackobj traceback object
# """
# separator = u'-' * 80
#
# logFile = os.path.join(tempfile.gettempdir(), "error.log")
# notice = """An unhandled exception occurred. Please report the problem.\n"""
# notice += """A log has been written to "{}".\n\nError information:""".format(logFile)
# timeString = time.strftime("%Y-%m-%d, %H:%M:%S")
#
# tbinfofile = cStringIO.StringIO()
# traceback.print_tb(tracebackobj, None, tbinfofile)
# tbinfofile.seek(0)
# tbinfo = tbinfofile.read()
# tbinfo = tbinfo.decode('utf-8')
#
# try:
# excValueStr = str(excValue).decode('utf-8')
# except UnicodeEncodeError, e:
# excValueStr = unicode(excValue)
#
# errmsg = u'{0}: \n{1}'.format(excType, excValueStr)
# sections = [u'\n', separator, timeString, separator, errmsg, separator, tbinfo]
# msg = u'\n'.join(sections)
# try:
# f = codecs.open(logFile, "a+", encoding='utf-8')
# f.write(msg)
# f.close()
# except IOError, e:
# msgbox(u"unable to write to {0}".format(logFile), u"Writing error")
#
# # always show an error message
# try:
# if not _isQAppRunning():
# app = QtGui.QApplication([])
# _showMessageBox(unicode(notice) + unicode(msg))
# except:
# msgbox(unicode(notice) + unicode(msg), u"Error")
. Output only the next line. | widget.clicked.connect(exception) |
Given the following code snippet before the placeholder: <|code_start|> self._addedBars = 0
self._minHeight = 50
self._width = parent.width() * 0.38
self._margin = margin
self._totalProgress = 0
self.initUi()
for worker in workers:
self._addProgressBar(worker)
def initUi(self):
self.sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Expanding)
self._pbHeight = 30
self.setMinimumWidth(self._width)
#self.setMaximumWidth(self._width)
self.setMinimumHeight(self._minHeight)
self.glayout = QtGui.QGridLayout(self)
self.totalProgressBar = QtGui.QProgressBar(self)
self.totalProgressBar.setMinimumHeight(self._pbHeight)
self.totalProgressBar.setMaximumHeight(self._pbHeight)
self.toggleButton = QtGui.QPushButton('Details', self)
self.toggleButton.setCheckable(True)
self.toggleButton.toggled.connect(self.showDetails)
<|code_end|>
, predict the next line using imports from the current file:
from pandasqt.compat import QtCore, QtGui, Qt, Signal, Slot
and context including class names, function names, and sometimes code from other files:
# Path: pandasqt/compat.py
. Output only the next line. | self.glayout.addWidget(self.totalProgressBar, 0, 0, 1, 1) |
Here is a snippet: <|code_start|>
class OverlayProgressWidget(QtGui.QFrame):
def __init__(self, parent, workers=[], debug=True, margin=0):
super(OverlayProgressWidget, self).__init__(parent)
self._debug = debug
self._workers = workers
self._detailProgressBars = []
self._addedBars = 0
self._minHeight = 50
self._width = parent.width() * 0.38
<|code_end|>
. Write the next line using the current file imports:
from pandasqt.compat import QtCore, QtGui, Qt, Signal, Slot
and context from other files:
# Path: pandasqt/compat.py
, which may include functions, classes, or code. Output only the next line. | self._margin = margin |
Given snippet: <|code_start|> separator = u'-' * 80
logFile = os.path.join(tempfile.gettempdir(), "error.log")
notice = """An unhandled exception occurred. Please report the problem.\n"""
notice += """A log has been written to "{}".\n\nError information:""".format(logFile)
timeString = time.strftime("%Y-%m-%d, %H:%M:%S")
tbinfofile = cStringIO.StringIO()
traceback.print_tb(tracebackobj, None, tbinfofile)
tbinfofile.seek(0)
tbinfo = tbinfofile.read()
tbinfo = tbinfo.decode('utf-8')
try:
excValueStr = str(excValue).decode('utf-8')
except UnicodeEncodeError, e:
excValueStr = unicode(excValue)
errmsg = u'{0}: \n{1}'.format(excType, excValueStr)
sections = [u'\n', separator, timeString, separator, errmsg, separator, tbinfo]
msg = u'\n'.join(sections)
try:
f = codecs.open(logFile, "a+", encoding='utf-8')
f.write(msg)
f.close()
except IOError, e:
msgbox(u"unable to write to {0}".format(logFile), u"Writing error")
# always show an error message
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
import cStringIO
import traceback
import codecs
import os
import tempfile
from pandasqt.compat import QtGui
from easygui.boxes.derived_boxes import msgbox
and context:
# Path: pandasqt/compat.py
which might include code, classes, or functions. Output only the next line. | if not _isQAppRunning(): |
Given the following code snippet before the placeholder: <|code_start|>
class ProgressWorker(QtCore.QObject):
progressChanged = Signal(int) # set value of OverlayProgressView
finished = Signal()
<|code_end|>
, predict the next line using imports from the current file:
from pandasqt.compat import QtCore, QtGui, Qt, Signal, Slot
and context including class names, function names, and sometimes code from other files:
# Path: pandasqt/compat.py
. Output only the next line. | def __init__(self, name): |
Given the code snippet: <|code_start|>
class ProgressWorker(QtCore.QObject):
progressChanged = Signal(int) # set value of OverlayProgressView
finished = Signal()
<|code_end|>
, generate the next line using the imports in this file:
from pandasqt.compat import QtCore, QtGui, Qt, Signal, Slot
and context (functions, classes, or occasionally code) from other files:
# Path: pandasqt/compat.py
. Output only the next line. | def __init__(self, name): |
Continue the code snippet: <|code_start|>
class ProgressWorker(QtCore.QObject):
progressChanged = Signal(int) # set value of OverlayProgressView
finished = Signal()
<|code_end|>
. Use current file imports:
from pandasqt.compat import QtCore, QtGui, Qt, Signal, Slot
and context (classes, functions, or code) from other files:
# Path: pandasqt/compat.py
. Output only the next line. | def __init__(self, name): |
Given the code snippet: <|code_start|>from __future__ import with_statement
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = model.Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
<|code_end|>
, generate the next line using the imports in this file:
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
from whyattend import model
import sys; sys.path.append(".")
and context (functions, classes, or occasionally code) from other files:
# Path: whyattend/model.py
# def init_db():
# def __init__(self, wot_id, openid, member_since, name, clan, role, locked=False):
# def is_recruit(self):
# def battles_played(self):
# def battles_reserve(self):
# def __repr__(self):
# def to_dict(self):
# def player_role_value(self):
# def __init__(self, player, battle, reserve=False):
# def __init__(self, date, clan, enemy_clan, victory, draw, creator, battle_commander, map_name, map_province,
# duration, description='', paid=False):
# def outcome_str(self):
# def outcome_repr(self):
# def has_player(self, player):
# def has_reserve(self, player):
# def get_players(self):
# def get_reserve_players(self):
# def __str__(self):
# def __init__(self, title, description, clan, date):
# def get_players(self):
# def get_reserves(self):
# def get_final_battle(self):
# def get_representative_battle(self):
# def __init__(self, replay_blob, replay_pickle):
# def unpickle(self):
# def get(cls):
# class Player(Base):
# class BattleAttendance(Base):
# class Battle(Base):
# class BattleGroup(Base):
# class Replay(Base):
# class WebappData(Base):
. Output only the next line. | def run_migrations_offline(): |
Based on the snippet: <|code_start|>
# noinspection PyUnusedLocal
@app.teardown_appcontext
def shutdown_session(exception=None):
"""Remove the database session at the end of the request or when the application shuts down.
This is needed to use SQLAlchemy in a declarative way."""
db_session.remove()
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()
return session['_csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf_token
# decorates a decorator function to be able to specify parameters :-)
decorator_with_args = lambda decorator: lambda *args, **kwargs: \
lambda func: decorator(func, *args, **kwargs)
@app.before_request
def lookup_current_user():
g.player = None
if 'openid' in session:
# Checking if player exists for every request might be overkill
g.player = Player.query.filter_by(openid=session.get('openid')).first()
<|code_end|>
, predict the immediate next line with the help of imports:
import csv
import datetime
import os
import pickle
import logging
import hashlib
import tarfile
import calendar
import jinja2
import calendar
import hashlib
from cStringIO import StringIO
from collections import defaultdict, OrderedDict
from functools import wraps
from datetime import timedelta
from flask import Flask, g, session, render_template, flash, redirect, request, url_for, abort, make_response, jsonify
from flask import Response
from flask_openid import OpenID
from flask_cache import Cache
from sqlalchemy import or_, and_, alias
from sqlalchemy.orm import joinedload, joinedload_all
from werkzeug.utils import secure_filename, Headers
from pytz import timezone
from . import config, replays, wotapi, util, constants, analysis
from .model import Player, Battle, BattleAttendance, Replay, BattleGroup, db_session, WebappData
from logging.handlers import RotatingFileHandler
from logging.handlers import RotatingFileHandler
from sqlalchemy import case, desc, asc, select, func, literal
from datetime import timedelta
and context (classes, functions, sometimes code) from other files:
# Path: whyattend/model.py
# def init_db():
# def __init__(self, wot_id, openid, member_since, name, clan, role, locked=False):
# def is_recruit(self):
# def battles_played(self):
# def battles_reserve(self):
# def __repr__(self):
# def to_dict(self):
# def player_role_value(self):
# def __init__(self, player, battle, reserve=False):
# def __init__(self, date, clan, enemy_clan, victory, draw, creator, battle_commander, map_name, map_province,
# duration, description='', paid=False):
# def outcome_str(self):
# def outcome_repr(self):
# def has_player(self, player):
# def has_reserve(self, player):
# def get_players(self):
# def get_reserve_players(self):
# def __str__(self):
# def __init__(self, title, description, clan, date):
# def get_players(self):
# def get_reserves(self):
# def get_final_battle(self):
# def get_representative_battle(self):
# def __init__(self, replay_blob, replay_pickle):
# def unpickle(self):
# def get(cls):
# class Player(Base):
# class BattleAttendance(Base):
# class Battle(Base):
# class BattleGroup(Base):
# class Replay(Base):
# class WebappData(Base):
. Output only the next line. | if g.player and g.player.locked: |
Using the snippet: <|code_start|>if config.LOG_FILE:
file_handler = RotatingFileHandler(config.LOG_FILE, maxBytes=5 * 1024 * 1024, backupCount=5)
file_handler.setLevel(logging.INFO)
logger.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s '))
logger.addHandler(file_handler)
@app.before_request
def csrf_protect():
if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
flash('Invalid CSRF token. Please try again or contact an administrator for help.')
return redirect(url_for('index'))
# noinspection PyUnusedLocal
@app.teardown_appcontext
def shutdown_session(exception=None):
"""Remove the database session at the end of the request or when the application shuts down.
This is needed to use SQLAlchemy in a declarative way."""
db_session.remove()
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()
<|code_end|>
, determine the next line of code. You have imports:
import csv
import datetime
import os
import pickle
import logging
import hashlib
import tarfile
import calendar
import jinja2
import calendar
import hashlib
from cStringIO import StringIO
from collections import defaultdict, OrderedDict
from functools import wraps
from datetime import timedelta
from flask import Flask, g, session, render_template, flash, redirect, request, url_for, abort, make_response, jsonify
from flask import Response
from flask_openid import OpenID
from flask_cache import Cache
from sqlalchemy import or_, and_, alias
from sqlalchemy.orm import joinedload, joinedload_all
from werkzeug.utils import secure_filename, Headers
from pytz import timezone
from . import config, replays, wotapi, util, constants, analysis
from .model import Player, Battle, BattleAttendance, Replay, BattleGroup, db_session, WebappData
from logging.handlers import RotatingFileHandler
from logging.handlers import RotatingFileHandler
from sqlalchemy import case, desc, asc, select, func, literal
from datetime import timedelta
and context (class names, function names, or code) available:
# Path: whyattend/model.py
# def init_db():
# def __init__(self, wot_id, openid, member_since, name, clan, role, locked=False):
# def is_recruit(self):
# def battles_played(self):
# def battles_reserve(self):
# def __repr__(self):
# def to_dict(self):
# def player_role_value(self):
# def __init__(self, player, battle, reserve=False):
# def __init__(self, date, clan, enemy_clan, victory, draw, creator, battle_commander, map_name, map_province,
# duration, description='', paid=False):
# def outcome_str(self):
# def outcome_repr(self):
# def has_player(self, player):
# def has_reserve(self, player):
# def get_players(self):
# def get_reserve_players(self):
# def __str__(self):
# def __init__(self, title, description, clan, date):
# def get_players(self):
# def get_reserves(self):
# def get_final_battle(self):
# def get_representative_battle(self):
# def __init__(self, replay_blob, replay_pickle):
# def unpickle(self):
# def get(cls):
# class Player(Base):
# class BattleAttendance(Base):
# class Battle(Base):
# class BattleGroup(Base):
# class Replay(Base):
# class WebappData(Base):
. Output only the next line. | return session['_csrf_token'] |
Here is a snippet: <|code_start|>logger = logging.getLogger(__name__)
if config.LOG_FILE:
file_handler = RotatingFileHandler(config.LOG_FILE, maxBytes=5 * 1024 * 1024, backupCount=5)
file_handler.setLevel(logging.INFO)
logger.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s '))
logger.addHandler(file_handler)
@app.before_request
def csrf_protect():
if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
flash('Invalid CSRF token. Please try again or contact an administrator for help.')
return redirect(url_for('index'))
# noinspection PyUnusedLocal
@app.teardown_appcontext
def shutdown_session(exception=None):
"""Remove the database session at the end of the request or when the application shuts down.
This is needed to use SQLAlchemy in a declarative way."""
db_session.remove()
def generate_csrf_token():
if '_csrf_token' not in session:
<|code_end|>
. Write the next line using the current file imports:
import csv
import datetime
import os
import pickle
import logging
import hashlib
import tarfile
import calendar
import jinja2
import calendar
import hashlib
from cStringIO import StringIO
from collections import defaultdict, OrderedDict
from functools import wraps
from datetime import timedelta
from flask import Flask, g, session, render_template, flash, redirect, request, url_for, abort, make_response, jsonify
from flask import Response
from flask_openid import OpenID
from flask_cache import Cache
from sqlalchemy import or_, and_, alias
from sqlalchemy.orm import joinedload, joinedload_all
from werkzeug.utils import secure_filename, Headers
from pytz import timezone
from . import config, replays, wotapi, util, constants, analysis
from .model import Player, Battle, BattleAttendance, Replay, BattleGroup, db_session, WebappData
from logging.handlers import RotatingFileHandler
from logging.handlers import RotatingFileHandler
from sqlalchemy import case, desc, asc, select, func, literal
from datetime import timedelta
and context from other files:
# Path: whyattend/model.py
# def init_db():
# def __init__(self, wot_id, openid, member_since, name, clan, role, locked=False):
# def is_recruit(self):
# def battles_played(self):
# def battles_reserve(self):
# def __repr__(self):
# def to_dict(self):
# def player_role_value(self):
# def __init__(self, player, battle, reserve=False):
# def __init__(self, date, clan, enemy_clan, victory, draw, creator, battle_commander, map_name, map_province,
# duration, description='', paid=False):
# def outcome_str(self):
# def outcome_repr(self):
# def has_player(self, player):
# def has_reserve(self, player):
# def get_players(self):
# def get_reserve_players(self):
# def __str__(self):
# def __init__(self, title, description, clan, date):
# def get_players(self):
# def get_reserves(self):
# def get_final_battle(self):
# def get_representative_battle(self):
# def __init__(self, replay_blob, replay_pickle):
# def unpickle(self):
# def get(cls):
# class Player(Base):
# class BattleAttendance(Base):
# class Battle(Base):
# class BattleGroup(Base):
# class Replay(Base):
# class WebappData(Base):
, which may include functions, classes, or code. Output only the next line. | session['_csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest() |
Predict the next line after this snippet: <|code_start|> db_session.remove()
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()
return session['_csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf_token
# decorates a decorator function to be able to specify parameters :-)
decorator_with_args = lambda decorator: lambda *args, **kwargs: \
lambda func: decorator(func, *args, **kwargs)
@app.before_request
def lookup_current_user():
g.player = None
if 'openid' in session:
# Checking if player exists for every request might be overkill
g.player = Player.query.filter_by(openid=session.get('openid')).first()
if g.player and g.player.locked:
g.player = None
session.pop('openid', None)
# noinspection PyPep8Naming
@app.before_request
<|code_end|>
using the current file's imports:
import csv
import datetime
import os
import pickle
import logging
import hashlib
import tarfile
import calendar
import jinja2
import calendar
import hashlib
from cStringIO import StringIO
from collections import defaultdict, OrderedDict
from functools import wraps
from datetime import timedelta
from flask import Flask, g, session, render_template, flash, redirect, request, url_for, abort, make_response, jsonify
from flask import Response
from flask_openid import OpenID
from flask_cache import Cache
from sqlalchemy import or_, and_, alias
from sqlalchemy.orm import joinedload, joinedload_all
from werkzeug.utils import secure_filename, Headers
from pytz import timezone
from . import config, replays, wotapi, util, constants, analysis
from .model import Player, Battle, BattleAttendance, Replay, BattleGroup, db_session, WebappData
from logging.handlers import RotatingFileHandler
from logging.handlers import RotatingFileHandler
from sqlalchemy import case, desc, asc, select, func, literal
from datetime import timedelta
and any relevant context from other files:
# Path: whyattend/model.py
# def init_db():
# def __init__(self, wot_id, openid, member_since, name, clan, role, locked=False):
# def is_recruit(self):
# def battles_played(self):
# def battles_reserve(self):
# def __repr__(self):
# def to_dict(self):
# def player_role_value(self):
# def __init__(self, player, battle, reserve=False):
# def __init__(self, date, clan, enemy_clan, victory, draw, creator, battle_commander, map_name, map_province,
# duration, description='', paid=False):
# def outcome_str(self):
# def outcome_repr(self):
# def has_player(self, player):
# def has_reserve(self, player):
# def get_players(self):
# def get_reserve_players(self):
# def __str__(self):
# def __init__(self, title, description, clan, date):
# def get_players(self):
# def get_reserves(self):
# def get_final_battle(self):
# def get_representative_battle(self):
# def __init__(self, replay_blob, replay_pickle):
# def unpickle(self):
# def get(cls):
# class Player(Base):
# class BattleAttendance(Base):
# class Battle(Base):
# class BattleGroup(Base):
# class Replay(Base):
# class WebappData(Base):
. Output only the next line. | def inject_constants(): |
Given the code snippet: <|code_start|>
response = make_response(buf.getvalue())
response.headers['Content-Type'] = 'application/tar'
response.headers['Content-Disposition'] = 'attachment; filename=' + secure_filename("replays.tar")
return response
@app.route('/payout/<clan>')
@require_login
@require_role(config.PAYOUT_ROLES)
@require_clan_membership
def payout(clan):
"""
Payout date range and battle selection page.
:param clan:
:return:
"""
return render_template('payout/payout.html', clan=clan)
@app.route('/payout/reserve-conflicts/<clan>')
@require_login
@require_role(config.PAYOUT_ROLES)
@require_clan_membership
def reserve_conflicts(clan):
# noinspection PyShadowingNames
def overlapping_battles(battle, ordered_battles, before_dt=timedelta(minutes=0), after_dt=timedelta(minutes=0)):
""" Return a list of battles b whose start time lies within the interval
[battle.date - before_dt, battle.date + battle.duration + after_dt].
Such battles overlap with the given battle. """
<|code_end|>
, generate the next line using the imports in this file:
import csv
import datetime
import os
import pickle
import logging
import hashlib
import tarfile
import calendar
import jinja2
import calendar
import hashlib
from cStringIO import StringIO
from collections import defaultdict, OrderedDict
from functools import wraps
from datetime import timedelta
from flask import Flask, g, session, render_template, flash, redirect, request, url_for, abort, make_response, jsonify
from flask import Response
from flask_openid import OpenID
from flask_cache import Cache
from sqlalchemy import or_, and_, alias
from sqlalchemy.orm import joinedload, joinedload_all
from werkzeug.utils import secure_filename, Headers
from pytz import timezone
from . import config, replays, wotapi, util, constants, analysis
from .model import Player, Battle, BattleAttendance, Replay, BattleGroup, db_session, WebappData
from logging.handlers import RotatingFileHandler
from logging.handlers import RotatingFileHandler
from sqlalchemy import case, desc, asc, select, func, literal
from datetime import timedelta
and context (functions, classes, or occasionally code) from other files:
# Path: whyattend/model.py
# def init_db():
# def __init__(self, wot_id, openid, member_since, name, clan, role, locked=False):
# def is_recruit(self):
# def battles_played(self):
# def battles_reserve(self):
# def __repr__(self):
# def to_dict(self):
# def player_role_value(self):
# def __init__(self, player, battle, reserve=False):
# def __init__(self, date, clan, enemy_clan, victory, draw, creator, battle_commander, map_name, map_province,
# duration, description='', paid=False):
# def outcome_str(self):
# def outcome_repr(self):
# def has_player(self, player):
# def has_reserve(self, player):
# def get_players(self):
# def get_reserve_players(self):
# def __str__(self):
# def __init__(self, title, description, clan, date):
# def get_players(self):
# def get_reserves(self):
# def get_final_battle(self):
# def get_representative_battle(self):
# def __init__(self, replay_blob, replay_pickle):
# def unpickle(self):
# def get(cls):
# class Player(Base):
# class BattleAttendance(Base):
# class Battle(Base):
# class BattleGroup(Base):
# class Replay(Base):
# class WebappData(Base):
. Output only the next line. | return [b for b in ordered_battles if battle.date - before_dt <= b.date <= |
Here is a snippet: <|code_start|> if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
flash('Invalid CSRF token. Please try again or contact an administrator for help.')
return redirect(url_for('index'))
# noinspection PyUnusedLocal
@app.teardown_appcontext
def shutdown_session(exception=None):
"""Remove the database session at the end of the request or when the application shuts down.
This is needed to use SQLAlchemy in a declarative way."""
db_session.remove()
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()
return session['_csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf_token
# decorates a decorator function to be able to specify parameters :-)
decorator_with_args = lambda decorator: lambda *args, **kwargs: \
lambda func: decorator(func, *args, **kwargs)
@app.before_request
<|code_end|>
. Write the next line using the current file imports:
import csv
import datetime
import os
import pickle
import logging
import hashlib
import tarfile
import calendar
import jinja2
import calendar
import hashlib
from cStringIO import StringIO
from collections import defaultdict, OrderedDict
from functools import wraps
from datetime import timedelta
from flask import Flask, g, session, render_template, flash, redirect, request, url_for, abort, make_response, jsonify
from flask import Response
from flask_openid import OpenID
from flask_cache import Cache
from sqlalchemy import or_, and_, alias
from sqlalchemy.orm import joinedload, joinedload_all
from werkzeug.utils import secure_filename, Headers
from pytz import timezone
from . import config, replays, wotapi, util, constants, analysis
from .model import Player, Battle, BattleAttendance, Replay, BattleGroup, db_session, WebappData
from logging.handlers import RotatingFileHandler
from logging.handlers import RotatingFileHandler
from sqlalchemy import case, desc, asc, select, func, literal
from datetime import timedelta
and context from other files:
# Path: whyattend/model.py
# def init_db():
# def __init__(self, wot_id, openid, member_since, name, clan, role, locked=False):
# def is_recruit(self):
# def battles_played(self):
# def battles_reserve(self):
# def __repr__(self):
# def to_dict(self):
# def player_role_value(self):
# def __init__(self, player, battle, reserve=False):
# def __init__(self, date, clan, enemy_clan, victory, draw, creator, battle_commander, map_name, map_province,
# duration, description='', paid=False):
# def outcome_str(self):
# def outcome_repr(self):
# def has_player(self, player):
# def has_reserve(self, player):
# def get_players(self):
# def get_reserve_players(self):
# def __str__(self):
# def __init__(self, title, description, clan, date):
# def get_players(self):
# def get_reserves(self):
# def get_final_battle(self):
# def get_representative_battle(self):
# def __init__(self, replay_blob, replay_pickle):
# def unpickle(self):
# def get(cls):
# class Player(Base):
# class BattleAttendance(Base):
# class Battle(Base):
# class BattleGroup(Base):
# class Replay(Base):
# class WebappData(Base):
, which may include functions, classes, or code. Output only the next line. | def lookup_current_user(): |
Based on the snippet: <|code_start|> db_session.remove()
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()
return session['_csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf_token
# decorates a decorator function to be able to specify parameters :-)
decorator_with_args = lambda decorator: lambda *args, **kwargs: \
lambda func: decorator(func, *args, **kwargs)
@app.before_request
def lookup_current_user():
g.player = None
if 'openid' in session:
# Checking if player exists for every request might be overkill
g.player = Player.query.filter_by(openid=session.get('openid')).first()
if g.player and g.player.locked:
g.player = None
session.pop('openid', None)
# noinspection PyPep8Naming
@app.before_request
<|code_end|>
, predict the immediate next line with the help of imports:
import csv
import datetime
import os
import pickle
import logging
import hashlib
import tarfile
import calendar
import jinja2
import calendar
import hashlib
from cStringIO import StringIO
from collections import defaultdict, OrderedDict
from functools import wraps
from datetime import timedelta
from flask import Flask, g, session, render_template, flash, redirect, request, url_for, abort, make_response, jsonify
from flask import Response
from flask_openid import OpenID
from flask_cache import Cache
from sqlalchemy import or_, and_, alias
from sqlalchemy.orm import joinedload, joinedload_all
from werkzeug.utils import secure_filename, Headers
from pytz import timezone
from . import config, replays, wotapi, util, constants, analysis
from .model import Player, Battle, BattleAttendance, Replay, BattleGroup, db_session, WebappData
from logging.handlers import RotatingFileHandler
from logging.handlers import RotatingFileHandler
from sqlalchemy import case, desc, asc, select, func, literal
from datetime import timedelta
and context (classes, functions, sometimes code) from other files:
# Path: whyattend/model.py
# def init_db():
# def __init__(self, wot_id, openid, member_since, name, clan, role, locked=False):
# def is_recruit(self):
# def battles_played(self):
# def battles_reserve(self):
# def __repr__(self):
# def to_dict(self):
# def player_role_value(self):
# def __init__(self, player, battle, reserve=False):
# def __init__(self, date, clan, enemy_clan, victory, draw, creator, battle_commander, map_name, map_province,
# duration, description='', paid=False):
# def outcome_str(self):
# def outcome_repr(self):
# def has_player(self, player):
# def has_reserve(self, player):
# def get_players(self):
# def get_reserve_players(self):
# def __str__(self):
# def __init__(self, title, description, clan, date):
# def get_players(self):
# def get_reserves(self):
# def get_final_battle(self):
# def get_representative_battle(self):
# def __init__(self, replay_blob, replay_pickle):
# def unpickle(self):
# def get(cls):
# class Player(Base):
# class BattleAttendance(Base):
# class Battle(Base):
# class BattleGroup(Base):
# class Replay(Base):
# class WebappData(Base):
. Output only the next line. | def inject_constants(): |
Here is a snippet: <|code_start|> "exists": False
},
{
"challenge": 40,
"step": 1
},
{
"challenge": 42,
"step": 1,
"exists": False
}
]
}
]
}
woods = {
"name": "woods",
"challenges": [
{
"challenge": 0,
"step": 1,
"exists": False
},
{
"challenge": 32,
"step": 1
}
],
<|code_end|>
. Write the next line using the current file imports:
from cave import cave
from clearing import clearing
from rabbithole import rabbithole
from linux_story.common import get_story_file
and context from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
, which may include functions, classes, or code. Output only the next line. | "children": [ |
Using the snippet: <|code_start|>chest = {
"name": ".chest",
"challenges": [
{
"challenge": 15,
"step": 1
}
],
"children": [
{
"name": "CAT",
"contents": get_story_file("CAT")
},
{
"name": "CD",
"contents": get_story_file("CD")
},
{
"name": "LS",
"contents": get_story_file("LS")
},
{
"name": ".note",
"contents": get_story_file(".note")
}
]
}
my_room = {
"name": "my-room",
<|code_end|>
, determine the next line of code. You have imports:
from linux_story.common import get_story_file
and context (class names, function names, or code) available:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
. Output only the next line. | "children": [ |
Continue the code snippet: <|code_start|># challenge_24.py
#
# Copyright (C) 2014-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# A chapter of the story
# ----------------------------------------------------------------------------------------
class Step1(StepTemplateMkdir):
story = [
_("You walk down the narrow road, with {{bb:Eleanor}} dancing " +\
"alongside, until you reach an open space in the " +\
"{{bb:east}} part of town."),
_("\n{{lb:Look around.}}")
]
commands = [
"ls",
"ls -a"
]
start_dir = "~/town/east"
end_dir = "~/town/east"
hints = [
<|code_end|>
. Use current file imports:
from linux_story.step_helper_functions import unblock_cd_commands
from linux_story.story.challenges.CompanionMisc import StepTemplateMkdir
and context (classes, functions, or code) from other files:
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
#
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateMkdir(StepTemplateEleanorBernard):
# TerminalClass = TerminalMkdirBernard
. Output only the next line. | _("{{rb:Look around with}} {{yb:ls}}{{rb:.}}") |
Based on the snippet: <|code_start|> _("{{rb:Look around with}} {{yb:ls}}{{rb:.}}")
]
deleted_items = ["~/town/Eleanor"]
file_list = [{"path": "~/town/east/Eleanor"}]
companion_speech = _("Eleanor: {{Bb:I can't see my parents anywhere...but there's a weird building there.}}")
def next(self):
return 24, 2
class Step2(StepTemplateMkdir):
story = [
_("You see a {{bb:shed-shop}}, {{bb:library}} and {{bb:restaurant}}."),
_("\nEleanor: {{Bb:\"Hey, what is that shed-shop?\"}}\n"),
_("{{Bb:\"Let's}} {{lb:go in}}{{Bb:!\"}}")
]
start_dir = "~/town/east"
end_dir = "~/town/east/shed-shop"
hints = [
_("{{rb:Use}} {{yb:cd shed-shop}} {{rb:to go in the shed-shop.}}")
]
companion_speech = _("Eleanor: {{Bb:Do you think they sell candy?}}")
def block_command(self, line):
return unblock_cd_commands(line)
def next(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from linux_story.step_helper_functions import unblock_cd_commands
from linux_story.story.challenges.CompanionMisc import StepTemplateMkdir
and context (classes, functions, sometimes code) from other files:
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
#
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateMkdir(StepTemplateEleanorBernard):
# TerminalClass = TerminalMkdirBernard
. Output only the next line. | return 24, 3 |
Given snippet: <|code_start|>
hints = [
_("{{rb:Use}} {{yb:cd library}} {{rb:to go inside the library.}}")
]
companion_speech = _("Eleanor: {{Bb:I love the library! Let's go inside!}}")
def block_command(self, line):
return unblock_cd_commands(line)
def next(self):
return 26, 3
class Step3(StepTemplateMkdir):
story = [
_("{{bb:Eleanor}} skips into the {{bb:library}}, while you follow her.\n"),
_("{{lb:Look around}} the {{bb:library}}.")
]
start_dir = "~/town/east/library"
end_dir = "~/town/east/library"
hints = [
_("{{rb:Use}} {{yb:ls}} {{rb:to look around.}}")
]
commands = [
"ls",
"ls -a"
]
deleted_items = ["~/town/east/Eleanor"]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from linux_story.story.challenges.CompanionMisc import StepTemplateMkdir
from linux_story.common import get_story_file
from linux_story.step_helper_functions import unblock_cd_commands
and context:
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateMkdir(StepTemplateEleanorBernard):
# TerminalClass = TerminalMkdirBernard
#
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
#
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
which might include code, classes, or functions. Output only the next line. | file_list = [ |
Given the following code snippet before the placeholder: <|code_start|>
_("{{Bb:\"What is that}} {{lb:NANO}} {{Bb:paper?\"}}\n"),
_("{{Bb:\"Let's}} {{lb:examine}} {{Bb:it.\"}}")
]
start_dir = "~/town/east/library"
end_dir = "~/town/east/library"
commands = [
"cat public-section/NANO"
]
hints = [
_("{{rb:Examine the NANO script with}} {{yb:cat public-section/NANO}}")
]
companion_speech = (
_("Eleanor: {{Bb:The library should probably have introduced late " +\
"fees.}}")
)
def next(self):
return 26, 7
class Step7(StepTemplateMkdir):
story = [
_("Eleanor: {{Bb:\"So nano allows you to edit files?}}"),
_("{{Bb:Maybe we could use this to fix that}} " +\
"{{yb:best-horn-in-the-world.sh}} {{Bb:script?\"}}\n"),
_("{{Bb:\"Let's}} {{lb:head back}} {{Bb:to the}} {{bb:shed-shop}}{{Bb:.\"}}")
]
<|code_end|>
, predict the next line using imports from the current file:
from linux_story.story.challenges.CompanionMisc import StepTemplateMkdir
from linux_story.common import get_story_file
from linux_story.step_helper_functions import unblock_cd_commands
and context including class names, function names, and sometimes code from other files:
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateMkdir(StepTemplateEleanorBernard):
# TerminalClass = TerminalMkdirBernard
#
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
#
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
. Output only the next line. | start_dir = "~/town/east/library" |
Given the code snippet: <|code_start|> commands = [
"ls",
"ls -a"
]
deleted_items = ["~/town/east/Eleanor"]
file_list = [
{
"path": "~/town/east/library/Eleanor",
"contents": get_story_file("Eleanor")
}
]
companion_speech = _("Eleanor: {{Bb:It's all echo-y-y-y-y..}}")
def next(self):
return 26, 4
class Step4(StepTemplateMkdir):
story = [
_("You're in a corridor leading to two clearly " +\
"labelled doors. " +\
"One has the sign {{bb:public-section}}, the other " +\
"{{bb:private-section}}.\n"),
_("Eleanor: {{Bb:\"There used to be a librarian here."),
_("She would tell me off for trying to look in the}} " +\
"{{bb:private-section}}."),
_("{{Bb:What do you think is in there? Let's try and}} " +\
<|code_end|>
, generate the next line using the imports in this file:
from linux_story.story.challenges.CompanionMisc import StepTemplateMkdir
from linux_story.common import get_story_file
from linux_story.step_helper_functions import unblock_cd_commands
and context (functions, classes, or occasionally code) from other files:
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateMkdir(StepTemplateEleanorBernard):
# TerminalClass = TerminalMkdirBernard
#
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
#
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
. Output only the next line. | "{{lb:look inside}}{{Bb:.\"}}") |
Using the snippet: <|code_start|> "step": 1,
"exists": False
},
{
"challenge": 13,
"step": 2
},
{
"challenge": 13,
"step": 5,
"exists": False
},
{
"challenge": 14,
"step": 4
},
{
"challenge": 14,
"step": 5,
"exists": False
}
],
"children": [
{
"name": "banana",
"contents": get_story_file("banana"),
"challenges": [
{
"challenge": 14,
"step": 4
<|code_end|>
, determine the next line of code. You have imports:
from farm import farm
from linux_story.common import get_story_file
from my_house import my_house
from woods import woods
from town import town
and context (class names, function names, or code) available:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
. Output only the next line. | } |
Predict the next line after this snippet: <|code_start|>
class PlayerLocation:
def __init__(self, start_dir, end_dir):
self.__fake_path = start_dir
self.__end_dir = end_dir
def get_fake_path(self):
return self.__fake_path
def get_real_path(self):
return generate_real_path(self.__fake_path)
<|code_end|>
using the current file's imports:
from linux_story.common import fake_home_dir
and any relevant context from other files:
# Path: linux_story/common.py
# def get_max_challenge_number():
# def get_username():
# def get_story_file(name):
. Output only the next line. | def set_fake_path(self, fake_path): |
Predict the next line after this snippet: <|code_start|> "step": 6,
"exists": False
},
{
"challenge": 12,
"step": 1
},
{
"challenge": 23,
"step": 4,
"exists": False
}
]
}
dog_hidden_shelter = {
"name": "dog",
"contents": get_story_file("dog"),
"challenges": [
{
"challenge": 10,
"step": 1
},
{
"challenge": 11,
"step": 6,
"exists": False
},
{
"challenge": 12,
<|code_end|>
using the current file's imports:
from linux_story.common import get_story_file
and any relevant context from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
. Output only the next line. | "step": 2 |
Predict the next line for this snippet: <|code_start|> "challenges": [
{
"challenge": 21,
"step": 10
}
]
}
]
},
{
"name": "farmhouse",
"children": [
{
"name": "bed",
"contents": get_story_file("bed_farmhouse")
}
]
},
{
"name": "toolshed",
"children": [
{
"name": "MKDIR",
"contents": get_story_file("MKDIR")
},
{
"name": "spanner",
"contents": get_story_file("spanner")
},
{
<|code_end|>
with the help of current file imports:
from linux_story.common import get_story_file
and context from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
, which may contain function names, class names, or code. Output only the next line. | "name": "hammer", |
Using the snippet: <|code_start|> {
"user": _("\"Why don't you like Bernard?\""),
"clara": \
_("Clara: {{Bb:\"He makes very simple tools and charges a fortune " +\
"for them.}}" +\
"\n{{Bb:His father was a very clever man and spent all " +\
"his time in the library reading up commands. He became a " +\
"successful business man as a result.\"}}")
},
{
"user": _("\"What happened to Bernard's father?\""),
"clara": \
_("Clara: {{Bb:\"People aren't sure, he disappeared one day. " +\
"It was " +\
"assumed he had died. I saw him leave the library the day " +\
"he went missing, " +\
"he left in a hurry. He looked absolutely terrified.\"}}")
}
]
}
# Generate the story from the step number
def create_story(step):
print_text = ""
if step > 1:
print_text = _("{{yb:%s}}") % story_replies["echo 1"][step - 2]["user"]
story = [
<|code_end|>
, determine the next line of code. You have imports:
import os
from linux_story.story.challenges.CompanionMisc import StepTemplateNano
from linux_story.helper_functions import record_user_interaction
and context (class names, function names, or code) available:
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateNano(StepTemplateEleanorBernard):
# TerminalClass = TerminalNanoBernard
#
# Path: linux_story/helper_functions.py
# def record_user_interaction(instance, base_name):
# """
# This is to store some of the user actions, so we can determine
# if the user does the optional side quests.
#
# Args:
# The class instance.
# base_name (str): a string for the identity of the command.
# """
#
# class_instance = instance.__class__.__name__
# challenge_number = instance.__module__.split("_")[-1]
# profile_var_name = "{} {} {}".format(
# base_name, challenge_number, class_instance
# )
#
# # First, try loading the profile variable name
# # If the value is None, then make it True and increment the total.
# already_done = load_app_state_variable("linux-story", profile_var_name)
#
# # If the command has not been done yet in this class, then increment the
# # total
# if not already_done:
# save_app_state_variable("linux-story", profile_var_name, True)
# total_name = "{} total".format(base_name)
# increment_app_state_variable("linux-story", total_name, 1)
#
# # If total reaches a certain amount, then can award XP.
. Output only the next line. | story_replies["echo 1"][step - 2]["clara"], |
Based on the snippet: <|code_start|> "clara": \
_("Clara: {{Bb:\"I heard a bell ring, and saw the " +\
"lead librarian disappear in front of me. I was " +\
"so scared I ran away, and found this}} {{bb:.cellar}}" +\
"{{Bb:.\"}}")
},
{
"user": _("\"Do you have any relatives in town?\""),
"clara": \
_("Clara: {{Bb:\"I have a couple of children, a}} " +\
"{{bb:little-boy}} {{Bb:and a}} " +\
"{{bb:young-girl}}{{Bb:. I hope they are alright.\"}}")
},
{
"user": _("\"Why is the library so empty?\""),
"clara": \
_("Clara: {{Bb:\"We should have introduced late fees a long " +\
"time ago...\"}}")
}
],
"echo 3": [
{
"user": _("\"Do you know any other people in town?\""),
"clara": \
_("Clara: {{Bb:\"There's a man I don't trust that runs the}} " +\
"{{bb:shed-shop}}{{Bb:. I think his name is}} {{bb:Bernard}}{{Bb:.\"}}")
},
{
"user": _("\"Why don't you like Bernard?\""),
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from linux_story.story.challenges.CompanionMisc import StepTemplateNano
from linux_story.helper_functions import record_user_interaction
and context (classes, functions, sometimes code) from other files:
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateNano(StepTemplateEleanorBernard):
# TerminalClass = TerminalNanoBernard
#
# Path: linux_story/helper_functions.py
# def record_user_interaction(instance, base_name):
# """
# This is to store some of the user actions, so we can determine
# if the user does the optional side quests.
#
# Args:
# The class instance.
# base_name (str): a string for the identity of the command.
# """
#
# class_instance = instance.__class__.__name__
# challenge_number = instance.__module__.split("_")[-1]
# profile_var_name = "{} {} {}".format(
# base_name, challenge_number, class_instance
# )
#
# # First, try loading the profile variable name
# # If the value is None, then make it True and increment the total.
# already_done = load_app_state_variable("linux-story", profile_var_name)
#
# # If the command has not been done yet in this class, then increment the
# # total
# if not already_done:
# save_app_state_variable("linux-story", profile_var_name, True)
# total_name = "{} total".format(base_name)
# increment_app_state_variable("linux-story", total_name, 1)
#
# # If total reaches a certain amount, then can award XP.
. Output only the next line. | "clara": \ |
Given snippet: <|code_start|> poss_step = challenge_dict["step"]
if self.__challenge_step_earlier_or_equal(challenge, step, poss_challenge, poss_step):
challenge_data = challenge_dict
if self.__challenge_step_higher(lower_bound_challenge, lower_bound_step, poss_challenge, poss_step):
lower_bound_challenge = poss_challenge
lower_bound_step = poss_step
if self.KEY_PERMISSIONS in tree:
challenge_data[self.KEY_PERMISSIONS] = tree[self.KEY_PERMISSIONS]
return challenge_data
@staticmethod
def __challenge_step_higher(challenge, step, poss_challenge, poss_step):
return (poss_challenge > challenge) or (poss_challenge == challenge and poss_step > step)
@staticmethod
def __challenge_step_earlier_or_equal(challenge, step, poss_challenge, poss_step):
return (poss_challenge <= challenge and poss_step <= step) or (poss_challenge < challenge)
@staticmethod
def __create_dir(path, permissions):
if os.path.exists(path) and not os.path.isdir(path):
raise Exception("File " + path + " exists and should be a directory")
if not os.path.exists(path): # check permissions
FileTree.mkdir_p(path)
os.chmod(path, permissions)
@staticmethod
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import filecmp
import os
import shutil
import stat
import errno
from linux_story.common import fake_home_dir, tq_file_system, get_story_file
and context:
# Path: linux_story/common.py
# def get_max_challenge_number():
# def get_username():
# def get_story_file(name):
which might include code, classes, or functions. Output only the next line. | def mkdir_p(path): |
Next line prediction: <|code_start|>
@staticmethod
def __get_default_owner():
return os.environ['LOGNAME']
def __get_contents_path(self, tree):
if self.KEY_CONTENTS not in tree:
raise Exception("No contents associated with the file: " + tree["name"])
return tree[self.KEY_CONTENTS]
def delete_item(path):
if os.path.exists(path):
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
def revert_to_default_permissions(filesystem):
for root, dirs, files in os.walk(filesystem):
for d in dirs:
path = os.path.join(root, d)
os.chmod(path, 0755)
for f in files:
path = os.path.join(root, f)
os.chmod(path, 0644)
def get_oct_permissions(path):
<|code_end|>
. Use current file imports:
(import filecmp
import os
import shutil
import stat
import errno
from linux_story.common import fake_home_dir, tq_file_system, get_story_file)
and context including class names, function names, or small code snippets from other files:
# Path: linux_story/common.py
# def get_max_challenge_number():
# def get_username():
# def get_story_file(name):
. Output only the next line. | return oct(os.stat(path).st_mode & 0777) |
Given the code snippet: <|code_start|> challenge_data = {}
for challenge_dict in tree[self.KEY_CHALLENGES]:
if self.KEY_CHALLENGE not in challenge_dict or self.KEY_STEP not in challenge_dict:
raise Exception("missing challenge key in " + str(challenge_dict))
poss_challenge = challenge_dict["challenge"]
poss_step = challenge_dict["step"]
if self.__challenge_step_earlier_or_equal(challenge, step, poss_challenge, poss_step):
challenge_data = challenge_dict
if self.__challenge_step_higher(lower_bound_challenge, lower_bound_step, poss_challenge, poss_step):
lower_bound_challenge = poss_challenge
lower_bound_step = poss_step
if self.KEY_PERMISSIONS in tree:
challenge_data[self.KEY_PERMISSIONS] = tree[self.KEY_PERMISSIONS]
return challenge_data
@staticmethod
def __challenge_step_higher(challenge, step, poss_challenge, poss_step):
return (poss_challenge > challenge) or (poss_challenge == challenge and poss_step > step)
@staticmethod
def __challenge_step_earlier_or_equal(challenge, step, poss_challenge, poss_step):
return (poss_challenge <= challenge and poss_step <= step) or (poss_challenge < challenge)
@staticmethod
def __create_dir(path, permissions):
if os.path.exists(path) and not os.path.isdir(path):
raise Exception("File " + path + " exists and should be a directory")
<|code_end|>
, generate the next line using the imports in this file:
import filecmp
import os
import shutil
import stat
import errno
from linux_story.common import fake_home_dir, tq_file_system, get_story_file
and context (functions, classes, or occasionally code) from other files:
# Path: linux_story/common.py
# def get_max_challenge_number():
# def get_username():
# def get_story_file(name):
. Output only the next line. | if not os.path.exists(path): # check permissions |
Predict the next line for this snippet: <|code_start|> "challenges": [
{
"challenge": 36,
"step": 1,
"exists": False
}
]
},
{
"name": "scroll",
"contents": get_story_file("scroll-cage"),
"challenges": [
{
"challenge": 0,
"step": 1,
"exists": False
},
{
"challenge": 36,
"step": 1
}
]
}
]
}
locked_room = {
"name": "locked-room",
"challenges": [
{
<|code_end|>
with the help of current file imports:
from linux_story.common import get_story_file
and context from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
, which may contain function names, class names, or code. Output only the next line. | "challenge": 32, |
Here is a snippet: <|code_start|>#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# A terminal for one of the challenges
class TerminalSudo(TerminalRm):
terminal_commands = [
"ls", "cat", "cd", "mv", "echo", "mkdir", "nano", "chmod", "rm", "sudo"
]
def do_sudo(self, line):
command = line.split(" ")[0]
following_line = " ".join(line.split(" ")[1:])
if command in self.terminal_commands:
success_cb = getattr(self, 'do_{}'.format(command))
else:
success_cb = lambda *cb_args: printf("sudo: " + line + ": command not found")
self.__sudo(self._location.get_real_path(), line, success_cb, 0, following_line)
def __sudo(self, real_path, line, success_cb, counter=0, *cb_args):
if counter == 0:
self._client.send_hint("\n{{gb:Type a password. You won't be able to see what you type.}}")
elif counter == 3:
self.passed = False
print "sudo: 3 incorrect password attempts"
<|code_end|>
. Write the next line using the current file imports:
import getpass
from linux_story.story.terminals.terminal_rm import TerminalRm
and context from other files:
# Path: linux_story/story/terminals/terminal_rm.py
# class TerminalRm(TerminalChmod):
# terminal_commands = [
# "ls", "cat", "cd", "mv", "echo", "mkdir", "nano", "chmod", "rm"
# ]
#
# def do_rm(self, line):
# shell_command(self._location.get_real_path(), line, "rm")
#
# def complete_rm(self, text, line, begidx, endidx):
# completions = self._autocomplete_files(text, line, begidx, endidx)
# return completions
, which may include functions, classes, or code. Output only the next line. | return |
Based on the snippet: <|code_start|># terminal_nano.py
#
# Copyright (C) 2014-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# A terminal for one of the challenges
class TerminalNano(TerminalMkdir):
terminal_commands = ["ls", "cat", "cd", "mv", "echo", "mkdir", "nano"]
def __init__(self, step, location, dirs_to_attempt, client):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import threading
from kano.logging import logger
from linux_story.PlayerLocation import generate_real_path
from linux_story.commands_real import nano
from linux_story.story.terminals.terminal_mkdir import TerminalMkdir
and context (classes, functions, sometimes code) from other files:
# Path: linux_story/PlayerLocation.py
# def generate_real_path(fake_path):
# return fake_path.replace('~', fake_home_dir)
#
# Path: linux_story/commands_real.py
# def nano(real_path, line):
# '''
# Runs the linux-story version of nano as a separate process,
# and prints out any resulting errors.
#
# Args:
# real_path (str): the current location of the user.
# line (str): the command entered by the user.
#
# Returns:
# None
# '''
#
# # File path of the local nano
# dir_path = os.path.abspath(os.path.dirname(__file__))
# nano_filepath = os.path.join(dir_path, "..", "nano-2.2.6/src/nano")
#
# if not os.path.exists(nano_filepath):
# # File path of installed nano
# nano_filepath = "/usr/share/linux-story/nano"
#
# if not os.path.exists(nano_filepath):
# raise Exception("Cannot find nano")
#
# # notifying the SoundManager about the command that is about run
# sounds_manager.on_command_run(['nano'] + line.split())
#
# # Unsetting the LINES and COLUMNS variables because the
# # hack in TerminalUi.py which sets the size to 1000x1000 is disturbing nano
# # (https://github.com/KanoComputing/terminal-quest/commit/dd45b447363e3fdcebf80000dbbfd920b96637db)
# cmd = 'LINES= COLUMNS= ' + nano_filepath + " " + line
# p = subprocess.Popen(cmd, cwd=real_path, shell=True)
# stdout, stderr = p.communicate()
#
# if stdout:
# print stdout.strip()
#
# if stderr:
# print stderr.strip()
#
# Path: linux_story/story/terminals/terminal_mkdir.py
# class TerminalMkdir(TerminalEcho):
# terminal_commands = ["ls", "cat", "cd", "mv", "echo", "mkdir"]
#
# def do_mkdir(self, line):
# shell_command(self._location.get_real_path(), line, "mkdir")
. Output only the next line. | self._step_nano = step.get_nano_logic() |
Based on the snippet: <|code_start|> def do_nano(self, line):
##########################################
# set up step_nano
self._step_nano.set_nano_running(True)
self._step_nano.opened_nano(line)
# Read contents of the file
text = self.read_goal_contents()
self._step_nano.set_nano_content(text)
##########################################
# Read nano in a separate thread
t = threading.Thread(target=self.try_and_get_pipe_contents)
t.daemon = True
t.start()
# If the line is given, it is the filepath of the file we are
# adjusting.
# if line:
# self.set_last_nano_filepath(line)
nano(self._location.get_real_path(), line)
def try_and_get_pipe_contents(self):
try:
self._step_nano.get_pipe_contents()
except Exception as e:
logger.error(
"\nFailed to get nano contents, exception {}".format(str(e))
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import threading
from kano.logging import logger
from linux_story.PlayerLocation import generate_real_path
from linux_story.commands_real import nano
from linux_story.story.terminals.terminal_mkdir import TerminalMkdir
and context (classes, functions, sometimes code) from other files:
# Path: linux_story/PlayerLocation.py
# def generate_real_path(fake_path):
# return fake_path.replace('~', fake_home_dir)
#
# Path: linux_story/commands_real.py
# def nano(real_path, line):
# '''
# Runs the linux-story version of nano as a separate process,
# and prints out any resulting errors.
#
# Args:
# real_path (str): the current location of the user.
# line (str): the command entered by the user.
#
# Returns:
# None
# '''
#
# # File path of the local nano
# dir_path = os.path.abspath(os.path.dirname(__file__))
# nano_filepath = os.path.join(dir_path, "..", "nano-2.2.6/src/nano")
#
# if not os.path.exists(nano_filepath):
# # File path of installed nano
# nano_filepath = "/usr/share/linux-story/nano"
#
# if not os.path.exists(nano_filepath):
# raise Exception("Cannot find nano")
#
# # notifying the SoundManager about the command that is about run
# sounds_manager.on_command_run(['nano'] + line.split())
#
# # Unsetting the LINES and COLUMNS variables because the
# # hack in TerminalUi.py which sets the size to 1000x1000 is disturbing nano
# # (https://github.com/KanoComputing/terminal-quest/commit/dd45b447363e3fdcebf80000dbbfd920b96637db)
# cmd = 'LINES= COLUMNS= ' + nano_filepath + " " + line
# p = subprocess.Popen(cmd, cwd=real_path, shell=True)
# stdout, stderr = p.communicate()
#
# if stdout:
# print stdout.strip()
#
# if stderr:
# print stderr.strip()
#
# Path: linux_story/story/terminals/terminal_mkdir.py
# class TerminalMkdir(TerminalEcho):
# terminal_commands = ["ls", "cat", "cd", "mv", "echo", "mkdir"]
#
# def do_mkdir(self, line):
# shell_command(self._location.get_real_path(), line, "mkdir")
. Output only the next line. | ) |
Given the code snippet: <|code_start|> ]
file_list = [
{
"path": "~/town/east/shed-shop/Bernards-hat",
"contents": get_story_file("bernards-hat")
}
]
companion_speech = _("Eleanor: {{Bb:......}}")
def next(self):
return 30, 2
class Step2(StepNano):
story = [
_("Everyone seems to be here. What was that bell?"),
_("\n{{bb:Clara}} looks like she has something to say. {{lb:Listen to her.}}")
]
commands = [
"cat Clara"
]
start_dir = "~/town/east/restaurant/.cellar"
end_dir = "~/town/east/restaurant/.cellar"
hints = [
_("{{rb:Use}} {{yb:cat Clara}} {{rb:to see what Clara has to say.}}")
]
companion_speech = \
_("Eleanor: {{Bb:\"....I was so scared. I don't think I want to go " +\
"outside now.\"}}")
<|code_end|>
, generate the next line using the imports in this file:
import os
from linux_story.common import get_story_file
from linux_story.story.challenges.CompanionMisc import StepTemplateEleanorBernard
from linux_story.step_helper_functions import unblock_cd_commands
from linux_story.story.terminals.terminal_nano import TerminalNano
and context (functions, classes, or occasionally code) from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
#
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateEleanorBernard(StepTemplate):
# companion_command = "cat Eleanor"
#
# def check_command(self, last_user_input):
# spoke = self._companion_speaks(last_user_input)
# if not spoke:
# return self._default_check_command(last_user_input)
#
# def block_command(self, line):
# if "basement" in line and ("ls" in line or "cat" in line):
# print bernard_text
# return True
# else:
# return StepTemplate.block_command(self, line)
#
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
#
# Path: linux_story/story/terminals/terminal_nano.py
# class TerminalNano(TerminalMkdir):
# terminal_commands = ["ls", "cat", "cd", "mv", "echo", "mkdir", "nano"]
#
# def __init__(self, step, location, dirs_to_attempt, client):
# self._step_nano = step.get_nano_logic()
#
# TerminalMkdir.__init__(self, step, location, dirs_to_attempt, client)
#
# def do_nano(self, line):
#
# ##########################################
# # set up step_nano
# self._step_nano.set_nano_running(True)
# self._step_nano.opened_nano(line)
#
# # Read contents of the file
# text = self.read_goal_contents()
# self._step_nano.set_nano_content(text)
# ##########################################
#
# # Read nano in a separate thread
# t = threading.Thread(target=self.try_and_get_pipe_contents)
# t.daemon = True
# t.start()
#
# # If the line is given, it is the filepath of the file we are
# # adjusting.
# # if line:
# # self.set_last_nano_filepath(line)
#
# nano(self._location.get_real_path(), line)
#
# def try_and_get_pipe_contents(self):
# try:
# self._step_nano.get_pipe_contents()
# except Exception as e:
# logger.error(
# "\nFailed to get nano contents, exception {}".format(str(e))
# )
# self._step.send_hint("\nFailed to get nano contents, {}".format(str(e)))
#
# def read_goal_contents(self):
# text = ""
# end_path = generate_real_path(self._step_nano.get_goal_nano_filepath())
#
# if os.path.exists(end_path):
# # check contents of file contains the self.end_text
# f = open(end_path, "r")
# text = f.read()
# f.close()
#
# return text
. Output only the next line. | def next(self): |
Given the following code snippet before the placeholder: <|code_start|> _("{{Bb:\"}}{{gb:%s}}" +\
"{{Bb:, you look like you can take care of yourself, but " +\
"I don't feel happy with Eleanor going outside.\"}}")\
% os.environ['LOGNAME'],
_("\n{{Bb:\"}}{{gb:%s}}{{Bb:, will you leave Eleanor with me? " +\
"I'll look after her.\"}}") % os.environ['LOGNAME'],
_("\n{{yb:1: \"That's a good idea, take good care of her.\"}}"),
_("{{yb:2: \"No I don't trust you, she's safer with me.\"}}"),
_("{{yb:3: \"(Ask Eleanor.) Are you happy to stay here?\"}}"),
# _("{{yb:4: Do you have enough food here?}}"),
_("\n{{lb:Reply to Clara.}}")
]
commands = [
"echo 1"
]
start_dir = "~/town/east/restaurant/.cellar"
end_dir = "~/town/east/restaurant/.cellar"
hints = [
_("{{rb:Use}} {{yb:echo 1}}{{rb:,}} {{yb:echo 2}} {{rb:or}} " +\
"{{yb:echo 3}} {{rb:to reply to Clara.}}")
]
companion_speech = (
_("Eleanor: {{Bb:\"I'm happy to stay here. I like Clara.\"}}")
)
def check_command(self, line):
if line == "echo 2":
text = (
_("\nClara: {{Bb:\"Please let me look after her. " +\
"I don't think it's safe for her to go outside.\"}}")
<|code_end|>
, predict the next line using imports from the current file:
import os
from linux_story.common import get_story_file
from linux_story.story.challenges.CompanionMisc import StepTemplateEleanorBernard
from linux_story.step_helper_functions import unblock_cd_commands
from linux_story.story.terminals.terminal_nano import TerminalNano
and context including class names, function names, and sometimes code from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
#
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateEleanorBernard(StepTemplate):
# companion_command = "cat Eleanor"
#
# def check_command(self, last_user_input):
# spoke = self._companion_speaks(last_user_input)
# if not spoke:
# return self._default_check_command(last_user_input)
#
# def block_command(self, line):
# if "basement" in line and ("ls" in line or "cat" in line):
# print bernard_text
# return True
# else:
# return StepTemplate.block_command(self, line)
#
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
#
# Path: linux_story/story/terminals/terminal_nano.py
# class TerminalNano(TerminalMkdir):
# terminal_commands = ["ls", "cat", "cd", "mv", "echo", "mkdir", "nano"]
#
# def __init__(self, step, location, dirs_to_attempt, client):
# self._step_nano = step.get_nano_logic()
#
# TerminalMkdir.__init__(self, step, location, dirs_to_attempt, client)
#
# def do_nano(self, line):
#
# ##########################################
# # set up step_nano
# self._step_nano.set_nano_running(True)
# self._step_nano.opened_nano(line)
#
# # Read contents of the file
# text = self.read_goal_contents()
# self._step_nano.set_nano_content(text)
# ##########################################
#
# # Read nano in a separate thread
# t = threading.Thread(target=self.try_and_get_pipe_contents)
# t.daemon = True
# t.start()
#
# # If the line is given, it is the filepath of the file we are
# # adjusting.
# # if line:
# # self.set_last_nano_filepath(line)
#
# nano(self._location.get_real_path(), line)
#
# def try_and_get_pipe_contents(self):
# try:
# self._step_nano.get_pipe_contents()
# except Exception as e:
# logger.error(
# "\nFailed to get nano contents, exception {}".format(str(e))
# )
# self._step.send_hint("\nFailed to get nano contents, {}".format(str(e)))
#
# def read_goal_contents(self):
# text = ""
# end_path = generate_real_path(self._step_nano.get_goal_nano_filepath())
#
# if os.path.exists(end_path):
# # check contents of file contains the self.end_text
# f = open(end_path, "r")
# text = f.read()
# f.close()
#
# return text
. Output only the next line. | ) |
Continue the code snippet: <|code_start|> "ls -a"
]
hints = [
_("{{rb:Use}} {{yb:ls}} {{rb:to check everyone is still present.}}")
]
deleted_items = [
"~/town/east/shed-shop/Bernard"
]
file_list = [
{
"path": "~/town/east/shed-shop/Bernards-hat",
"contents": get_story_file("bernards-hat")
}
]
companion_speech = _("Eleanor: {{Bb:......}}")
def next(self):
return 30, 2
class Step2(StepNano):
story = [
_("Everyone seems to be here. What was that bell?"),
_("\n{{bb:Clara}} looks like she has something to say. {{lb:Listen to her.}}")
]
commands = [
"cat Clara"
]
start_dir = "~/town/east/restaurant/.cellar"
end_dir = "~/town/east/restaurant/.cellar"
<|code_end|>
. Use current file imports:
import os
from linux_story.common import get_story_file
from linux_story.story.challenges.CompanionMisc import StepTemplateEleanorBernard
from linux_story.step_helper_functions import unblock_cd_commands
from linux_story.story.terminals.terminal_nano import TerminalNano
and context (classes, functions, or code) from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
#
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateEleanorBernard(StepTemplate):
# companion_command = "cat Eleanor"
#
# def check_command(self, last_user_input):
# spoke = self._companion_speaks(last_user_input)
# if not spoke:
# return self._default_check_command(last_user_input)
#
# def block_command(self, line):
# if "basement" in line and ("ls" in line or "cat" in line):
# print bernard_text
# return True
# else:
# return StepTemplate.block_command(self, line)
#
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
#
# Path: linux_story/story/terminals/terminal_nano.py
# class TerminalNano(TerminalMkdir):
# terminal_commands = ["ls", "cat", "cd", "mv", "echo", "mkdir", "nano"]
#
# def __init__(self, step, location, dirs_to_attempt, client):
# self._step_nano = step.get_nano_logic()
#
# TerminalMkdir.__init__(self, step, location, dirs_to_attempt, client)
#
# def do_nano(self, line):
#
# ##########################################
# # set up step_nano
# self._step_nano.set_nano_running(True)
# self._step_nano.opened_nano(line)
#
# # Read contents of the file
# text = self.read_goal_contents()
# self._step_nano.set_nano_content(text)
# ##########################################
#
# # Read nano in a separate thread
# t = threading.Thread(target=self.try_and_get_pipe_contents)
# t.daemon = True
# t.start()
#
# # If the line is given, it is the filepath of the file we are
# # adjusting.
# # if line:
# # self.set_last_nano_filepath(line)
#
# nano(self._location.get_real_path(), line)
#
# def try_and_get_pipe_contents(self):
# try:
# self._step_nano.get_pipe_contents()
# except Exception as e:
# logger.error(
# "\nFailed to get nano contents, exception {}".format(str(e))
# )
# self._step.send_hint("\nFailed to get nano contents, {}".format(str(e)))
#
# def read_goal_contents(self):
# text = ""
# end_path = generate_real_path(self._step_nano.get_goal_nano_filepath())
#
# if os.path.exists(end_path):
# # check contents of file contains the self.end_text
# f = open(end_path, "r")
# text = f.read()
# f.close()
#
# return text
. Output only the next line. | hints = [ |
Using the snippet: <|code_start|>
greenhouse = {
"name": "greenhouse",
"children": [
{
"name": "carrots",
"contents": get_story_file("carrots")
},
{
"name": "pumpkin",
"contents": get_story_file("pumpkin")
},
{
"name": "tomato",
"contents": get_story_file("tomato")
},
{
<|code_end|>
, determine the next line of code. You have imports:
from linux_story.common import get_story_file
and context (class names, function names, or code) available:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
. Output only the next line. | "name": "onion", |
Continue the code snippet: <|code_start|> "step": 3
},
{
"challenge": 42,
"step": 6,
"exists": False
}
]
},
{
"name": "Rabbit",
"type": "file",
"contents": get_story_file("Rabbit"),
"challenges": [
{
"challenge": 0,
"step": 1,
"exists": False
},
{
"challenge": 42,
"step": 4
},
{
"challenge": 42,
"step": 6,
"exists": False
}
]
},
<|code_end|>
. Use current file imports:
from linux_story.common import get_story_file
and context (classes, functions, or code) from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
. Output only the next line. | { |
Here is a snippet: <|code_start|># terminal_cd.py
#
# Copyright (C) 2014-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# The a terminal for one of the challenges
def not_locked(directory):
uid = os.geteuid()
gid = os.getegid()
s = os.stat(directory)
mode = s[stat.ST_MODE]
<|code_end|>
. Write the next line using the current file imports:
import os
import stat
from linux_story.commands_fake import cd
from linux_story.step_helper_functions import route_between_paths
from linux_story.story.terminals.terminal_cat import TerminalCat
and context from other files:
# Path: linux_story/commands_fake.py
# def cd(real_path, line, has_access=True):
# if not has_access:
# # Could simplify this to "Permission denied"
# print "-bash: cd: {}: Permission denied".format(line)
# return
#
# if not line:
# new_path = fake_home_dir
# else:
# if line.startswith('~'):
# new_line = line.replace('~', fake_home_dir)
# new_path = os.path.expanduser(new_line)
# else:
# new_path = os.path.join(real_path, line)
# new_path = os.path.abspath(new_path)
#
# if not os.path.exists(new_path) or not os.path.isdir(new_path):
# new_path = real_path
#
# if new_path[-1] == '/':
# new_path = new_path[:-1]
# return new_path
#
# Path: linux_story/step_helper_functions.py
# def route_between_paths(start_path, end_path):
# """
# Args:
# start_path (str)
# end_path (str)
#
# Assume they are in the same form,
# as absolute fake paths, e.g.
# ~/town/.hidden-shelter and
# ~/farm/barn/.shelter
#
# Return:
# list of strings: listing every path you could hit on
# a direct route from start_path to end_path.
# """
# common_path = find_common_parent(start_path, end_path)
#
# start_split = start_path.split(common_path)
# if len(start_split) != 2:
# raise Exception("common_path is not correct")
#
# end_split = end_path.split(common_path)
# if len(end_split) != 2:
# raise Exception("common_path is not correct")
#
# start_diff = start_split[1]
# end_diff = end_split[1]
#
# start_dirs = filter(None, start_diff.split("/"))
# end_dirs = filter(None, end_diff.split("/"))
#
# a_dest_path = start_path
# dest_paths = []
#
# for d in start_dirs[::-1]:
# a_dest_path = a_dest_path.replace(d, "")
#
# if a_dest_path.endswith("//"):
# a_dest_path = a_dest_path[:-2]
# if a_dest_path.endswith("/"):
# a_dest_path = a_dest_path[:-1]
#
# a_dest_path = os.path.expanduser(a_dest_path)
# dest_paths.append(a_dest_path)
#
# for d in end_dirs:
# a_dest_path = os.path.join(a_dest_path, d)
# a_dest_path = os.path.expanduser(a_dest_path)
# dest_paths.append(a_dest_path)
#
# return dest_paths
#
# Path: linux_story/story/terminals/terminal_cat.py
# class TerminalCat(TerminalLs):
# terminal_commands = ["ls", "cat"]
#
# def do_cat(self, line):
# shell_command(self._get_real_path(), line, "cat")
#
# def complete_cat(self, text, line, begidx, endidx):
# return self._autocomplete_files(text, line, begidx, endidx)
, which may include functions, classes, or code. Output only the next line. | return ( |
Next line prediction: <|code_start|>
def not_locked(directory):
uid = os.geteuid()
gid = os.getegid()
s = os.stat(directory)
mode = s[stat.ST_MODE]
return (
((s[stat.ST_UID] == uid) and (mode & stat.S_IXUSR)) or
((s[stat.ST_GID] == gid) and (mode & stat.S_IXGRP)) or
(mode & stat.S_IWOTH)
)
class TerminalCd(TerminalCat):
terminal_commands = ["ls", "cat", "cd"]
def do_cd(self, line):
if self.__check_cd(line):
self._set_command_blocked(False)
new_path = cd(self._location.get_real_path(), line)
if not not_locked(new_path):
self._set_command_blocked(True)
print (
_("bash: cd: " + line + ": Permission denied")
)
elif new_path:
self._location.set_real_path(new_path)
self._set_prompt()
else:
self._set_command_blocked(True)
<|code_end|>
. Use current file imports:
(import os
import stat
from linux_story.commands_fake import cd
from linux_story.step_helper_functions import route_between_paths
from linux_story.story.terminals.terminal_cat import TerminalCat)
and context including class names, function names, or small code snippets from other files:
# Path: linux_story/commands_fake.py
# def cd(real_path, line, has_access=True):
# if not has_access:
# # Could simplify this to "Permission denied"
# print "-bash: cd: {}: Permission denied".format(line)
# return
#
# if not line:
# new_path = fake_home_dir
# else:
# if line.startswith('~'):
# new_line = line.replace('~', fake_home_dir)
# new_path = os.path.expanduser(new_line)
# else:
# new_path = os.path.join(real_path, line)
# new_path = os.path.abspath(new_path)
#
# if not os.path.exists(new_path) or not os.path.isdir(new_path):
# new_path = real_path
#
# if new_path[-1] == '/':
# new_path = new_path[:-1]
# return new_path
#
# Path: linux_story/step_helper_functions.py
# def route_between_paths(start_path, end_path):
# """
# Args:
# start_path (str)
# end_path (str)
#
# Assume they are in the same form,
# as absolute fake paths, e.g.
# ~/town/.hidden-shelter and
# ~/farm/barn/.shelter
#
# Return:
# list of strings: listing every path you could hit on
# a direct route from start_path to end_path.
# """
# common_path = find_common_parent(start_path, end_path)
#
# start_split = start_path.split(common_path)
# if len(start_split) != 2:
# raise Exception("common_path is not correct")
#
# end_split = end_path.split(common_path)
# if len(end_split) != 2:
# raise Exception("common_path is not correct")
#
# start_diff = start_split[1]
# end_diff = end_split[1]
#
# start_dirs = filter(None, start_diff.split("/"))
# end_dirs = filter(None, end_diff.split("/"))
#
# a_dest_path = start_path
# dest_paths = []
#
# for d in start_dirs[::-1]:
# a_dest_path = a_dest_path.replace(d, "")
#
# if a_dest_path.endswith("//"):
# a_dest_path = a_dest_path[:-2]
# if a_dest_path.endswith("/"):
# a_dest_path = a_dest_path[:-1]
#
# a_dest_path = os.path.expanduser(a_dest_path)
# dest_paths.append(a_dest_path)
#
# for d in end_dirs:
# a_dest_path = os.path.join(a_dest_path, d)
# a_dest_path = os.path.expanduser(a_dest_path)
# dest_paths.append(a_dest_path)
#
# return dest_paths
#
# Path: linux_story/story/terminals/terminal_cat.py
# class TerminalCat(TerminalLs):
# terminal_commands = ["ls", "cat"]
#
# def do_cat(self, line):
# shell_command(self._get_real_path(), line, "cat")
#
# def complete_cat(self, text, line, begidx, endidx):
# return self._autocomplete_files(text, line, begidx, endidx)
. Output only the next line. | print (_("Nice try! But you entered an unexpected destination path.")) |
Given the following code snippet before the placeholder: <|code_start|># terminal_cd.py
#
# Copyright (C) 2014-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# The a terminal for one of the challenges
def not_locked(directory):
uid = os.geteuid()
gid = os.getegid()
s = os.stat(directory)
mode = s[stat.ST_MODE]
return (
<|code_end|>
, predict the next line using imports from the current file:
import os
import stat
from linux_story.commands_fake import cd
from linux_story.step_helper_functions import route_between_paths
from linux_story.story.terminals.terminal_cat import TerminalCat
and context including class names, function names, and sometimes code from other files:
# Path: linux_story/commands_fake.py
# def cd(real_path, line, has_access=True):
# if not has_access:
# # Could simplify this to "Permission denied"
# print "-bash: cd: {}: Permission denied".format(line)
# return
#
# if not line:
# new_path = fake_home_dir
# else:
# if line.startswith('~'):
# new_line = line.replace('~', fake_home_dir)
# new_path = os.path.expanduser(new_line)
# else:
# new_path = os.path.join(real_path, line)
# new_path = os.path.abspath(new_path)
#
# if not os.path.exists(new_path) or not os.path.isdir(new_path):
# new_path = real_path
#
# if new_path[-1] == '/':
# new_path = new_path[:-1]
# return new_path
#
# Path: linux_story/step_helper_functions.py
# def route_between_paths(start_path, end_path):
# """
# Args:
# start_path (str)
# end_path (str)
#
# Assume they are in the same form,
# as absolute fake paths, e.g.
# ~/town/.hidden-shelter and
# ~/farm/barn/.shelter
#
# Return:
# list of strings: listing every path you could hit on
# a direct route from start_path to end_path.
# """
# common_path = find_common_parent(start_path, end_path)
#
# start_split = start_path.split(common_path)
# if len(start_split) != 2:
# raise Exception("common_path is not correct")
#
# end_split = end_path.split(common_path)
# if len(end_split) != 2:
# raise Exception("common_path is not correct")
#
# start_diff = start_split[1]
# end_diff = end_split[1]
#
# start_dirs = filter(None, start_diff.split("/"))
# end_dirs = filter(None, end_diff.split("/"))
#
# a_dest_path = start_path
# dest_paths = []
#
# for d in start_dirs[::-1]:
# a_dest_path = a_dest_path.replace(d, "")
#
# if a_dest_path.endswith("//"):
# a_dest_path = a_dest_path[:-2]
# if a_dest_path.endswith("/"):
# a_dest_path = a_dest_path[:-1]
#
# a_dest_path = os.path.expanduser(a_dest_path)
# dest_paths.append(a_dest_path)
#
# for d in end_dirs:
# a_dest_path = os.path.join(a_dest_path, d)
# a_dest_path = os.path.expanduser(a_dest_path)
# dest_paths.append(a_dest_path)
#
# return dest_paths
#
# Path: linux_story/story/terminals/terminal_cat.py
# class TerminalCat(TerminalLs):
# terminal_commands = ["ls", "cat"]
#
# def do_cat(self, line):
# shell_command(self._get_real_path(), line, "cat")
#
# def complete_cat(self, text, line, begidx, endidx):
# return self._autocomplete_files(text, line, begidx, endidx)
. Output only the next line. | ((s[stat.ST_UID] == uid) and (mode & stat.S_IXUSR)) or |
Next line prediction: <|code_start|>#
# Animation.py
#
# Copyright (C) 2014-2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# A simple running bird animation for terminal quest, heavily based on the rabbit animation.
#
#
class Animation:
def __init__(self, filename):
self.__screen = None
self.__path = get_path_to_file_in_system(filename)
def play_across_screen(self, cycles=1, start_direction='left-to-right', speed=10):
status = 1 # everything went wrong
try:
<|code_end|>
. Use current file imports:
(import time
import curses
import random
import os
import struct
import fcntl
import termios
from linux_story.helper_functions import get_path_to_file_in_system)
and context including class names, function names, or small code snippets from other files:
# Path: linux_story/helper_functions.py
# def get_path_to_file_in_system(name):
# """
# Finds the path of a file (asset), first looking for any translation,
# and falling back to the default location.
#
# Args:
# name (str) - the name of the asset file
#
# Returns:
# path (str) - the path to the file (asset)
# """
#
# path_in_system = None
#
# lang_dirs = get_language_dirs()
#
# for lang_dir in lang_dirs:
# asset_path = os.path.join(localized_story_files_dir_pattern.format(lang_dir), name)
# if os.path.isfile(asset_path):
# path_in_system = asset_path
# break
#
# if path_in_system is None:
# path_in_system = os.path.join(fallback_story_files_dir, name)
#
# return path_in_system
. Output only the next line. | self.__init_curses() |
Given the following code snippet before the placeholder: <|code_start|> _("{{rb:Use}} {{yb:cat best-horn-in-the-world.sh}} {{rb:to examine the " +\
"tool.}}")
]
companion_speech = (
_("Eleanor: {{Bb:I think this tool is a bit broken.}}")
)
def check_command(self, line):
if line == "cat best-shed-maker-in-the-world.sh" or \
line == "cat ./best-shed-maker-in-the-world.sh":
self.send_hint(
_("\n{{rb:You're examining the wrong tool. You want to look " +\
"at}} {{yb:best-horn-in-the-world.sh}}")
)
else:
return StepTemplateMkdir.check_command(self, line)
def next(self):
return 25, 6
class Step6(StepTemplateMkdir):
story = [
_("The script reads {{yb:eco \"Honk!\"}}"),
_("Maybe it should read {{yb:echo \"Honk!\"}} instead..."),
_("How could we make changes to this script?"),
_("\nBernard: {{Bb:\"Ho ho, you look like you understand the problem.\"}}"),
<|code_end|>
, predict the next line using imports from the current file:
from linux_story.story.challenges.CompanionMisc import StepTemplateMkdir
from linux_story.step_helper_functions import unblock_cd_commands
and context including class names, function names, and sometimes code from other files:
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateMkdir(StepTemplateEleanorBernard):
# TerminalClass = TerminalMkdirBernard
#
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
. Output only the next line. | _("Eleanor: {{Bb:\"If we need extra help, we can go to the library, it was just outside.\"}}"), |
Here is a snippet: <|code_start|> ]
companion_speech = _("Eleanor: {{Bb:I don't think this will work...}}")
def next(self):
return 25, 5
class Step5(StepTemplateMkdir):
story = [
_("You get the error {{yb:mkdir: cannot create directory `shed': " +\
"File exists}}"),
_("\nBernard: {{Bb:\"Of course it won't work a second time - " +\
"you already have a shed!\""),
_("\"I'm working on the next big thing,}} " +\
"{{bb:best-horn-in-the-world.sh}}{{Bb:.\"}}"),
_("{{Bb:\"It can be used to alert anyone that you're coming. " +\
"I'm having some teething problems, " +\
"but I'm sure I'll fix them soon.\"}}"),
_("\n{{lb:Examine}} {{bb:best-horn-in-the-world.sh}} {{lb:and see if you " +\
"can identify the problem.}}\n"),
_("{{gb:Remember to use}} {{ob:TAB}}{{gb:!}}")
]
start_dir = "~/town/east/shed-shop"
end_dir = "~/town/east/shed-shop"
commands = [
<|code_end|>
. Write the next line using the current file imports:
from linux_story.story.challenges.CompanionMisc import StepTemplateMkdir
from linux_story.step_helper_functions import unblock_cd_commands
and context from other files:
# Path: linux_story/story/challenges/CompanionMisc.py
# class StepTemplateMkdir(StepTemplateEleanorBernard):
# TerminalClass = TerminalMkdirBernard
#
# Path: linux_story/step_helper_functions.py
# def unblock_cd_commands(line):
# if line.startswith("mkdir") or \
# (line.startswith("mv") and not line.strip() == 'mv --help'):
# print _('Nice try! But you do not need that command for this challenge')
# return True
# return False
, which may include functions, classes, or code. Output only the next line. | "cat best-horn-in-the-world.sh", |
Given the code snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# A terminal for one of the challenges
class TerminalRm(TerminalChmod):
terminal_commands = [
"ls", "cat", "cd", "mv", "echo", "mkdir", "nano", "chmod", "rm"
]
def do_rm(self, line):
shell_command(self._location.get_real_path(), line, "rm")
def complete_rm(self, text, line, begidx, endidx):
completions = self._autocomplete_files(text, line, begidx, endidx)
<|code_end|>
, generate the next line using the imports in this file:
from linux_story.commands_real import shell_command
from linux_story.story.terminals.terminal_chmod import TerminalChmod
and context (functions, classes, or occasionally code) from other files:
# Path: linux_story/commands_real.py
# def shell_command(real_loc, line, command_word=""):
# """
# Suitable for launching commands which don't involve curses.
#
# Args:
# real_loc (str): the current location of the user.
# line (str): line user typed not including the command word.
# command_word (str): command you want to run (e.g. ls).
#
# Returns:
# bool: False if error, True otherwise.
# """
#
# if command_word:
# line = command_word + " " + line
#
# line = line.replace('~', fake_home_dir)
# args = line.split(" ")
#
# # run the command
# p = subprocess.Popen(args, cwd=real_loc,
# stdout=subprocess.PIPE,
# stderr=subprocess.PIPE)
# stdout, stderr = p.communicate()
#
# if stderr:
# print stderr.strip().replace(fake_home_dir, '~')
# return False
#
# if stdout:
# if command_word == "cat":
# print stdout
#
# else:
# print stdout.strip()
#
# # notifying the SoundManager about the command that was run
# sounds_manager.on_command_run(args)
#
# # should this return stdout?
# return True
#
# Path: linux_story/story/terminals/terminal_chmod.py
# class TerminalChmod(TerminalNano):
# terminal_commands = [
# "ls", "cat", "cd", "mv", "echo", "mkdir", "nano", "chmod"
# ]
#
# def do_chmod(self, line):
# shell_command(self._location.get_real_path(), line, "chmod")
#
# def complete_chmod(self, text, line, begidx, endidx):
# completions = self._autocomplete_files(text, line, begidx, endidx)
# return completions
. Output only the next line. | return completions |
Based on the snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# A terminal for one of the challenges
class TerminalRm(TerminalChmod):
terminal_commands = [
"ls", "cat", "cd", "mv", "echo", "mkdir", "nano", "chmod", "rm"
<|code_end|>
, predict the immediate next line with the help of imports:
from linux_story.commands_real import shell_command
from linux_story.story.terminals.terminal_chmod import TerminalChmod
and context (classes, functions, sometimes code) from other files:
# Path: linux_story/commands_real.py
# def shell_command(real_loc, line, command_word=""):
# """
# Suitable for launching commands which don't involve curses.
#
# Args:
# real_loc (str): the current location of the user.
# line (str): line user typed not including the command word.
# command_word (str): command you want to run (e.g. ls).
#
# Returns:
# bool: False if error, True otherwise.
# """
#
# if command_word:
# line = command_word + " " + line
#
# line = line.replace('~', fake_home_dir)
# args = line.split(" ")
#
# # run the command
# p = subprocess.Popen(args, cwd=real_loc,
# stdout=subprocess.PIPE,
# stderr=subprocess.PIPE)
# stdout, stderr = p.communicate()
#
# if stderr:
# print stderr.strip().replace(fake_home_dir, '~')
# return False
#
# if stdout:
# if command_word == "cat":
# print stdout
#
# else:
# print stdout.strip()
#
# # notifying the SoundManager about the command that was run
# sounds_manager.on_command_run(args)
#
# # should this return stdout?
# return True
#
# Path: linux_story/story/terminals/terminal_chmod.py
# class TerminalChmod(TerminalNano):
# terminal_commands = [
# "ls", "cat", "cd", "mv", "echo", "mkdir", "nano", "chmod"
# ]
#
# def do_chmod(self, line):
# shell_command(self._location.get_real_path(), line, "chmod")
#
# def complete_chmod(self, text, line, begidx, endidx):
# completions = self._autocomplete_files(text, line, begidx, endidx)
# return completions
. Output only the next line. | ] |
Given the following code snippet before the placeholder: <|code_start|># rabbithole.py
#
# Copyright (C) 2014-2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
cage = {
"name": "cage",
"challenges": [
{
"challenge": 0,
"step": 1,
"exists": False
},
{
"challenge": 44,
"step": 5,
"permissions": 0500
},
{
"challenge": 45,
"step": 6,
"permissions": 0755
}
<|code_end|>
, predict the next line using imports from the current file:
from linux_story.common import get_story_file
from chest import chest
and context including class names, function names, and sometimes code from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
. Output only the next line. | ], |
Predict the next line after this snippet: <|code_start|># east.py
#
# Copyright (C) 2014-2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
restaurant = {
"name": "restaurant",
"children": [
{
"name": "",
"children": [
{
"name": ".cellar",
"children": [
<|code_end|>
using the current file's imports:
from linux_story.common import get_story_file
from shed_shop import shed_shop
from library import library
and any relevant context from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
. Output only the next line. | { |
Predict the next line for this snippet: <|code_start|> "exists": False
},
{
"challenge": 46,
"step": 1
}
]
}
edith = {
"name": "Edith",
"contents": get_story_file("Edith"),
"challenges": [
{
"challenge": 0,
"step": 1,
"exists": False
},
{
"challenge": 46,
"step": 1
}
]
}
edward = {
"name": "Edward",
"contents": get_story_file("Edward"),
"challenges": [
<|code_end|>
with the help of current file imports:
from linux_story.common import get_story_file
from hidden_shelter import hidden_shelter
from east import east
and context from other files:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
, which may contain function names, class names, or code. Output only the next line. | { |
Given snippet: <|code_start|>
def set_goal_nano_end_content(self, goal_nano_end_content):
self.__goal_nano_end_content = goal_nano_end_content
def get_goal_nano_end_content(self):
return self.__goal_nano_end_content
def get_last_prompt(self):
return self.__last_nano_prompt
def set_last_prompt(self, last_prompt):
self.__last_nano_prompt = last_prompt
def get_goal_nano_filepath(self):
return self.__goal_nano_filepath
def set_goal_nano_filepath(self, goal_path):
self.__goal_nano_filepath = goal_path
def check_nano_content_default(self):
if not self.get_nano_running():
if self.get_last_nano_filename() == self.get_goal_nano_save_name():
return True
elif self.get_on_filename_screen() and self.get_nano_content().strip() == self.get_goal_nano_end_content():
if self.get_editable() == self.get_goal_nano_save_name():
hint = \
_("\n{{gb:Press}} {{ob:Enter}} {{gb:to confirm the filename.}}")
else:
hint = \
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import ast
import os
import time
from linux_story.PlayerLocation import generate_real_path
and context:
# Path: linux_story/PlayerLocation.py
# def generate_real_path(fake_path):
# return fake_path.replace('~', fake_home_dir)
which might include code, classes, or functions. Output only the next line. | _("\n{{gb:Type}} {{yb:%s}} {{gb:and press}} {{yb:Enter}}") % self.get_goal_nano_save_name() |
Based on the snippet: <|code_start|># MessageServer.py
#
# Copyright (C) 2014-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# Controls communicating between the GUI and the terminal
class MessageServer:
HOST = "localhost"
PORT = 9959
def __init__(self, queue, window):
self.__window = window
self.__server_busy = False
SocketServer.TCPServer.allow_reuse_address = True
self.__server = SocketServer.TCPServer((MessageServer.HOST, MessageServer.PORT), MyTCPHandler)
self.__server.queue = queue
self.__is_busy = False
self.__exiting = False
def start_in_separate_thread(self):
t = threading.Thread(target=self.__server.serve_forever)
t.start()
def shutdown(self, widget=None, event=None):
<|code_end|>
, predict the immediate next line with the help of imports:
import socket
import threading
import Queue
import SocketServer
import time
import traceback
from linux_story.MyTCPHandler import MyTCPHandler
from kano.logging import logger
and context (classes, functions, sometimes code) from other files:
# Path: linux_story/MyTCPHandler.py
# class MyTCPHandler(SocketServer.BaseRequestHandler):
# """
# The RequestHandler class for our server.
#
# It is instantiated once per connection to the server, and must
# override the handle() method to implement communication to the
# client.
# """
#
# def __init__(self, arg1, arg2, arg3):
# self.continue_server = True
# SocketServer.BaseRequestHandler.__init__(self, arg1, arg2, arg3)
#
# def handle(self):
#
# # self.request is the TCP socket connected to the client
# data = self.request.recv(4096).strip()
# self.server.queue.put(json.loads(data))
. Output only the next line. | self.__exiting = True |
Using the snippet: <|code_start|> "name": "ECHO",
"contents": get_story_file("ECHO"),
},
{
"name": "map",
"contents": get_story_file("map"),
}
]
}
parents_room = {
"name": "parents-room",
"children": [
{
"name": "picture",
"contents": get_story_file("picture")
},
{
"name": "tv",
"contents": get_story_file("tv")
},
{
"name": "window",
"contents": get_story_file("window")
},
{
"name": "bed",
"contents": get_story_file("bed_parents-room")
},
safe
<|code_end|>
, determine the next line of code. You have imports:
from linux_story.common import get_story_file
and context (class names, function names, or code) available:
# Path: linux_story/common.py
# def get_story_file(name):
# return os.path.join(fallback_story_files_dir, name)
. Output only the next line. | ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.