Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> 'soft off': 'soft power off',
'soft reboot': 'soft rebooting',
}
LOG = logging.getLogger(__name__)
_DEFAULT_POLL_INTERVAL = 2
class Node(base.Resource):
def __repr__(self):
return "<Node %s>" % self._info
class NodeManager(base.CreateManager):
resource_class = Node
_creation_attributes = ['chassis_uuid', 'driver', 'driver_info',
'extra', 'uuid', 'properties', 'name',
'bios_interface', 'boot_interface',
'console_interface', 'deploy_interface',
'inspect_interface', 'management_interface',
'network_interface', 'power_interface',
'raid_interface', 'rescue_interface',
'storage_interface', 'vendor_interface',
'resource_class', 'conductor_group',
'automated_clean', 'network_data']
_resource_name = 'nodes'
def list(self, associated=None, maintenance=None, marker=None,
limit=None, detail=False, sort_key=None, sort_dir=None,
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
from oslo_utils import strutils
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.v1 import volume_connector
from ironicclient.v1 import volume_target
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/volume_connector.py
# class VolumeConnector(base.Resource):
# class VolumeConnectorManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_connector_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, volume_connector_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_connector_id, patch, os_ironic_api_version=None,
# global_request_id=None):
#
# Path: ironicclient/v1/volume_target.py
# class VolumeTarget(base.Resource):
# class VolumeTargetManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_target_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def delete(self, volume_target_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_target_id, patch, os_ironic_api_version=None,
# global_request_id=None):
. Output only the next line. | fields=None, provision_state=None, driver=None, |
Given 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.
_power_states = {
'on': 'power on',
'off': 'power off',
'reboot': 'rebooting',
'soft off': 'soft power off',
'soft reboot': 'soft rebooting',
}
LOG = logging.getLogger(__name__)
_DEFAULT_POLL_INTERVAL = 2
class Node(base.Resource):
def __repr__(self):
return "<Node %s>" % self._info
class NodeManager(base.CreateManager):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import os
from oslo_utils import strutils
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.v1 import volume_connector
from ironicclient.v1 import volume_target
and context:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/volume_connector.py
# class VolumeConnector(base.Resource):
# class VolumeConnectorManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_connector_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, volume_connector_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_connector_id, patch, os_ironic_api_version=None,
# global_request_id=None):
#
# Path: ironicclient/v1/volume_target.py
# class VolumeTarget(base.Resource):
# class VolumeTargetManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_target_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def delete(self, volume_target_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_target_id, patch, os_ironic_api_version=None,
# global_request_id=None):
which might include code, classes, or functions. Output only the next line. | resource_class = Node |
Here is a snippet: <|code_start|> super(ExcTest, self).setUp()
self.message = 'SpongeBob SquarePants'
self.traceback = 'Foo Traceback'
self.method = 'call_spongebob'
self.url = 'http://foo.bar'
self.expected_json = {'error': {'message': self.message,
'details': self.traceback}}
def test_from_response(self, mock_apiclient):
fake_response = mock.Mock(status_code=http_client.BAD_REQUEST)
exc.from_response(fake_response, message=self.message,
traceback=self.traceback, method=self.method,
url=self.url)
self.assertEqual(http_client.BAD_REQUEST, fake_response.status_code)
self.assertEqual(self.expected_json, fake_response.json())
mock_apiclient.assert_called_once_with(
fake_response, method=self.method, url=self.url)
def test_from_response_status(self, mock_apiclient):
fake_response = mock.Mock(status=http_client.BAD_REQUEST)
fake_response.getheader.return_value = 'fake-header'
delattr(fake_response, 'status_code')
exc.from_response(fake_response, message=self.message,
traceback=self.traceback, method=self.method,
url=self.url)
expected_header = {'Content-Type': 'fake-header'}
self.assertEqual(expected_header, fake_response.headers)
self.assertEqual(http_client.BAD_REQUEST, fake_response.status_code)
self.assertEqual(self.expected_json, fake_response.json())
<|code_end|>
. Write the next line using the current file imports:
from http import client as http_client
from unittest import mock
from ironicclient.common.apiclient import exceptions
from ironicclient import exc
from ironicclient.tests.unit import utils as test_utils
and context from other files:
# Path: ironicclient/common/apiclient/exceptions.py
# class ClientException(Exception):
# class ValidationError(ClientException):
# class UnsupportedVersion(ClientException):
# class CommandError(ClientException):
# class AuthorizationFailure(ClientException):
# class ConnectionError(ClientException):
# class ConnectionRefused(ConnectionError):
# class AuthPluginOptionsMissing(AuthorizationFailure):
# class AuthSystemNotFound(AuthorizationFailure):
# class NoUniqueMatch(ClientException):
# class EndpointException(ClientException):
# class EndpointNotFound(EndpointException):
# class AmbiguousEndpoints(EndpointException):
# class HttpError(ClientException):
# class HTTPRedirection(HttpError):
# class HTTPClientError(HttpError):
# class HttpServerError(HttpError):
# class MultipleChoices(HTTPRedirection):
# class BadRequest(HTTPClientError):
# class Unauthorized(HTTPClientError):
# class PaymentRequired(HTTPClientError):
# class Forbidden(HTTPClientError):
# class NotFound(HTTPClientError):
# class MethodNotAllowed(HTTPClientError):
# class NotAcceptable(HTTPClientError):
# class ProxyAuthenticationRequired(HTTPClientError):
# class RequestTimeout(HTTPClientError):
# class Conflict(HTTPClientError):
# class Gone(HTTPClientError):
# class LengthRequired(HTTPClientError):
# class PreconditionFailed(HTTPClientError):
# class RequestEntityTooLarge(HTTPClientError):
# class RequestUriTooLong(HTTPClientError):
# class UnsupportedMediaType(HTTPClientError):
# class RequestedRangeNotSatisfiable(HTTPClientError):
# class ExpectationFailed(HTTPClientError):
# class UnprocessableEntity(HTTPClientError):
# class InternalServerError(HttpServerError):
# class HttpNotImplemented(HttpServerError):
# class BadGateway(HttpServerError):
# class ServiceUnavailable(HttpServerError):
# class GatewayTimeout(HttpServerError):
# class HttpVersionNotSupported(HttpServerError):
# def __init__(self, opt_names):
# def __init__(self, auth_system):
# def __init__(self, endpoints=None):
# def __init__(self, message=None, details=None,
# response=None, request_id=None,
# url=None, method=None, http_status=None):
# def __init__(self, *args, **kwargs):
# def from_response(response, method, url):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
, which may include functions, classes, or code. Output only the next line. | mock_apiclient.assert_called_once_with( |
Given the following code snippet before the placeholder: <|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.
@mock.patch.object(exceptions, 'from_response', autospec=True)
class ExcTest(test_utils.BaseTestCase):
def setUp(self):
super(ExcTest, self).setUp()
self.message = 'SpongeBob SquarePants'
self.traceback = 'Foo Traceback'
self.method = 'call_spongebob'
self.url = 'http://foo.bar'
self.expected_json = {'error': {'message': self.message,
'details': self.traceback}}
def test_from_response(self, mock_apiclient):
<|code_end|>
, predict the next line using imports from the current file:
from http import client as http_client
from unittest import mock
from ironicclient.common.apiclient import exceptions
from ironicclient import exc
from ironicclient.tests.unit import utils as test_utils
and context including class names, function names, and sometimes code from other files:
# Path: ironicclient/common/apiclient/exceptions.py
# class ClientException(Exception):
# class ValidationError(ClientException):
# class UnsupportedVersion(ClientException):
# class CommandError(ClientException):
# class AuthorizationFailure(ClientException):
# class ConnectionError(ClientException):
# class ConnectionRefused(ConnectionError):
# class AuthPluginOptionsMissing(AuthorizationFailure):
# class AuthSystemNotFound(AuthorizationFailure):
# class NoUniqueMatch(ClientException):
# class EndpointException(ClientException):
# class EndpointNotFound(EndpointException):
# class AmbiguousEndpoints(EndpointException):
# class HttpError(ClientException):
# class HTTPRedirection(HttpError):
# class HTTPClientError(HttpError):
# class HttpServerError(HttpError):
# class MultipleChoices(HTTPRedirection):
# class BadRequest(HTTPClientError):
# class Unauthorized(HTTPClientError):
# class PaymentRequired(HTTPClientError):
# class Forbidden(HTTPClientError):
# class NotFound(HTTPClientError):
# class MethodNotAllowed(HTTPClientError):
# class NotAcceptable(HTTPClientError):
# class ProxyAuthenticationRequired(HTTPClientError):
# class RequestTimeout(HTTPClientError):
# class Conflict(HTTPClientError):
# class Gone(HTTPClientError):
# class LengthRequired(HTTPClientError):
# class PreconditionFailed(HTTPClientError):
# class RequestEntityTooLarge(HTTPClientError):
# class RequestUriTooLong(HTTPClientError):
# class UnsupportedMediaType(HTTPClientError):
# class RequestedRangeNotSatisfiable(HTTPClientError):
# class ExpectationFailed(HTTPClientError):
# class UnprocessableEntity(HTTPClientError):
# class InternalServerError(HttpServerError):
# class HttpNotImplemented(HttpServerError):
# class BadGateway(HttpServerError):
# class ServiceUnavailable(HttpServerError):
# class GatewayTimeout(HttpServerError):
# class HttpVersionNotSupported(HttpServerError):
# def __init__(self, opt_names):
# def __init__(self, auth_system):
# def __init__(self, endpoints=None):
# def __init__(self, message=None, details=None,
# response=None, request_id=None,
# url=None, method=None, http_status=None):
# def __init__(self, *args, **kwargs):
# def from_response(response, method, url):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | fake_response = mock.Mock(status_code=http_client.BAD_REQUEST) |
Based on the snippet: <|code_start|># All Rights Reserved.
#
# 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.
@mock.patch.object(exceptions, 'from_response', autospec=True)
class ExcTest(test_utils.BaseTestCase):
def setUp(self):
super(ExcTest, self).setUp()
self.message = 'SpongeBob SquarePants'
self.traceback = 'Foo Traceback'
self.method = 'call_spongebob'
self.url = 'http://foo.bar'
self.expected_json = {'error': {'message': self.message,
'details': self.traceback}}
<|code_end|>
, predict the immediate next line with the help of imports:
from http import client as http_client
from unittest import mock
from ironicclient.common.apiclient import exceptions
from ironicclient import exc
from ironicclient.tests.unit import utils as test_utils
and context (classes, functions, sometimes code) from other files:
# Path: ironicclient/common/apiclient/exceptions.py
# class ClientException(Exception):
# class ValidationError(ClientException):
# class UnsupportedVersion(ClientException):
# class CommandError(ClientException):
# class AuthorizationFailure(ClientException):
# class ConnectionError(ClientException):
# class ConnectionRefused(ConnectionError):
# class AuthPluginOptionsMissing(AuthorizationFailure):
# class AuthSystemNotFound(AuthorizationFailure):
# class NoUniqueMatch(ClientException):
# class EndpointException(ClientException):
# class EndpointNotFound(EndpointException):
# class AmbiguousEndpoints(EndpointException):
# class HttpError(ClientException):
# class HTTPRedirection(HttpError):
# class HTTPClientError(HttpError):
# class HttpServerError(HttpError):
# class MultipleChoices(HTTPRedirection):
# class BadRequest(HTTPClientError):
# class Unauthorized(HTTPClientError):
# class PaymentRequired(HTTPClientError):
# class Forbidden(HTTPClientError):
# class NotFound(HTTPClientError):
# class MethodNotAllowed(HTTPClientError):
# class NotAcceptable(HTTPClientError):
# class ProxyAuthenticationRequired(HTTPClientError):
# class RequestTimeout(HTTPClientError):
# class Conflict(HTTPClientError):
# class Gone(HTTPClientError):
# class LengthRequired(HTTPClientError):
# class PreconditionFailed(HTTPClientError):
# class RequestEntityTooLarge(HTTPClientError):
# class RequestUriTooLong(HTTPClientError):
# class UnsupportedMediaType(HTTPClientError):
# class RequestedRangeNotSatisfiable(HTTPClientError):
# class ExpectationFailed(HTTPClientError):
# class UnprocessableEntity(HTTPClientError):
# class InternalServerError(HttpServerError):
# class HttpNotImplemented(HttpServerError):
# class BadGateway(HttpServerError):
# class ServiceUnavailable(HttpServerError):
# class GatewayTimeout(HttpServerError):
# class HttpVersionNotSupported(HttpServerError):
# def __init__(self, opt_names):
# def __init__(self, auth_system):
# def __init__(self, endpoints=None):
# def __init__(self, message=None, details=None,
# response=None, request_id=None,
# url=None, method=None, http_status=None):
# def __init__(self, *args, **kwargs):
# def from_response(response, method, url):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | def test_from_response(self, mock_apiclient): |
Continue the code 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.
LOG = logging.getLogger(__name__)
def get_client(api_version, auth_type=None, os_ironic_api_version=None,
max_retries=None, retry_interval=None, session=None,
valid_interfaces=None, interface=None, service_type=None,
<|code_end|>
. Use current file imports:
import logging
from openstack import config
from oslo_utils import importutils
from ironicclient.common.i18n import _
from ironicclient import exc
and context (classes, functions, or code) from other files:
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | region_name=None, additional_headers=None, |
Based on the snippet: <|code_start|> self.assertEqual(1, len(ports))
def test_ports_list_by_address(self):
ports = self.mgr.list(address=PORT['address'])
expect = [
('GET', '/v1/ports/?address=%s' % PORT['address'], {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(ports))
def test_ports_list_by_address_detail(self):
ports = self.mgr.list(address=PORT['address'], detail=True)
expect = [
('GET', '/v1/ports/detail?address=%s' % PORT['address'], {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(ports))
def test_ports_list_by_node(self):
ports = self.mgr.list(node=PORT['node_uuid'])
expect = [
('GET', '/v1/ports/?node=%s' % PORT['node_uuid'], {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(ports))
def test_ports_list_by_portgroup(self):
ports = self.mgr.list(portgroup=PORT['portgroup_uuid'])
expect = [
('GET', '/v1/ports/?portgroup=%s' % PORT['portgroup_uuid'],
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import testtools
import ironicclient.v1.port
from testtools.matchers import HasLength
from ironicclient import exc
from ironicclient.tests.unit import utils
and context (classes, functions, sometimes code) from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | {}, None), |
Given the code snippet: <|code_start|> '/v1/ports/detail?address=%s' % PORT['address']:
{
'GET': (
{},
{"ports": [PORT]},
),
},
'/v1/ports/?address=%s' % PORT['address']:
{
'GET': (
{},
{"ports": [PORT]},
),
},
'/v1/ports/?node=%s' % PORT['node_uuid']:
{
'GET': (
{},
{"ports": [PORT]},
),
},
'/v1/ports/?portgroup=%s' % PORT['portgroup_uuid']:
{
'GET': (
{},
{"ports": [PORT]},
),
},
}
<|code_end|>
, generate the next line using the imports in this file:
import copy
import testtools
import ironicclient.v1.port
from testtools.matchers import HasLength
from ironicclient import exc
from ironicclient.tests.unit import utils
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | fake_responses_pagination = { |
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.
class MakeClientTest(testtools.TestCase):
@mock.patch.object(plugin, 'OS_BAREMETAL_API_LATEST', new=False)
@mock.patch.object(client, 'Client', autospec=True)
def test_make_client_explicit_version(self, mock_client):
instance = fakes.FakeClientManager()
instance.get_endpoint_for_service_type = mock.Mock(
return_value='endpoint')
plugin.make_client(instance)
mock_client.assert_called_once_with(
os_ironic_api_version=fakes.API_VERSION,
<|code_end|>
with the help of current file imports:
import argparse
import testtools
from unittest import mock
from ironicclient.osc import plugin
from ironicclient.tests.unit.osc import fakes
from ironicclient.v1 import client
and context from other files:
# Path: ironicclient/osc/plugin.py
# LOG = logging.getLogger(__name__)
# CLIENT_CLASS = 'ironicclient.v1.client.Client'
# API_VERSION_OPTION = 'os_baremetal_api_version'
# API_NAME = 'baremetal'
# LAST_KNOWN_API_VERSION = http.LAST_KNOWN_API_VERSION
# LATEST_VERSION = http.LATEST_VERSION
# API_VERSIONS = {
# '1.%d' % i: CLIENT_CLASS
# for i in range(1, LAST_KNOWN_API_VERSION + 1)
# }
# API_VERSIONS['1'] = CLIENT_CLASS
# OS_BAREMETAL_API_LATEST = True
# OS_BAREMETAL_API_LATEST = False
# OS_BAREMETAL_API_LATEST = True
# OS_BAREMETAL_API_LATEST = False
# def make_client(instance):
# def build_option_parser(parser):
# def _get_environment_version(default):
# def __call__(self, parser, namespace, values, option_string=None):
# class ReplaceLatestVersion(argparse.Action):
#
# Path: ironicclient/tests/unit/osc/fakes.py
# AUTH_TOKEN = "foobar"
# AUTH_URL = "http://0.0.0.0"
# API_VERSION = '1.6'
# class FakeApp(object):
# class FakeClientManager(object):
# class FakeResource(object):
# def __init__(self):
# def __init__(self):
# def __init__(self, manager, info, loaded=False):
# def _add_details(self, info):
# def __repr__(self):
#
# Path: ironicclient/v1/client.py
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(self, endpoint_override=None, *args, **kwargs):
# def current_api_version(self):
# def is_api_version_negotiated(self):
# def negotiate_api_version(self):
, which may contain function names, class names, or code. Output only the next line. | allow_api_version_downgrade=False, |
Given snippet: <|code_start|> instance.get_endpoint_for_service_type.assert_called_once_with(
'baremetal', region_name=instance._region_name,
interface=instance.interface)
@mock.patch.object(plugin, 'OS_BAREMETAL_API_LATEST', new=False)
@mock.patch.object(client, 'Client', autospec=True)
def test_make_client_v1(self, mock_client):
instance = fakes.FakeClientManager()
instance.get_endpoint_for_service_type = mock.Mock(
return_value='endpoint')
instance._api_version = {'baremetal': '1'}
plugin.make_client(instance)
mock_client.assert_called_once_with(
os_ironic_api_version=plugin.LATEST_VERSION,
allow_api_version_downgrade=True,
session=instance.session,
region_name=instance._region_name,
endpoint_override='endpoint')
instance.get_endpoint_for_service_type.assert_called_once_with(
'baremetal', region_name=instance._region_name,
interface=instance.interface)
@mock.patch.object(plugin, 'OS_BAREMETAL_API_LATEST', new=True)
@mock.patch.object(argparse.ArgumentParser, 'add_argument', autospec=True)
class BuildOptionParserTest(testtools.TestCase):
@mock.patch.object(plugin.utils, 'env', lambda x: None)
def test_build_option_parser(self, mock_add_argument):
parser = argparse.ArgumentParser()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import testtools
from unittest import mock
from ironicclient.osc import plugin
from ironicclient.tests.unit.osc import fakes
from ironicclient.v1 import client
and context:
# Path: ironicclient/osc/plugin.py
# LOG = logging.getLogger(__name__)
# CLIENT_CLASS = 'ironicclient.v1.client.Client'
# API_VERSION_OPTION = 'os_baremetal_api_version'
# API_NAME = 'baremetal'
# LAST_KNOWN_API_VERSION = http.LAST_KNOWN_API_VERSION
# LATEST_VERSION = http.LATEST_VERSION
# API_VERSIONS = {
# '1.%d' % i: CLIENT_CLASS
# for i in range(1, LAST_KNOWN_API_VERSION + 1)
# }
# API_VERSIONS['1'] = CLIENT_CLASS
# OS_BAREMETAL_API_LATEST = True
# OS_BAREMETAL_API_LATEST = False
# OS_BAREMETAL_API_LATEST = True
# OS_BAREMETAL_API_LATEST = False
# def make_client(instance):
# def build_option_parser(parser):
# def _get_environment_version(default):
# def __call__(self, parser, namespace, values, option_string=None):
# class ReplaceLatestVersion(argparse.Action):
#
# Path: ironicclient/tests/unit/osc/fakes.py
# AUTH_TOKEN = "foobar"
# AUTH_URL = "http://0.0.0.0"
# API_VERSION = '1.6'
# class FakeApp(object):
# class FakeClientManager(object):
# class FakeResource(object):
# def __init__(self):
# def __init__(self):
# def __init__(self, manager, info, loaded=False):
# def _add_details(self, info):
# def __repr__(self):
#
# Path: ironicclient/v1/client.py
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(self, endpoint_override=None, *args, **kwargs):
# def current_api_version(self):
# def is_api_version_negotiated(self):
# def negotiate_api_version(self):
which might include code, classes, or functions. Output only the next line. | mock_add_argument.reset_mock() |
Given snippet: <|code_start|> version_list = ['1'] + ['1.%d' % i for i in range(
1, plugin.LAST_KNOWN_API_VERSION + 1)] + ['latest']
mock_add_argument.assert_called_once_with(
mock.ANY, '--os-baremetal-api-version',
action=plugin.ReplaceLatestVersion, choices=version_list,
default='1.1', help=mock.ANY,
metavar='<baremetal-api-version>')
self.assertFalse(plugin.OS_BAREMETAL_API_LATEST)
@mock.patch.object(plugin.utils, 'env', lambda x: None)
class ReplaceLatestVersionTest(testtools.TestCase):
@mock.patch.object(plugin, 'OS_BAREMETAL_API_LATEST', new=False)
def test___call___latest(self):
parser = argparse.ArgumentParser()
plugin.build_option_parser(parser)
namespace = argparse.Namespace()
parser.parse_known_args(['--os-baremetal-api-version', 'latest'],
namespace)
self.assertEqual(plugin.LATEST_VERSION,
namespace.os_baremetal_api_version)
self.assertTrue(plugin.OS_BAREMETAL_API_LATEST)
@mock.patch.object(plugin, 'OS_BAREMETAL_API_LATEST', new=True)
def test___call___specific_version(self):
parser = argparse.ArgumentParser()
plugin.build_option_parser(parser)
namespace = argparse.Namespace()
parser.parse_known_args(['--os-baremetal-api-version', '1.4'],
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import testtools
from unittest import mock
from ironicclient.osc import plugin
from ironicclient.tests.unit.osc import fakes
from ironicclient.v1 import client
and context:
# Path: ironicclient/osc/plugin.py
# LOG = logging.getLogger(__name__)
# CLIENT_CLASS = 'ironicclient.v1.client.Client'
# API_VERSION_OPTION = 'os_baremetal_api_version'
# API_NAME = 'baremetal'
# LAST_KNOWN_API_VERSION = http.LAST_KNOWN_API_VERSION
# LATEST_VERSION = http.LATEST_VERSION
# API_VERSIONS = {
# '1.%d' % i: CLIENT_CLASS
# for i in range(1, LAST_KNOWN_API_VERSION + 1)
# }
# API_VERSIONS['1'] = CLIENT_CLASS
# OS_BAREMETAL_API_LATEST = True
# OS_BAREMETAL_API_LATEST = False
# OS_BAREMETAL_API_LATEST = True
# OS_BAREMETAL_API_LATEST = False
# def make_client(instance):
# def build_option_parser(parser):
# def _get_environment_version(default):
# def __call__(self, parser, namespace, values, option_string=None):
# class ReplaceLatestVersion(argparse.Action):
#
# Path: ironicclient/tests/unit/osc/fakes.py
# AUTH_TOKEN = "foobar"
# AUTH_URL = "http://0.0.0.0"
# API_VERSION = '1.6'
# class FakeApp(object):
# class FakeClientManager(object):
# class FakeResource(object):
# def __init__(self):
# def __init__(self):
# def __init__(self, manager, info, loaded=False):
# def _add_details(self, info):
# def __repr__(self):
#
# Path: ironicclient/v1/client.py
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(self, endpoint_override=None, *args, **kwargs):
# def current_api_version(self):
# def is_api_version_negotiated(self):
# def negotiate_api_version(self):
which might include code, classes, or functions. Output only the next line. | namespace) |
Based on the 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.
_CREATE_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Schema for ironic resources file",
"type": "object",
"properties": {
"chassis": {
"type": "array",
"items": {
"type": "object"
}
},
"nodes": {
"type": "array",
"items": {
<|code_end|>
, predict the immediate next line with the help of imports:
import functools
import json
import jsonschema
import yaml
from ironicclient import exc
and context (classes, functions, sometimes code) from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | "type": "object" |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# 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 HumanResource(base.Resource):
HUMAN_ID = True
class HumanResourceManager(base.ManagerWithFind):
resource_class = HumanResource
def list(self):
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from oslotest import base as test_base
from ironicclient.common.apiclient import base
and context including class names, function names, and sometimes code from other files:
# Path: ironicclient/common/apiclient/base.py
# def getid(obj):
# def add_hook(cls, hook_type, hook_func):
# def run_hooks(cls, hook_type, *args, **kwargs):
# def __init__(self, client):
# def _list(self, url, response_key=None, obj_class=None, json=None):
# def _get(self, url, response_key=None):
# def _head(self, url):
# def _post(self, url, json, response_key=None, return_raw=False):
# def _put(self, url, json=None, response_key=None):
# def _patch(self, url, json=None, response_key=None):
# def _delete(self, url):
# def list(self):
# def find(self, **kwargs):
# def findall(self, **kwargs):
# def build_url(self, base_url=None, **kwargs):
# def _filter_kwargs(self, kwargs):
# def create(self, **kwargs):
# def get(self, **kwargs):
# def head(self, **kwargs):
# def list(self, base_url=None, **kwargs):
# def put(self, base_url=None, **kwargs):
# def update(self, **kwargs):
# def delete(self, **kwargs):
# def find(self, base_url=None, **kwargs):
# def __init__(self, name, module):
# def _parse_extension_module(self):
# def __repr__(self):
# def __init__(self, manager, info, loaded=False):
# def __repr__(self):
# def human_id(self):
# def _add_details(self, info):
# def __getattr__(self, k):
# def get(self):
# def __eq__(self, other):
# def is_loaded(self):
# def set_loaded(self, val):
# def to_dict(self):
# class HookableMixin(object):
# class BaseManager(HookableMixin):
# class ManagerWithFind(BaseManager, metaclass=abc.ABCMeta):
# class CrudManager(BaseManager):
# class Extension(HookableMixin):
# class Resource(object):
# SUPPORTED_HOOKS = ('__pre_parse_args__', '__post_parse_args__')
# HUMAN_ID = False
# NAME_ATTR = 'name'
. Output only the next line. | return self._list("/human_resources", "human_resources") |
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.
class Conductor(base.Resource):
def __repr__(self):
return "<Conductor %s>" % self._info
class ConductorManager(base.Manager):
resource_class = Conductor
<|code_end|>
. Write the next line using the current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may include functions, classes, or code. Output only the next line. | _resource_name = 'conductors' |
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.
class Conductor(base.Resource):
def __repr__(self):
return "<Conductor %s>" % self._info
class ConductorManager(base.Manager):
resource_class = Conductor
_resource_name = 'conductors'
def list(self, marker=None, limit=None, sort_key=None, sort_dir=None,
<|code_end|>
with the help of current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may contain function names, class names, or code. Output only the next line. | fields=None, detail=False, os_ironic_api_version=None, |
Using the 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.
class Conductor(base.Resource):
def __repr__(self):
return "<Conductor %s>" % self._info
class ConductorManager(base.Manager):
resource_class = Conductor
_resource_name = 'conductors'
def list(self, marker=None, limit=None, sort_key=None, sort_dir=None,
fields=None, detail=False, os_ironic_api_version=None,
<|code_end|>
, determine the next line of code. You have imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (class names, function names, or code) available:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | global_request_id=None): |
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.
@mock.patch.object(http, '_construct_http_client', autospec=True)
class ClientTest(utils.BaseTestCase):
session = mock.sentinel.session
def test_client_user_api_version(self, http_client_mock):
endpoint = 'http://ironic:6385'
<|code_end|>
. Write the next line using the current file imports:
from unittest import mock
from ironicclient.common import filecache
from ironicclient.common import http
from ironicclient.tests.unit import utils
from ironicclient.v1 import client
and context from other files:
# Path: ironicclient/common/filecache.py
# LOG = logging.getLogger(__name__)
# AUTHOR = 'openstack'
# PROGNAME = 'python-ironicclient'
# CACHE = None
# CACHE_DIR = appdirs.user_cache_dir(PROGNAME, AUTHOR)
# CACHE_EXPIRY_ENV_VAR = 'IRONICCLIENT_CACHE_EXPIRY' # environment variable
# CACHE_FILENAME = os.path.join(CACHE_DIR, 'ironic-api-version.dbm')
# DEFAULT_EXPIRY = 300 # seconds
# CACHE = dogpile.cache.make_region(key_mangler=str).configure(
# 'dogpile.cache.dbm',
# expiration_time=expiry_time,
# arguments={
# "filename": CACHE_FILENAME,
# }
# )
# def _get_cache():
# def _build_key(host, port):
# def save_data(host, port, data):
# def retrieve_data(host, port, expiry=None):
#
# Path: ironicclient/common/http.py
# DEFAULT_VER = '1.9'
# LAST_KNOWN_API_VERSION = 78
# LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
# LOG = logging.getLogger(__name__)
# USER_AGENT = 'python-ironicclient'
# CHUNKSIZE = 1024 * 64 # 64kB
# _MAJOR_VERSION = 1
# API_VERSION = '/v%d' % _MAJOR_VERSION
# API_VERSION_SELECTED_STATES = ('user', 'negotiated', 'cached', 'default')
# DEFAULT_MAX_RETRIES = 5
# DEFAULT_RETRY_INTERVAL = 2
# SENSITIVE_HEADERS = ('X-Auth-Token',)
# SUPPORTED_ENDPOINT_SCHEME = ('http', 'https')
# _API_VERSION_RE = re.compile(r'/+(v%d)?/*$' % _MAJOR_VERSION)
# _RETRY_EXCEPTIONS = (exc.Conflict, exc.ServiceUnavailable,
# exc.ConnectionRefused, kexc.RetriableConnectionFailure)
# def _trim_endpoint_api_version(url):
# def _extract_error_json(body):
# def get_server(url):
# def negotiate_version(self, conn, resp):
# def _query_server(conn):
# def _generic_parse_version_headers(self, accessor_func):
# def _parse_version_headers(self, accessor_func):
# def _make_simple_request(self, conn, method, url):
# def _must_negotiate_version(self):
# def with_retries(func):
# def wrapper(self, url, method, **kwargs):
# def __init__(self,
# os_ironic_api_version,
# api_version_select_state,
# max_retries,
# retry_interval,
# **kwargs):
# def _parse_version_headers(self, resp):
# def _get_endpoint_filter(self):
# def _make_simple_request(self, conn, method, url):
# def _http_request(self, url, method, **kwargs):
# def json_request(self, method, url, **kwargs):
# def raw_request(self, method, url, **kwargs):
# def _construct_http_client(session,
# token=None,
# auth_ref=None,
# os_ironic_api_version=DEFAULT_VER,
# api_version_select_state='default',
# max_retries=DEFAULT_MAX_RETRIES,
# retry_interval=DEFAULT_RETRY_INTERVAL,
# timeout=600,
# ca_file=None,
# cert_file=None,
# key_file=None,
# insecure=None,
# **kwargs):
# class VersionNegotiationMixin(object):
# class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/client.py
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(self, endpoint_override=None, *args, **kwargs):
# def current_api_version(self):
# def is_api_version_negotiated(self):
# def negotiate_api_version(self):
, which may include functions, classes, or code. Output only the next line. | os_ironic_api_version = '1.15' |
Continue the code 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.
class FileCacheTest(utils.BaseTestCase):
def test__build_key_ok(self):
result = filecache._build_key('localhost', '5000')
<|code_end|>
. Use current file imports:
import os
import dogpile.cache
from unittest import mock
from ironicclient.common import filecache
from ironicclient.tests.unit import utils
and context (classes, functions, or code) from other files:
# Path: ironicclient/common/filecache.py
# LOG = logging.getLogger(__name__)
# AUTHOR = 'openstack'
# PROGNAME = 'python-ironicclient'
# CACHE = None
# CACHE_DIR = appdirs.user_cache_dir(PROGNAME, AUTHOR)
# CACHE_EXPIRY_ENV_VAR = 'IRONICCLIENT_CACHE_EXPIRY' # environment variable
# CACHE_FILENAME = os.path.join(CACHE_DIR, 'ironic-api-version.dbm')
# DEFAULT_EXPIRY = 300 # seconds
# CACHE = dogpile.cache.make_region(key_mangler=str).configure(
# 'dogpile.cache.dbm',
# expiration_time=expiry_time,
# arguments={
# "filename": CACHE_FILENAME,
# }
# )
# def _get_cache():
# def _build_key(host, port):
# def save_data(host, port, data):
# def retrieve_data(host, port, expiry=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | self.assertEqual('localhost:5000', result) |
Based on the snippet: <|code_start|> result = filecache._build_key(None, None)
self.assertEqual('None:None', result)
@mock.patch.object(filecache, 'CACHE', None)
@mock.patch.object(os.environ, 'get', autospec=True)
@mock.patch.object(os.path, 'exists', autospec=True)
@mock.patch.object(os, 'makedirs', autospec=True)
@mock.patch.object(dogpile.cache, 'make_region', autospec=True)
def test__get_cache_mkdir(self, mock_makeregion, mock_makedirs,
mock_exists, mock_get):
cache_val = 6
# If not present in the env, get will return the defaulted value
mock_get.return_value = filecache.DEFAULT_EXPIRY
mock_exists.return_value = False
cache_region = mock.Mock(spec=dogpile.cache.region.CacheRegion)
cache_region.configure.return_value = cache_val
mock_makeregion.return_value = cache_region
self.assertEqual(cache_val, filecache._get_cache())
self.assertEqual(cache_val, filecache.CACHE)
mock_exists.assert_called_once_with(filecache.CACHE_DIR)
mock_makedirs.assert_called_once_with(filecache.CACHE_DIR)
mock_get.assert_called_once_with(filecache.CACHE_EXPIRY_ENV_VAR,
mock.ANY)
cache_region.configure.assert_called_once_with(
mock.ANY,
arguments=mock.ANY,
expiration_time=filecache.DEFAULT_EXPIRY)
@mock.patch.object(filecache, 'CACHE', None)
@mock.patch.object(os.environ, 'get', autospec=True)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import dogpile.cache
from unittest import mock
from ironicclient.common import filecache
from ironicclient.tests.unit import utils
and context (classes, functions, sometimes code) from other files:
# Path: ironicclient/common/filecache.py
# LOG = logging.getLogger(__name__)
# AUTHOR = 'openstack'
# PROGNAME = 'python-ironicclient'
# CACHE = None
# CACHE_DIR = appdirs.user_cache_dir(PROGNAME, AUTHOR)
# CACHE_EXPIRY_ENV_VAR = 'IRONICCLIENT_CACHE_EXPIRY' # environment variable
# CACHE_FILENAME = os.path.join(CACHE_DIR, 'ironic-api-version.dbm')
# DEFAULT_EXPIRY = 300 # seconds
# CACHE = dogpile.cache.make_region(key_mangler=str).configure(
# 'dogpile.cache.dbm',
# expiration_time=expiry_time,
# arguments={
# "filename": CACHE_FILENAME,
# }
# )
# def _get_cache():
# def _build_key(host, port):
# def save_data(host, port, data):
# def retrieve_data(host, port, expiry=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | @mock.patch.object(os.path, 'exists', autospec=True) |
Predict the next line after this snippet: <|code_start|> 'default_management_interface': baremetal_driver_default_management_if,
'default_network_interface': baremetal_driver_default_network_if,
'default_power_interface': baremetal_driver_default_power_if,
'default_raid_interface': baremetal_driver_default_raid_if,
'default_rescue_interface': baremetal_driver_default_rescue_if,
'default_storage_interface': baremetal_driver_default_storage_if,
'default_vendor_interface': baremetal_driver_default_vendor_if,
'enabled_bios_interfaces': baremetal_driver_enabled_bios_ifs,
'enabled_boot_interfaces': baremetal_driver_enabled_boot_ifs,
'enabled_console_interfaces': baremetal_driver_enabled_console_ifs,
'enabled_deploy_interfaces': baremetal_driver_enabled_deploy_ifs,
'enabled_inspect_interfaces': baremetal_driver_enabled_inspect_ifs,
'enabled_management_interfaces': baremetal_driver_enabled_management_ifs,
'enabled_network_interfaces': baremetal_driver_enabled_network_ifs,
'enabled_power_interfaces': baremetal_driver_enabled_power_ifs,
'enabled_raid_interfaces': baremetal_driver_enabled_raid_ifs,
'enabled_rescue_interfaces': baremetal_driver_enabled_rescue_ifs,
'enabled_storage_interfaces': baremetal_driver_enabled_storage_ifs,
'enabled_vendor_interfaces': baremetal_driver_enabled_vendor_ifs,
}
baremetal_driver_passthru_method = 'lookup'
BAREMETAL_DRIVER_PASSTHRU = {"lookup": {"attach": "false",
"http_methods": ["POST"],
"description": "",
"async": "false"}}
baremetal_portgroup_uuid = 'ppp-gggggg-pppp'
baremetal_portgroup_name = 'Portgroup-name'
<|code_end|>
using the current file's imports:
import json
from unittest import mock
from osc_lib.tests import utils
from ironicclient.tests.unit.osc import fakes
and any relevant context from other files:
# Path: ironicclient/tests/unit/osc/fakes.py
# AUTH_TOKEN = "foobar"
# AUTH_URL = "http://0.0.0.0"
# API_VERSION = '1.6'
# class FakeApp(object):
# class FakeClientManager(object):
# class FakeResource(object):
# def __init__(self):
# def __init__(self):
# def __init__(self, manager, info, loaded=False):
# def _add_details(self, info):
# def __repr__(self):
. Output only the next line. | baremetal_portgroup_address = 'AA:BB:CC:CC:BB:AA' |
Here is a snippet: <|code_start|> {},
{'drivers': [DRIVER1]},
),
},
'/v1/drivers/?fields=name,hosts':
{
'GET': (
{},
{'drivers': [DRIVER1]}
)
},
'/v1/drivers/%s' % DRIVER1['name']:
{
'GET': (
{},
DRIVER1
),
},
'/v1/drivers/%s?fields=name,hosts' % DRIVER1['name']:
{
'GET': (
{},
DRIVER1,
),
},
'/v1/drivers/%s/properties' % DRIVER2['name']:
{
'GET': (
{},
DRIVER2_PROPERTIES,
<|code_end|>
. Write the next line using the current file imports:
from unittest import mock
from testtools import matchers
from ironicclient import exc
from ironicclient.tests.unit import utils
from ironicclient.v1 import driver
import testtools
and context from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/driver.py
# class Driver(base.Resource):
# class DriverManager(base.Manager):
# def __repr__(self):
# def list(self, driver_type=None, detail=None, os_ironic_api_version=None,
# global_request_id=None, fields=None):
# def get(self, driver_name, os_ironic_api_version=None,
# global_request_id=None, fields=None):
# def update(self, driver_name, patch, http_method='PATCH',
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, driver_name, os_ironic_api_version=None,
# global_request_id=None):
# def properties(self, driver_name, os_ironic_api_version=None,
# global_request_id=None):
# def raid_logical_disk_properties(self, driver_name,
# os_ironic_api_version=None,
# global_request_id=None):
# def vendor_passthru(self, driver_name, method, args=None,
# http_method=None, os_ironic_api_version=None,
# global_request_id=None):
# def get_vendor_passthru_methods(self, driver_name,
# os_ironic_api_version=None,
# global_request_id=None):
, which may include functions, classes, or code. Output only the next line. | ), |
Given the following code snippet before the placeholder: <|code_start|> ]
self.assertEqual(expect, self.api.calls)
driver_attr = {}
for attr in DRIVER1.keys():
driver_attr[attr] = getattr(driver_, attr)
self.assertEqual(DRIVER1, driver_attr)
def test_driver_list_fields(self):
drivers = self.mgr.list(fields=['name', 'hosts'])
expect = [
('GET', '/v1/drivers/?fields=name,hosts', {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertThat(drivers, matchers.HasLength(1))
def test_driver_show_fields(self):
driver_ = self.mgr.get(DRIVER1['name'], fields=['name', 'hosts'])
expect = [
('GET', '/v1/drivers/%s?fields=name,hosts' %
DRIVER1['name'], {}, None)
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(DRIVER1['name'], driver_.name)
self.assertEqual(DRIVER1['hosts'], driver_.hosts)
def test_driver_properties(self):
properties = self.mgr.properties(DRIVER2['name'])
expect = [
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from testtools import matchers
from ironicclient import exc
from ironicclient.tests.unit import utils
from ironicclient.v1 import driver
import testtools
and context including class names, function names, and sometimes code from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/driver.py
# class Driver(base.Resource):
# class DriverManager(base.Manager):
# def __repr__(self):
# def list(self, driver_type=None, detail=None, os_ironic_api_version=None,
# global_request_id=None, fields=None):
# def get(self, driver_name, os_ironic_api_version=None,
# global_request_id=None, fields=None):
# def update(self, driver_name, patch, http_method='PATCH',
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, driver_name, os_ironic_api_version=None,
# global_request_id=None):
# def properties(self, driver_name, os_ironic_api_version=None,
# global_request_id=None):
# def raid_logical_disk_properties(self, driver_name,
# os_ironic_api_version=None,
# global_request_id=None):
# def vendor_passthru(self, driver_name, method, args=None,
# http_method=None, os_ironic_api_version=None,
# global_request_id=None):
# def get_vendor_passthru_methods(self, driver_name,
# os_ironic_api_version=None,
# global_request_id=None):
. Output only the next line. | ('GET', '/v1/drivers/%s/properties' % DRIVER2['name'], {}, None), |
Predict the next line for this snippet: <|code_start|>fake_responses = {
'/v1/drivers':
{
'GET': (
{},
{'drivers': [DRIVER1]},
),
},
'/v1/drivers/?fields=name,hosts':
{
'GET': (
{},
{'drivers': [DRIVER1]}
)
},
'/v1/drivers/%s' % DRIVER1['name']:
{
'GET': (
{},
DRIVER1
),
},
'/v1/drivers/%s?fields=name,hosts' % DRIVER1['name']:
{
'GET': (
{},
DRIVER1,
),
},
'/v1/drivers/%s/properties' % DRIVER2['name']:
<|code_end|>
with the help of current file imports:
from unittest import mock
from testtools import matchers
from ironicclient import exc
from ironicclient.tests.unit import utils
from ironicclient.v1 import driver
import testtools
and context from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/driver.py
# class Driver(base.Resource):
# class DriverManager(base.Manager):
# def __repr__(self):
# def list(self, driver_type=None, detail=None, os_ironic_api_version=None,
# global_request_id=None, fields=None):
# def get(self, driver_name, os_ironic_api_version=None,
# global_request_id=None, fields=None):
# def update(self, driver_name, patch, http_method='PATCH',
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, driver_name, os_ironic_api_version=None,
# global_request_id=None):
# def properties(self, driver_name, os_ironic_api_version=None,
# global_request_id=None):
# def raid_logical_disk_properties(self, driver_name,
# os_ironic_api_version=None,
# global_request_id=None):
# def vendor_passthru(self, driver_name, method, args=None,
# http_method=None, os_ironic_api_version=None,
# global_request_id=None):
# def get_vendor_passthru_methods(self, driver_name,
# os_ironic_api_version=None,
# global_request_id=None):
, which may contain function names, class names, or code. Output only the next line. | { |
Predict the next line after this snippet: <|code_start|> 'extra': {}}
TARGET2 = {'uuid': '66666666-7777-8888-9999-000000000000',
'node_uuid': NODE_UUID,
'volume_type': 'fibre_channel',
'properties': {'target_wwn': 'foobar'},
'boot_index': 1,
'volume_id': '87654321',
'extra': {}}
CREATE_TARGET = copy.deepcopy(TARGET1)
del CREATE_TARGET['uuid']
CREATE_TARGET_WITH_UUID = copy.deepcopy(TARGET1)
UPDATED_TARGET = copy.deepcopy(TARGET1)
NEW_VALUE = '100'
UPDATED_TARGET['boot_index'] = NEW_VALUE
fake_responses = {
'/v1/volume/targets':
{
'GET': (
{},
{"targets": [TARGET1]},
),
'POST': (
{},
TARGET1
),
<|code_end|>
using the current file's imports:
import copy
import testtools
import ironicclient.v1.port
from ironicclient import exc
from ironicclient.tests.unit import utils
and any relevant context from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | }, |
Given the code snippet: <|code_start|> },
}
class VolumeTargetManagerTestBase(testtools.TestCase):
def _validate_obj(self, expect, obj):
self.assertEqual(expect['uuid'], obj.uuid)
self.assertEqual(expect['volume_type'], obj.volume_type)
self.assertEqual(expect['boot_index'], obj.boot_index)
self.assertEqual(expect['volume_id'], obj.volume_id)
self.assertEqual(expect['node_uuid'], obj.node_uuid)
def _validate_list(self, expect_request,
expect_targets, actual_targets):
self.assertEqual(expect_request, self.api.calls)
self.assertEqual(len(expect_targets), len(actual_targets))
for expect, obj in zip(expect_targets, actual_targets):
self._validate_obj(expect, obj)
class VolumeTargetManagerTest(VolumeTargetManagerTestBase):
def setUp(self):
super(VolumeTargetManagerTest, self).setUp()
self.api = utils.FakeAPI(fake_responses)
self.mgr = ironicclient.v1.volume_target.VolumeTargetManager(self.api)
def test_volume_targets_list(self):
volume_targets = self.mgr.list()
<|code_end|>
, generate the next line using the imports in this file:
import copy
import testtools
import ironicclient.v1.port
from ironicclient import exc
from ironicclient.tests.unit import utils
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | expect = [ |
Using the snippet: <|code_start|>#
# Copyright 2016 Mirantis, Inc.
# All Rights Reserved.
#
# 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 Event(base.Resource):
def __repr__(self):
return "<Event: %s>" % self.name
class EventManager(base.CreateManager):
resource_class = Event
<|code_end|>
, determine the next line of code. You have imports:
from ironicclient.common import base
and context (class names, function names, or code) available:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
. Output only the next line. | _creation_attributes = ['events'] |
Predict the next line after this snippet: <|code_start|> self.assertEqual(expect, self.api.calls)
self.assertThat(conductors, HasLength(1))
def test_conductor_list_marker(self):
self.api = utils.FakeAPI(fake_responses_pagination)
self.mgr = conductor.ConductorManager(self.api)
conductors = self.mgr.list(marker=CONDUCTOR1['hostname'])
expect = [
('GET', '/v1/conductors/?marker=%s' % CONDUCTOR1['hostname'],
{}, None)
]
self.assertEqual(expect, self.api.calls)
self.assertThat(conductors, HasLength(1))
def test_conductor_list_pagination_no_limit(self):
self.api = utils.FakeAPI(fake_responses_pagination)
self.mgr = conductor.ConductorManager(self.api)
conductors = self.mgr.list(limit=0)
expect = [
('GET', '/v1/conductors', {}, None),
('GET', '/v1/conductors/?limit=1', {}, None)
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(2, len(conductors))
def test_conductor_list_sort_key(self):
self.api = utils.FakeAPI(fake_responses_sorting)
self.mgr = conductor.ConductorManager(self.api)
conductors = self.mgr.list(sort_key='updated_at')
expect = [
<|code_end|>
using the current file's imports:
import testtools
from testtools.matchers import HasLength
from ironicclient.tests.unit import utils
from ironicclient.v1 import conductor
and any relevant context from other files:
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/conductor.py
# class Conductor(base.Resource):
# class ConductorManager(base.Manager):
# def __repr__(self):
# def list(self, marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False, os_ironic_api_version=None,
# global_request_id=None):
# def get(self, hostname, fields=None, os_ironic_api_version=None,
# global_request_id=None):
. Output only the next line. | ('GET', '/v1/conductors/?sort_key=updated_at', {}, None) |
Here is a snippet: <|code_start|> },
'/v1/conductors/?sort_dir=desc':
{
'GET': (
{},
{"conductors": [CONDUCTOR2, CONDUCTOR1]}
),
},
}
class ConductorManagerTest(testtools.TestCase):
def setUp(self):
super(ConductorManagerTest, self).setUp()
self.api = utils.FakeAPI(fake_responses)
self.mgr = conductor.ConductorManager(self.api)
def test_conductor_list(self):
conductors = self.mgr.list()
expect = [
('GET', '/v1/conductors', {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(2, len(conductors))
def test_conductor_list_detail(self):
conductors = self.mgr.list(detail=True)
expect = [
('GET', '/v1/conductors/?detail=True', {}, None),
<|code_end|>
. Write the next line using the current file imports:
import testtools
from testtools.matchers import HasLength
from ironicclient.tests.unit import utils
from ironicclient.v1 import conductor
and context from other files:
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/conductor.py
# class Conductor(base.Resource):
# class ConductorManager(base.Manager):
# def __repr__(self):
# def list(self, marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False, os_ironic_api_version=None,
# global_request_id=None):
# def get(self, hostname, fields=None, os_ironic_api_version=None,
# global_request_id=None):
, which may include functions, classes, or code. Output only the next line. | ] |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc
#
# 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 Chassis(base.Resource):
def __repr__(self):
return "<Chassis %s>" % self._info
class ChassisManager(base.CreateManager):
<|code_end|>
, generate the next line using the imports in this file:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | resource_class = Chassis |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc
#
# 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 Chassis(base.Resource):
def __repr__(self):
return "<Chassis %s>" % self._info
class ChassisManager(base.CreateManager):
resource_class = Chassis
_resource_name = 'chassis'
_creation_attributes = ['description', 'extra', 'uuid']
<|code_end|>
. Use current file imports:
(from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | def list(self, marker=None, limit=None, sort_key=None, |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc
#
# 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 Chassis(base.Resource):
def __repr__(self):
return "<Chassis %s>" % self._info
class ChassisManager(base.CreateManager):
resource_class = Chassis
<|code_end|>
. Use current file imports:
(from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | _resource_name = 'chassis' |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc
#
# 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 Chassis(base.Resource):
def __repr__(self):
return "<Chassis %s>" % self._info
class ChassisManager(base.CreateManager):
resource_class = Chassis
_resource_name = 'chassis'
_creation_attributes = ['description', 'extra', 'uuid']
def list(self, marker=None, limit=None, sort_key=None,
sort_dir=None, detail=False, fields=None,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
which might include code, classes, or functions. Output only the next line. | os_ironic_api_version=None, global_request_id=None): |
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.
try:
except ImportError:
ironic_inspector_client = None
_DEFAULTS = {
'auth_type': 'none',
}
_TYPE = 'baremetal'
_INSPECTOR_TYPE = 'baremetal-introspection'
_DESCRIPTION = 'Bare Metal service (ironic) client'
_NAMESPACE = 'openstack.baremetal.v1'
<|code_end|>
with the help of current file imports:
import logging
import sys
import ironic_inspector_client
import openstack
import pbr.version
from cliff import app
from cliff import commandmanager
from openstack import config as os_config
from osc_lib import utils
from ironicclient.common import http
from ironicclient.common.i18n import _
from ironicclient import exc
from ironicclient.v1 import client
and context from other files:
# Path: ironicclient/common/http.py
# DEFAULT_VER = '1.9'
# LAST_KNOWN_API_VERSION = 78
# LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
# LOG = logging.getLogger(__name__)
# USER_AGENT = 'python-ironicclient'
# CHUNKSIZE = 1024 * 64 # 64kB
# _MAJOR_VERSION = 1
# API_VERSION = '/v%d' % _MAJOR_VERSION
# API_VERSION_SELECTED_STATES = ('user', 'negotiated', 'cached', 'default')
# DEFAULT_MAX_RETRIES = 5
# DEFAULT_RETRY_INTERVAL = 2
# SENSITIVE_HEADERS = ('X-Auth-Token',)
# SUPPORTED_ENDPOINT_SCHEME = ('http', 'https')
# _API_VERSION_RE = re.compile(r'/+(v%d)?/*$' % _MAJOR_VERSION)
# _RETRY_EXCEPTIONS = (exc.Conflict, exc.ServiceUnavailable,
# exc.ConnectionRefused, kexc.RetriableConnectionFailure)
# def _trim_endpoint_api_version(url):
# def _extract_error_json(body):
# def get_server(url):
# def negotiate_version(self, conn, resp):
# def _query_server(conn):
# def _generic_parse_version_headers(self, accessor_func):
# def _parse_version_headers(self, accessor_func):
# def _make_simple_request(self, conn, method, url):
# def _must_negotiate_version(self):
# def with_retries(func):
# def wrapper(self, url, method, **kwargs):
# def __init__(self,
# os_ironic_api_version,
# api_version_select_state,
# max_retries,
# retry_interval,
# **kwargs):
# def _parse_version_headers(self, resp):
# def _get_endpoint_filter(self):
# def _make_simple_request(self, conn, method, url):
# def _http_request(self, url, method, **kwargs):
# def json_request(self, method, url, **kwargs):
# def raw_request(self, method, url, **kwargs):
# def _construct_http_client(session,
# token=None,
# auth_ref=None,
# os_ironic_api_version=DEFAULT_VER,
# api_version_select_state='default',
# max_retries=DEFAULT_MAX_RETRIES,
# retry_interval=DEFAULT_RETRY_INTERVAL,
# timeout=600,
# ca_file=None,
# cert_file=None,
# key_file=None,
# insecure=None,
# **kwargs):
# class VersionNegotiationMixin(object):
# class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/client.py
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(self, endpoint_override=None, *args, **kwargs):
# def current_api_version(self):
# def is_api_version_negotiated(self):
# def negotiate_api_version(self):
, which may contain function names, class names, or code. Output only the next line. | _INSPECTOR_NAMESPACE = 'openstack.baremetal_introspection.v1' |
Continue the code snippet: <|code_start|> self.commands = dict(
(cmd[prefix_len:] if cmd.startswith(prefix) else cmd, ep)
for (cmd, ep) in self.commands.items()
)
class App(app.App):
def __init__(self):
version_info = pbr.version.VersionInfo('python-ironicclient')
mgr = CommandManager(_NAMESPACE)
self.config = os_config.OpenStackConfig(override_defaults=_DEFAULTS)
super(App, self).__init__(description=_DESCRIPTION,
version=str(version_info),
command_manager=mgr,
deferred_help=True)
def build_option_parser(self, description, version, argparse_kwargs=None):
parser = super(App, self).build_option_parser(
description, version, argparse_kwargs=argparse_kwargs)
self.config.register_argparse_arguments(parser, sys.argv[1:])
parser.add_argument(
'--os-baremetal-api-version',
metavar='<baremetal-api-version>',
default=utils.env('OS_BAREMETAL_API_VERSION'),
help='Bare metal API version, default="latest" (the maximum '
'version supported by both the client and the server). '
'(Env: OS_BAREMETAL_API_VERSION)',
)
<|code_end|>
. Use current file imports:
import logging
import sys
import ironic_inspector_client
import openstack
import pbr.version
from cliff import app
from cliff import commandmanager
from openstack import config as os_config
from osc_lib import utils
from ironicclient.common import http
from ironicclient.common.i18n import _
from ironicclient import exc
from ironicclient.v1 import client
and context (classes, functions, or code) from other files:
# Path: ironicclient/common/http.py
# DEFAULT_VER = '1.9'
# LAST_KNOWN_API_VERSION = 78
# LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
# LOG = logging.getLogger(__name__)
# USER_AGENT = 'python-ironicclient'
# CHUNKSIZE = 1024 * 64 # 64kB
# _MAJOR_VERSION = 1
# API_VERSION = '/v%d' % _MAJOR_VERSION
# API_VERSION_SELECTED_STATES = ('user', 'negotiated', 'cached', 'default')
# DEFAULT_MAX_RETRIES = 5
# DEFAULT_RETRY_INTERVAL = 2
# SENSITIVE_HEADERS = ('X-Auth-Token',)
# SUPPORTED_ENDPOINT_SCHEME = ('http', 'https')
# _API_VERSION_RE = re.compile(r'/+(v%d)?/*$' % _MAJOR_VERSION)
# _RETRY_EXCEPTIONS = (exc.Conflict, exc.ServiceUnavailable,
# exc.ConnectionRefused, kexc.RetriableConnectionFailure)
# def _trim_endpoint_api_version(url):
# def _extract_error_json(body):
# def get_server(url):
# def negotiate_version(self, conn, resp):
# def _query_server(conn):
# def _generic_parse_version_headers(self, accessor_func):
# def _parse_version_headers(self, accessor_func):
# def _make_simple_request(self, conn, method, url):
# def _must_negotiate_version(self):
# def with_retries(func):
# def wrapper(self, url, method, **kwargs):
# def __init__(self,
# os_ironic_api_version,
# api_version_select_state,
# max_retries,
# retry_interval,
# **kwargs):
# def _parse_version_headers(self, resp):
# def _get_endpoint_filter(self):
# def _make_simple_request(self, conn, method, url):
# def _http_request(self, url, method, **kwargs):
# def json_request(self, method, url, **kwargs):
# def raw_request(self, method, url, **kwargs):
# def _construct_http_client(session,
# token=None,
# auth_ref=None,
# os_ironic_api_version=DEFAULT_VER,
# api_version_select_state='default',
# max_retries=DEFAULT_MAX_RETRIES,
# retry_interval=DEFAULT_RETRY_INTERVAL,
# timeout=600,
# ca_file=None,
# cert_file=None,
# key_file=None,
# insecure=None,
# **kwargs):
# class VersionNegotiationMixin(object):
# class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/client.py
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(self, endpoint_override=None, *args, **kwargs):
# def current_api_version(self):
# def is_api_version_negotiated(self):
# def negotiate_api_version(self):
. Output only the next line. | parser.add_argument( |
Given the code snippet: <|code_start|>try:
except ImportError:
ironic_inspector_client = None
_DEFAULTS = {
'auth_type': 'none',
}
_TYPE = 'baremetal'
_INSPECTOR_TYPE = 'baremetal-introspection'
_DESCRIPTION = 'Bare Metal service (ironic) client'
_NAMESPACE = 'openstack.baremetal.v1'
_INSPECTOR_NAMESPACE = 'openstack.baremetal_introspection.v1'
_HELP = _("%(err)s.\n* Use --os-endpoint for standalone %(project)s.\n"
"* Use --os-auth-url and credentials for authentication.\n"
"* Use --os-cloud to load configuration from clouds.yaml\n"
"* See `%(cmd)s --help` for more details")
LOG = logging.getLogger(__name__)
class ClientManager(object):
def __init__(self, cloud_region, options):
self.cloud_region = cloud_region
self.options = options
self._ironic = None
self._inspector = None
<|code_end|>
, generate the next line using the imports in this file:
import logging
import sys
import ironic_inspector_client
import openstack
import pbr.version
from cliff import app
from cliff import commandmanager
from openstack import config as os_config
from osc_lib import utils
from ironicclient.common import http
from ironicclient.common.i18n import _
from ironicclient import exc
from ironicclient.v1 import client
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/common/http.py
# DEFAULT_VER = '1.9'
# LAST_KNOWN_API_VERSION = 78
# LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
# LOG = logging.getLogger(__name__)
# USER_AGENT = 'python-ironicclient'
# CHUNKSIZE = 1024 * 64 # 64kB
# _MAJOR_VERSION = 1
# API_VERSION = '/v%d' % _MAJOR_VERSION
# API_VERSION_SELECTED_STATES = ('user', 'negotiated', 'cached', 'default')
# DEFAULT_MAX_RETRIES = 5
# DEFAULT_RETRY_INTERVAL = 2
# SENSITIVE_HEADERS = ('X-Auth-Token',)
# SUPPORTED_ENDPOINT_SCHEME = ('http', 'https')
# _API_VERSION_RE = re.compile(r'/+(v%d)?/*$' % _MAJOR_VERSION)
# _RETRY_EXCEPTIONS = (exc.Conflict, exc.ServiceUnavailable,
# exc.ConnectionRefused, kexc.RetriableConnectionFailure)
# def _trim_endpoint_api_version(url):
# def _extract_error_json(body):
# def get_server(url):
# def negotiate_version(self, conn, resp):
# def _query_server(conn):
# def _generic_parse_version_headers(self, accessor_func):
# def _parse_version_headers(self, accessor_func):
# def _make_simple_request(self, conn, method, url):
# def _must_negotiate_version(self):
# def with_retries(func):
# def wrapper(self, url, method, **kwargs):
# def __init__(self,
# os_ironic_api_version,
# api_version_select_state,
# max_retries,
# retry_interval,
# **kwargs):
# def _parse_version_headers(self, resp):
# def _get_endpoint_filter(self):
# def _make_simple_request(self, conn, method, url):
# def _http_request(self, url, method, **kwargs):
# def json_request(self, method, url, **kwargs):
# def raw_request(self, method, url, **kwargs):
# def _construct_http_client(session,
# token=None,
# auth_ref=None,
# os_ironic_api_version=DEFAULT_VER,
# api_version_select_state='default',
# max_retries=DEFAULT_MAX_RETRIES,
# retry_interval=DEFAULT_RETRY_INTERVAL,
# timeout=600,
# ca_file=None,
# cert_file=None,
# key_file=None,
# insecure=None,
# **kwargs):
# class VersionNegotiationMixin(object):
# class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/client.py
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(self, endpoint_override=None, *args, **kwargs):
# def current_api_version(self):
# def is_api_version_negotiated(self):
# def negotiate_api_version(self):
. Output only the next line. | @property |
Using the snippet: <|code_start|> mgr = CommandManager(_NAMESPACE)
self.config = os_config.OpenStackConfig(override_defaults=_DEFAULTS)
super(App, self).__init__(description=_DESCRIPTION,
version=str(version_info),
command_manager=mgr,
deferred_help=True)
def build_option_parser(self, description, version, argparse_kwargs=None):
parser = super(App, self).build_option_parser(
description, version, argparse_kwargs=argparse_kwargs)
self.config.register_argparse_arguments(parser, sys.argv[1:])
parser.add_argument(
'--os-baremetal-api-version',
metavar='<baremetal-api-version>',
default=utils.env('OS_BAREMETAL_API_VERSION'),
help='Bare metal API version, default="latest" (the maximum '
'version supported by both the client and the server). '
'(Env: OS_BAREMETAL_API_VERSION)',
)
parser.add_argument(
'--max-retries',
metavar='<max-retries-number>',
default=http.DEFAULT_MAX_RETRIES,
type=int,
help='Maximum number of retries on connection problems and '
'resource state conflicts'
)
parser.add_argument(
'--retry-interval',
<|code_end|>
, determine the next line of code. You have imports:
import logging
import sys
import ironic_inspector_client
import openstack
import pbr.version
from cliff import app
from cliff import commandmanager
from openstack import config as os_config
from osc_lib import utils
from ironicclient.common import http
from ironicclient.common.i18n import _
from ironicclient import exc
from ironicclient.v1 import client
and context (class names, function names, or code) available:
# Path: ironicclient/common/http.py
# DEFAULT_VER = '1.9'
# LAST_KNOWN_API_VERSION = 78
# LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
# LOG = logging.getLogger(__name__)
# USER_AGENT = 'python-ironicclient'
# CHUNKSIZE = 1024 * 64 # 64kB
# _MAJOR_VERSION = 1
# API_VERSION = '/v%d' % _MAJOR_VERSION
# API_VERSION_SELECTED_STATES = ('user', 'negotiated', 'cached', 'default')
# DEFAULT_MAX_RETRIES = 5
# DEFAULT_RETRY_INTERVAL = 2
# SENSITIVE_HEADERS = ('X-Auth-Token',)
# SUPPORTED_ENDPOINT_SCHEME = ('http', 'https')
# _API_VERSION_RE = re.compile(r'/+(v%d)?/*$' % _MAJOR_VERSION)
# _RETRY_EXCEPTIONS = (exc.Conflict, exc.ServiceUnavailable,
# exc.ConnectionRefused, kexc.RetriableConnectionFailure)
# def _trim_endpoint_api_version(url):
# def _extract_error_json(body):
# def get_server(url):
# def negotiate_version(self, conn, resp):
# def _query_server(conn):
# def _generic_parse_version_headers(self, accessor_func):
# def _parse_version_headers(self, accessor_func):
# def _make_simple_request(self, conn, method, url):
# def _must_negotiate_version(self):
# def with_retries(func):
# def wrapper(self, url, method, **kwargs):
# def __init__(self,
# os_ironic_api_version,
# api_version_select_state,
# max_retries,
# retry_interval,
# **kwargs):
# def _parse_version_headers(self, resp):
# def _get_endpoint_filter(self):
# def _make_simple_request(self, conn, method, url):
# def _http_request(self, url, method, **kwargs):
# def json_request(self, method, url, **kwargs):
# def raw_request(self, method, url, **kwargs):
# def _construct_http_client(session,
# token=None,
# auth_ref=None,
# os_ironic_api_version=DEFAULT_VER,
# api_version_select_state='default',
# max_retries=DEFAULT_MAX_RETRIES,
# retry_interval=DEFAULT_RETRY_INTERVAL,
# timeout=600,
# ca_file=None,
# cert_file=None,
# key_file=None,
# insecure=None,
# **kwargs):
# class VersionNegotiationMixin(object):
# class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/client.py
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(self, endpoint_override=None, *args, **kwargs):
# def current_api_version(self):
# def is_api_version_negotiated(self):
# def negotiate_api_version(self):
. Output only the next line. | metavar='<retry-interval-seconds>', |
Based on the snippet: <|code_start|># Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
# 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 Driver(base.Resource):
def __repr__(self):
return "<Driver %s>" % self._info
class DriverManager(base.Manager):
resource_class = Driver
<|code_end|>
, predict the immediate next line with the help of imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient import exc
and context (classes, functions, sometimes code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | _resource_name = 'drivers' |
Predict the next line for this snippet: <|code_start|># Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
# 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 Driver(base.Resource):
def __repr__(self):
return "<Driver %s>" % self._info
class DriverManager(base.Manager):
resource_class = Driver
_resource_name = 'drivers'
def list(self, driver_type=None, detail=None, os_ironic_api_version=None,
<|code_end|>
with the help of current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may contain function names, class names, or code. Output only the next line. | global_request_id=None, fields=None): |
Next line prediction: <|code_start|># Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
# 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 Driver(base.Resource):
def __repr__(self):
return "<Driver %s>" % self._info
class DriverManager(base.Manager):
<|code_end|>
. Use current file imports:
(from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient import exc)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | resource_class = Driver |
Predict the next line for this snippet: <|code_start|># Copyright 2015 Hitachi Data Systems
#
# 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 VolumeConnector(base.Resource):
def __repr__(self):
return "<VolumeConnector %s>" % self._info
class VolumeConnectorManager(base.CreateManager):
resource_class = VolumeConnector
_creation_attributes = ['extra', 'node_uuid', 'type', 'connector_id',
'uuid']
_resource_name = 'volume/connectors'
def list(self, node=None, limit=None, marker=None, sort_key=None,
<|code_end|>
with the help of current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may contain function names, class names, or code. Output only the next line. | sort_dir=None, detail=False, fields=None, |
Here is a snippet: <|code_start|># Copyright 2015 Hitachi Data Systems
#
# 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 VolumeConnector(base.Resource):
def __repr__(self):
return "<VolumeConnector %s>" % self._info
class VolumeConnectorManager(base.CreateManager):
resource_class = VolumeConnector
_creation_attributes = ['extra', 'node_uuid', 'type', 'connector_id',
'uuid']
_resource_name = 'volume/connectors'
def list(self, node=None, limit=None, marker=None, sort_key=None,
sort_dir=None, detail=False, fields=None,
<|code_end|>
. Write the next line using the current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may include functions, classes, or code. Output only the next line. | os_ironic_api_version=None, global_request_id=None): |
Based on the snippet: <|code_start|># Copyright 2015 Hitachi Data Systems
#
# 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 VolumeConnector(base.Resource):
def __repr__(self):
return "<VolumeConnector %s>" % self._info
class VolumeConnectorManager(base.CreateManager):
resource_class = VolumeConnector
_creation_attributes = ['extra', 'node_uuid', 'type', 'connector_id',
'uuid']
_resource_name = 'volume/connectors'
<|code_end|>
, predict the immediate next line with the help of imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (classes, functions, sometimes code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | def list(self, node=None, limit=None, marker=None, sort_key=None, |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2015 Hitachi Data Systems
#
# 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 VolumeConnector(base.Resource):
def __repr__(self):
return "<VolumeConnector %s>" % self._info
class VolumeConnectorManager(base.CreateManager):
resource_class = VolumeConnector
_creation_attributes = ['extra', 'node_uuid', 'type', 'connector_id',
'uuid']
_resource_name = 'volume/connectors'
<|code_end|>
, predict the next line using imports from the current file:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context including class names, function names, and sometimes code from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | def list(self, node=None, limit=None, marker=None, sort_key=None, |
Here is a snippet: <|code_start|> ]
self.assertEqual(expect, self.api.calls)
self.assertThat(deploy_templates, HasLength(1))
def test_deploy_templates_list_pagination_no_limit(self):
self.api = utils.FakeAPI(fake_responses_pagination)
self.mgr = ironicclient.v1.deploy_template.DeployTemplateManager(
self.api)
deploy_templates = self.mgr.list(limit=0)
expect = [
('GET', '/v1/deploy_templates', {}, None),
('GET', '/v1/deploy_templates/?limit=1', {}, None)
]
self.assertEqual(expect, self.api.calls)
self.assertThat(deploy_templates, HasLength(2))
def test_deploy_templates_list_sort_key(self):
self.api = utils.FakeAPI(fake_responses_sorting)
self.mgr = ironicclient.v1.deploy_template.DeployTemplateManager(
self.api)
deploy_templates = self.mgr.list(sort_key='updated_at')
expect = [
('GET', '/v1/deploy_templates/?sort_key=updated_at', {}, None)
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(2, len(deploy_templates))
def test_deploy_templates_list_sort_dir(self):
self.api = utils.FakeAPI(fake_responses_sorting)
self.mgr = ironicclient.v1.deploy_template.DeployTemplateManager(
<|code_end|>
. Write the next line using the current file imports:
import copy
import testtools
import ironicclient.v1.deploy_template
from testtools.matchers import HasLength
from ironicclient import exc
from ironicclient.tests.unit import utils
and context from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
, which may include functions, classes, or code. Output only the next line. | self.api) |
Here is a snippet: <|code_start|>
class DeployTemplateManagerTest(testtools.TestCase):
def setUp(self):
super(DeployTemplateManagerTest, self).setUp()
self.api = utils.FakeAPI(fake_responses)
self.mgr = ironicclient.v1.deploy_template.DeployTemplateManager(
self.api)
def test_deploy_templates_list(self):
deploy_templates = self.mgr.list()
expect = [
('GET', '/v1/deploy_templates', {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(deploy_templates))
def test_deploy_templates_list_detail(self):
deploy_templates = self.mgr.list(detail=True)
expect = [
('GET', '/v1/deploy_templates/?detail=True', {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(deploy_templates))
def test_deploy_template_list_fields(self):
deploy_templates = self.mgr.list(fields=['uuid', 'name'])
expect = [
('GET', '/v1/deploy_templates/?fields=uuid,name', {}, None),
<|code_end|>
. Write the next line using the current file imports:
import copy
import testtools
import ironicclient.v1.deploy_template
from testtools.matchers import HasLength
from ironicclient import exc
from ironicclient.tests.unit import utils
and context from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
, which may include functions, classes, or code. Output only the next line. | ] |
Predict the next line for this snippet: <|code_start|> {},
TESTABLE_RESOURCE,
),
'DELETE': (
{},
None,
),
'PATCH': (
{},
UPDATED_TESTABLE_RESOURCE,
),
},
}
class TestableResource(base.Resource):
def __repr__(self):
return "<TestableResource %s>" % self._info
class TestableManager(base.CreateManager):
resource_class = TestableResource
_creation_attributes = ['attribute1', 'attribute2']
_resource_name = 'testableresources'
def _path(self, id=None):
return ('/v1/testableresources/%s' % id if id
else '/v1/testableresources')
<|code_end|>
with the help of current file imports:
import copy
import testtools
from unittest import mock
from ironicclient.common import base
from ironicclient import exc
from ironicclient.tests.unit import utils
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
, which may contain function names, class names, or code. Output only the next line. | def get(self, testable_resource_id, fields=None, **kwargs): |
Using the snippet: <|code_start|> global_request_id=REQ_ID)
expect = [
('GET', '/v1/testableresources/%s' % TESTABLE_RESOURCE['uuid'],
{'X-OpenStack-Ironic-API-Version': '1.10',
'X-Openstack-Request-Id': REQ_ID}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(TESTABLE_RESOURCE['uuid'], resource.uuid)
self.assertEqual(TESTABLE_RESOURCE['attribute1'], resource.attribute1)
def test_update(self):
patch = {'op': 'replace',
'value': NEW_ATTRIBUTE_VALUE,
'path': '/attribute1'}
resource = self.manager.update(
testable_resource_id=TESTABLE_RESOURCE['uuid'],
patch=patch
)
expect = [
('PATCH', '/v1/testableresources/%s' % TESTABLE_RESOURCE['uuid'],
{}, patch),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(NEW_ATTRIBUTE_VALUE, resource.attribute1)
def test_update_microversion_and_global_request_id_override(self):
patch = {'op': 'replace',
'value': NEW_ATTRIBUTE_VALUE,
'path': '/attribute1'}
resource = self.manager.update(
<|code_end|>
, determine the next line of code. You have imports:
import copy
import testtools
from unittest import mock
from ironicclient.common import base
from ironicclient import exc
from ironicclient.tests.unit import utils
and context (class names, function names, or code) available:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | testable_resource_id=TESTABLE_RESOURCE['uuid'], |
Next line prediction: <|code_start|>
def test_create(self):
resource = self.manager.create(**CREATE_TESTABLE_RESOURCE)
expect = [
('POST', '/v1/testableresources', {}, CREATE_TESTABLE_RESOURCE),
]
self.assertEqual(expect, self.api.calls)
self.assertTrue(resource)
self.assertIsInstance(resource, TestableResource)
def test_create_microversion_and_global_request_id_override(self):
resource = self.manager.create(
**CREATE_TESTABLE_RESOURCE,
os_ironic_api_version="1.22", global_request_id=REQ_ID)
expect = [
('POST', '/v1/testableresources',
{'X-OpenStack-Ironic-API-Version': '1.22',
'X-Openstack-Request-Id': REQ_ID}, CREATE_TESTABLE_RESOURCE),
]
self.assertEqual(expect, self.api.calls)
self.assertTrue(resource)
self.assertIsInstance(resource, TestableResource)
def test_create_with_invalid_attribute(self):
self.assertRaisesRegex(exc.InvalidAttribute, "non-existent-attribute",
self.manager.create,
**INVALID_ATTRIBUTE_TESTABLE_RESOURCE)
def test__get_microversion_and_global_request_id_override(self):
resource_id = TESTABLE_RESOURCE['uuid']
<|code_end|>
. Use current file imports:
(import copy
import testtools
from unittest import mock
from ironicclient.common import base
from ironicclient import exc
from ironicclient.tests.unit import utils)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | resource = self.manager._get( |
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.
LOG = logging.getLogger(__name__)
class Allocation(base.Resource):
def __repr__(self):
return "<Allocation %s>" % self._info
class AllocationManager(base.CreateManager):
resource_class = Allocation
_resource_name = 'allocations'
_creation_attributes = ['extra', 'name', 'resource_class', 'uuid',
'traits', 'candidate_nodes', 'node', 'owner']
<|code_end|>
with the help of current file imports:
import logging
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may contain function names, class names, or code. Output only the next line. | def list(self, resource_class=None, state=None, node=None, limit=None, |
Continue the code 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.
LOG = logging.getLogger(__name__)
class Allocation(base.Resource):
def __repr__(self):
return "<Allocation %s>" % self._info
class AllocationManager(base.CreateManager):
resource_class = Allocation
_resource_name = 'allocations'
_creation_attributes = ['extra', 'name', 'resource_class', 'uuid',
<|code_end|>
. Use current file imports:
import logging
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (classes, functions, or code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | 'traits', 'candidate_nodes', 'node', 'owner'] |
Given the code 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.
LOG = logging.getLogger(__name__)
class Allocation(base.Resource):
def __repr__(self):
return "<Allocation %s>" % self._info
class AllocationManager(base.CreateManager):
resource_class = Allocation
_resource_name = 'allocations'
_creation_attributes = ['extra', 'name', 'resource_class', 'uuid',
'traits', 'candidate_nodes', 'node', 'owner']
def list(self, resource_class=None, state=None, node=None, limit=None,
<|code_end|>
, generate the next line using the imports in this file:
import logging
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | marker=None, sort_key=None, sort_dir=None, fields=None, |
Here is a snippet: <|code_start|># Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# 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.
# NOTE(deva): Record the latest version that this client was tested with.
# We still have a lot of work to do in the client to implement
# microversion support in the client properly! See
# http://specs.openstack.org/openstack/ironic-specs/specs/kilo/api-microversions.html # noqa
# for full details.
DEFAULT_VER = '1.9'
LAST_KNOWN_API_VERSION = 78
LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
LOG = logging.getLogger(__name__)
USER_AGENT = 'python-ironicclient'
<|code_end|>
. Write the next line using the current file imports:
from distutils.version import StrictVersion
from http import client as http_client
from urllib import parse as urlparse
from keystoneauth1 import adapter
from keystoneauth1 import exceptions as kexc
from ironicclient.common import filecache
from ironicclient.common.i18n import _
from ironicclient import exc
import functools
import json
import logging
import re
import textwrap
import time
and context from other files:
# Path: ironicclient/common/filecache.py
# LOG = logging.getLogger(__name__)
# AUTHOR = 'openstack'
# PROGNAME = 'python-ironicclient'
# CACHE = None
# CACHE_DIR = appdirs.user_cache_dir(PROGNAME, AUTHOR)
# CACHE_EXPIRY_ENV_VAR = 'IRONICCLIENT_CACHE_EXPIRY' # environment variable
# CACHE_FILENAME = os.path.join(CACHE_DIR, 'ironic-api-version.dbm')
# DEFAULT_EXPIRY = 300 # seconds
# CACHE = dogpile.cache.make_region(key_mangler=str).configure(
# 'dogpile.cache.dbm',
# expiration_time=expiry_time,
# arguments={
# "filename": CACHE_FILENAME,
# }
# )
# def _get_cache():
# def _build_key(host, port):
# def save_data(host, port, data):
# def retrieve_data(host, port, expiry=None):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may include functions, classes, or code. Output only the next line. | CHUNKSIZE = 1024 * 64 # 64kB |
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.
# NOTE(deva): Record the latest version that this client was tested with.
# We still have a lot of work to do in the client to implement
# microversion support in the client properly! See
# http://specs.openstack.org/openstack/ironic-specs/specs/kilo/api-microversions.html # noqa
# for full details.
DEFAULT_VER = '1.9'
LAST_KNOWN_API_VERSION = 78
LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
LOG = logging.getLogger(__name__)
USER_AGENT = 'python-ironicclient'
CHUNKSIZE = 1024 * 64 # 64kB
<|code_end|>
. Use current file imports:
(from distutils.version import StrictVersion
from http import client as http_client
from urllib import parse as urlparse
from keystoneauth1 import adapter
from keystoneauth1 import exceptions as kexc
from ironicclient.common import filecache
from ironicclient.common.i18n import _
from ironicclient import exc
import functools
import json
import logging
import re
import textwrap
import time)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/common/filecache.py
# LOG = logging.getLogger(__name__)
# AUTHOR = 'openstack'
# PROGNAME = 'python-ironicclient'
# CACHE = None
# CACHE_DIR = appdirs.user_cache_dir(PROGNAME, AUTHOR)
# CACHE_EXPIRY_ENV_VAR = 'IRONICCLIENT_CACHE_EXPIRY' # environment variable
# CACHE_FILENAME = os.path.join(CACHE_DIR, 'ironic-api-version.dbm')
# DEFAULT_EXPIRY = 300 # seconds
# CACHE = dogpile.cache.make_region(key_mangler=str).configure(
# 'dogpile.cache.dbm',
# expiration_time=expiry_time,
# arguments={
# "filename": CACHE_FILENAME,
# }
# )
# def _get_cache():
# def _build_key(host, port):
# def save_data(host, port, data):
# def retrieve_data(host, port, expiry=None):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | _MAJOR_VERSION = 1 |
Predict the next line after this snippet: <|code_start|># Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# 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.
# NOTE(deva): Record the latest version that this client was tested with.
# We still have a lot of work to do in the client to implement
# microversion support in the client properly! See
# http://specs.openstack.org/openstack/ironic-specs/specs/kilo/api-microversions.html # noqa
# for full details.
DEFAULT_VER = '1.9'
LAST_KNOWN_API_VERSION = 78
LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
LOG = logging.getLogger(__name__)
<|code_end|>
using the current file's imports:
from distutils.version import StrictVersion
from http import client as http_client
from urllib import parse as urlparse
from keystoneauth1 import adapter
from keystoneauth1 import exceptions as kexc
from ironicclient.common import filecache
from ironicclient.common.i18n import _
from ironicclient import exc
import functools
import json
import logging
import re
import textwrap
import time
and any relevant context from other files:
# Path: ironicclient/common/filecache.py
# LOG = logging.getLogger(__name__)
# AUTHOR = 'openstack'
# PROGNAME = 'python-ironicclient'
# CACHE = None
# CACHE_DIR = appdirs.user_cache_dir(PROGNAME, AUTHOR)
# CACHE_EXPIRY_ENV_VAR = 'IRONICCLIENT_CACHE_EXPIRY' # environment variable
# CACHE_FILENAME = os.path.join(CACHE_DIR, 'ironic-api-version.dbm')
# DEFAULT_EXPIRY = 300 # seconds
# CACHE = dogpile.cache.make_region(key_mangler=str).configure(
# 'dogpile.cache.dbm',
# expiration_time=expiry_time,
# arguments={
# "filename": CACHE_FILENAME,
# }
# )
# def _get_cache():
# def _build_key(host, port):
# def save_data(host, port, data):
# def retrieve_data(host, port, expiry=None):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | USER_AGENT = 'python-ironicclient' |
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.
class DeployTemplate(base.Resource):
def __repr__(self):
return "<DeployTemplate %s>" % self._info
class DeployTemplateManager(base.CreateManager):
resource_class = DeployTemplate
_creation_attributes = ['extra', 'name', 'steps', 'uuid']
<|code_end|>
. Write the next line using the current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may include functions, classes, or code. Output only the next line. | _resource_name = 'deploy_templates' |
Given 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.
class DeployTemplate(base.Resource):
def __repr__(self):
return "<DeployTemplate %s>" % self._info
class DeployTemplateManager(base.CreateManager):
resource_class = DeployTemplate
_creation_attributes = ['extra', 'name', 'steps', 'uuid']
_resource_name = 'deploy_templates'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
which might include code, classes, or functions. Output only the next line. | def list(self, limit=None, marker=None, sort_key=None, sort_dir=None, |
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 DeployTemplate(base.Resource):
def __repr__(self):
return "<DeployTemplate %s>" % self._info
class DeployTemplateManager(base.CreateManager):
<|code_end|>
. Use current file imports:
(from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | resource_class = DeployTemplate |
Given the code snippet: <|code_start|> router.connect(name='index_converter', route='/math/unit-converter',
controller=a, action="index")
router.connect(name='distance_converter', route='/math/unit-converter/distance/',
controller=a, action="distance")
router.connect(name='pressure_converter', route='/math/unit-converter/pressure/',
controller=a, action="pressure")
router.connect(name='force_converter', route='/math/unit-converter/force/',
controller=a, action="force")
#ABOUT
a = about.About()
router.connect(name='about', route='/about',
controller=a, action="index")
router.connect(name='license', route='/about/license',
controller=a, action="license")
router.connect(name='technology', route='/about/technology',
controller=a, action="technology")
router.connect(name='home', route='/',
controller=a, action="home")
router.connect(name='options', route='/options',
controller=a, action="options")
router.connect(name='reset_options', route='/options/reset',
controller=a, action="reset_options")
router.connect(name='set_options', route='/options/save',
controller=a, action="set_options")
#Connect router handler as src
router_config = {
"/" : {
"request.dispatch" : router
<|code_end|>
, generate the next line using the imports in this file:
import cherrypy
from controller.structure import steel_profile
from controller.structure import earthquake
from controller.structure import concrete
from controller.geotechnic import surcharge_load
from controller.math import converter
from controller.about import about
and context (functions, classes, or occasionally code) from other files:
# Path: controller/structure/steel_profile.py
# class Steel_Profile:
# def index(self):
# def iwf(self):
# def angle(self):
#
# Path: controller/structure/earthquake.py
# class Earthquake:
# def index(self):
# def response_spectrum(self, **var):
#
# Path: controller/structure/concrete.py
# class Concrete:
# def index(self):
# def flexural_analysis(self, **var):
# def slab_two_ways_design(self, **var):
#
# Path: controller/geotechnic/surcharge_load.py
# class Surcharge_Load:
# def __init__(self):
# def point(self, **var):
# def strip(self, **var):
# H = float(param.get('H') or 12)
# H = float(param.get('H') or 5)
#
# Path: controller/math/converter.py
# class Converter:
# def __init__(self):
# def index(self):
# def distance(self, val, from_, to):
# def pressure(self, val, from_, to):
# def force(self, val, from_, to):
#
# Path: controller/about/about.py
# class About:
# def index(self):
# def license(self):
# def technology(self):
# def home(self):
# def options(self):
# def set_options(self, **kwargs):
# def reset_options(self):
. Output only the next line. | }
|
Using the snippet: <|code_start|> a = steel_profile.Steel_Profile()
router.connect(name='structure_steel_profile', route='/structure/steel/profile',
controller=a, action="index")
router.connect(name='structure_steel_profile', route='/structure/steel/profile/iwf',
controller=a, action="iwf")
router.connect(name='structure_steel_profile', route='/structure/steel/profile/angle',
controller=a, action="angle")
a = earthquake.Earthquake()
router.connect(name='earthquake_response_spectrum', route='/structure/earthquake/response-spectrum',
controller=a, action="response_spectrum")
a = concrete.Concrete()
router.connect(name='flexural_analysis', route='/structure/concrete/flexural-analysis',
controller=a, action="flexural_analysis")
router.connect(name='slab_two_ways_design', route='/structure/concrete/slab-two-ways',
controller=a, action="slab_two_ways_design")
#GEOTECHNIC
a = surcharge_load.Surcharge_Load()
router.connect(name='surcharge_point', route='/geotechnic/surcharge/point-load',
controller=a, action="point")
router.connect(name='surcharge_strip', route='/geotechnic/surcharge/strip-load',
controller=a, action="strip")
#MATH
a = converter.Converter()
router.connect(name='index_converter', route='/math/unit-converter',
controller=a, action="index")
router.connect(name='distance_converter', route='/math/unit-converter/distance/',
controller=a, action="distance")
router.connect(name='pressure_converter', route='/math/unit-converter/pressure/',
controller=a, action="pressure")
router.connect(name='force_converter', route='/math/unit-converter/force/',
<|code_end|>
, determine the next line of code. You have imports:
import cherrypy
from controller.structure import steel_profile
from controller.structure import earthquake
from controller.structure import concrete
from controller.geotechnic import surcharge_load
from controller.math import converter
from controller.about import about
and context (class names, function names, or code) available:
# Path: controller/structure/steel_profile.py
# class Steel_Profile:
# def index(self):
# def iwf(self):
# def angle(self):
#
# Path: controller/structure/earthquake.py
# class Earthquake:
# def index(self):
# def response_spectrum(self, **var):
#
# Path: controller/structure/concrete.py
# class Concrete:
# def index(self):
# def flexural_analysis(self, **var):
# def slab_two_ways_design(self, **var):
#
# Path: controller/geotechnic/surcharge_load.py
# class Surcharge_Load:
# def __init__(self):
# def point(self, **var):
# def strip(self, **var):
# H = float(param.get('H') or 12)
# H = float(param.get('H') or 5)
#
# Path: controller/math/converter.py
# class Converter:
# def __init__(self):
# def index(self):
# def distance(self, val, from_, to):
# def pressure(self, val, from_, to):
# def force(self, val, from_, to):
#
# Path: controller/about/about.py
# class About:
# def index(self):
# def license(self):
# def technology(self):
# def home(self):
# def options(self):
# def set_options(self, **kwargs):
# def reset_options(self):
. Output only the next line. | controller=a, action="force")
|
Given the code snippet: <|code_start|>
def setup():
#Router handler
router = cherrypy.dispatch.RoutesDispatcher()
#STRUCTURE
a = steel_profile.Steel_Profile()
router.connect(name='structure_steel_profile', route='/structure/steel/profile',
controller=a, action="index")
router.connect(name='structure_steel_profile', route='/structure/steel/profile/iwf',
controller=a, action="iwf")
router.connect(name='structure_steel_profile', route='/structure/steel/profile/angle',
controller=a, action="angle")
a = earthquake.Earthquake()
router.connect(name='earthquake_response_spectrum', route='/structure/earthquake/response-spectrum',
controller=a, action="response_spectrum")
a = concrete.Concrete()
router.connect(name='flexural_analysis', route='/structure/concrete/flexural-analysis',
controller=a, action="flexural_analysis")
<|code_end|>
, generate the next line using the imports in this file:
import cherrypy
from controller.structure import steel_profile
from controller.structure import earthquake
from controller.structure import concrete
from controller.geotechnic import surcharge_load
from controller.math import converter
from controller.about import about
and context (functions, classes, or occasionally code) from other files:
# Path: controller/structure/steel_profile.py
# class Steel_Profile:
# def index(self):
# def iwf(self):
# def angle(self):
#
# Path: controller/structure/earthquake.py
# class Earthquake:
# def index(self):
# def response_spectrum(self, **var):
#
# Path: controller/structure/concrete.py
# class Concrete:
# def index(self):
# def flexural_analysis(self, **var):
# def slab_two_ways_design(self, **var):
#
# Path: controller/geotechnic/surcharge_load.py
# class Surcharge_Load:
# def __init__(self):
# def point(self, **var):
# def strip(self, **var):
# H = float(param.get('H') or 12)
# H = float(param.get('H') or 5)
#
# Path: controller/math/converter.py
# class Converter:
# def __init__(self):
# def index(self):
# def distance(self, val, from_, to):
# def pressure(self, val, from_, to):
# def force(self, val, from_, to):
#
# Path: controller/about/about.py
# class About:
# def index(self):
# def license(self):
# def technology(self):
# def home(self):
# def options(self):
# def set_options(self, **kwargs):
# def reset_options(self):
. Output only the next line. | router.connect(name='slab_two_ways_design', route='/structure/concrete/slab-two-ways',
|
Based on the snippet: <|code_start|>
def setup():
#Router handler
router = cherrypy.dispatch.RoutesDispatcher()
#STRUCTURE
a = steel_profile.Steel_Profile()
router.connect(name='structure_steel_profile', route='/structure/steel/profile',
controller=a, action="index")
router.connect(name='structure_steel_profile', route='/structure/steel/profile/iwf',
controller=a, action="iwf")
router.connect(name='structure_steel_profile', route='/structure/steel/profile/angle',
controller=a, action="angle")
a = earthquake.Earthquake()
router.connect(name='earthquake_response_spectrum', route='/structure/earthquake/response-spectrum',
controller=a, action="response_spectrum")
a = concrete.Concrete()
router.connect(name='flexural_analysis', route='/structure/concrete/flexural-analysis',
controller=a, action="flexural_analysis")
router.connect(name='slab_two_ways_design', route='/structure/concrete/slab-two-ways',
controller=a, action="slab_two_ways_design")
#GEOTECHNIC
a = surcharge_load.Surcharge_Load()
<|code_end|>
, predict the immediate next line with the help of imports:
import cherrypy
from controller.structure import steel_profile
from controller.structure import earthquake
from controller.structure import concrete
from controller.geotechnic import surcharge_load
from controller.math import converter
from controller.about import about
and context (classes, functions, sometimes code) from other files:
# Path: controller/structure/steel_profile.py
# class Steel_Profile:
# def index(self):
# def iwf(self):
# def angle(self):
#
# Path: controller/structure/earthquake.py
# class Earthquake:
# def index(self):
# def response_spectrum(self, **var):
#
# Path: controller/structure/concrete.py
# class Concrete:
# def index(self):
# def flexural_analysis(self, **var):
# def slab_two_ways_design(self, **var):
#
# Path: controller/geotechnic/surcharge_load.py
# class Surcharge_Load:
# def __init__(self):
# def point(self, **var):
# def strip(self, **var):
# H = float(param.get('H') or 12)
# H = float(param.get('H') or 5)
#
# Path: controller/math/converter.py
# class Converter:
# def __init__(self):
# def index(self):
# def distance(self, val, from_, to):
# def pressure(self, val, from_, to):
# def force(self, val, from_, to):
#
# Path: controller/about/about.py
# class About:
# def index(self):
# def license(self):
# def technology(self):
# def home(self):
# def options(self):
# def set_options(self, **kwargs):
# def reset_options(self):
. Output only the next line. | router.connect(name='surcharge_point', route='/geotechnic/surcharge/point-load',
|
Using the snippet: <|code_start|> router.connect(name='structure_steel_profile', route='/structure/steel/profile/angle',
controller=a, action="angle")
a = earthquake.Earthquake()
router.connect(name='earthquake_response_spectrum', route='/structure/earthquake/response-spectrum',
controller=a, action="response_spectrum")
a = concrete.Concrete()
router.connect(name='flexural_analysis', route='/structure/concrete/flexural-analysis',
controller=a, action="flexural_analysis")
router.connect(name='slab_two_ways_design', route='/structure/concrete/slab-two-ways',
controller=a, action="slab_two_ways_design")
#GEOTECHNIC
a = surcharge_load.Surcharge_Load()
router.connect(name='surcharge_point', route='/geotechnic/surcharge/point-load',
controller=a, action="point")
router.connect(name='surcharge_strip', route='/geotechnic/surcharge/strip-load',
controller=a, action="strip")
#MATH
a = converter.Converter()
router.connect(name='index_converter', route='/math/unit-converter',
controller=a, action="index")
router.connect(name='distance_converter', route='/math/unit-converter/distance/',
controller=a, action="distance")
router.connect(name='pressure_converter', route='/math/unit-converter/pressure/',
controller=a, action="pressure")
router.connect(name='force_converter', route='/math/unit-converter/force/',
controller=a, action="force")
#ABOUT
a = about.About()
router.connect(name='about', route='/about',
controller=a, action="index")
<|code_end|>
, determine the next line of code. You have imports:
import cherrypy
from controller.structure import steel_profile
from controller.structure import earthquake
from controller.structure import concrete
from controller.geotechnic import surcharge_load
from controller.math import converter
from controller.about import about
and context (class names, function names, or code) available:
# Path: controller/structure/steel_profile.py
# class Steel_Profile:
# def index(self):
# def iwf(self):
# def angle(self):
#
# Path: controller/structure/earthquake.py
# class Earthquake:
# def index(self):
# def response_spectrum(self, **var):
#
# Path: controller/structure/concrete.py
# class Concrete:
# def index(self):
# def flexural_analysis(self, **var):
# def slab_two_ways_design(self, **var):
#
# Path: controller/geotechnic/surcharge_load.py
# class Surcharge_Load:
# def __init__(self):
# def point(self, **var):
# def strip(self, **var):
# H = float(param.get('H') or 12)
# H = float(param.get('H') or 5)
#
# Path: controller/math/converter.py
# class Converter:
# def __init__(self):
# def index(self):
# def distance(self, val, from_, to):
# def pressure(self, val, from_, to):
# def force(self, val, from_, to):
#
# Path: controller/about/about.py
# class About:
# def index(self):
# def license(self):
# def technology(self):
# def home(self):
# def options(self):
# def set_options(self, **kwargs):
# def reset_options(self):
. Output only the next line. | router.connect(name='license', route='/about/license',
|
Based on the snippet: <|code_start|> return template.render(**data)
def strip(self, **var):
# Prepare view & model object
template = view.lookup.get_template('geotechnic/surcharge_strip.mako')
model = surcharge_load.Surcharge_Load()
# Prepare url params & cookie as default value
param = cherrypy.request.params
cookie = cherrypy.request.cookie
# Get url parameter or set default variable (if None)
q = float(param.get('q') or 200)
x_load = float(param.get('x_load') or 1.2)
width = float(param.get('width') or 1)
H = float(param.get('H') or 5)
start = float(param.get('start') or -10)
end = float(param.get('end') or 10)
type = float(param.get('type') or 2)
# Calculate
x, y, z = model.strip(q, x_load, width, H, start, end, type)
plt = plot.Plot()
img = plt.pcolor(x, y, z)
data = {
'q': q,
'x_load': x_load, #m
'width': width, #m
'H': H, #m
<|code_end|>
, predict the immediate next line with the help of imports:
from src import view
from model.geotechnic import surcharge_load
from model.utils import plot
import cherrypy
and context (classes, functions, sometimes code) from other files:
# Path: src/view.py
#
# Path: model/geotechnic/surcharge_load.py
# class Surcharge_Load:
# def __init__(self):
# def point(self, q, x_load, H, start, end, type):
# def strip(self, q, x_load, width, H, start, end, type):
# A = 1.77
# B = pow(m,2)
# C = B
# A = 0.28
# B = 0.16
# C = 1
# X,Y = np.meshgrid(x,y)
# Z = []
# Z = np.array(Z).reshape((len(y), len(x))).transpose()
# X,Y = np.meshgrid(x,y)
# Z = []
# Z = np.array(Z).reshape((len(y), len(x))).transpose()
#
# Path: model/utils/plot.py
# class Plot:
# def __init__(self):
# def pcolor(self, x, y, z):
# def line(self, x, y, xlabel="X", ylabel="Y", title="X vs Y"):
# def encode_base64(self, img):
. Output only the next line. | 'start': start, #m
|
Predict the next line for this snippet: <|code_start|> # Calculate
x, y, z = model.point(q, x_load, H, start, end, type)
plt = plot.Plot()
img = plt.pcolor(x, y, z)
# Prepare data to view
data = {
'q': q,
'x_load': x_load, #m
'H': H, #m
'start': start, #m
'end': end, # m
'type': type,
'plot_image': img,
}
return template.render(**data)
def strip(self, **var):
# Prepare view & model object
template = view.lookup.get_template('geotechnic/surcharge_strip.mako')
model = surcharge_load.Surcharge_Load()
# Prepare url params & cookie as default value
param = cherrypy.request.params
cookie = cherrypy.request.cookie
# Get url parameter or set default variable (if None)
q = float(param.get('q') or 200)
x_load = float(param.get('x_load') or 1.2)
width = float(param.get('width') or 1)
<|code_end|>
with the help of current file imports:
from src import view
from model.geotechnic import surcharge_load
from model.utils import plot
import cherrypy
and context from other files:
# Path: src/view.py
#
# Path: model/geotechnic/surcharge_load.py
# class Surcharge_Load:
# def __init__(self):
# def point(self, q, x_load, H, start, end, type):
# def strip(self, q, x_load, width, H, start, end, type):
# A = 1.77
# B = pow(m,2)
# C = B
# A = 0.28
# B = 0.16
# C = 1
# X,Y = np.meshgrid(x,y)
# Z = []
# Z = np.array(Z).reshape((len(y), len(x))).transpose()
# X,Y = np.meshgrid(x,y)
# Z = []
# Z = np.array(Z).reshape((len(y), len(x))).transpose()
#
# Path: model/utils/plot.py
# class Plot:
# def __init__(self):
# def pcolor(self, x, y, z):
# def line(self, x, y, xlabel="X", ylabel="Y", title="X vs Y"):
# def encode_base64(self, img):
, which may contain function names, class names, or code. Output only the next line. | H = float(param.get('H') or 5)
|
Continue the code snippet: <|code_start|>
class Surcharge_Load:
def __init__(self):
pass
def point(self, **var):
# Prepare view & model object
template = view.lookup.get_template('geotechnic/surcharge_point.mako')
model = surcharge_load.Surcharge_Load()
# Prepare url params & cookie as default value
param = cherrypy.request.params
cookie = cherrypy.request.cookie
# Get url parameter or set default variable (if None)
q = float(param.get('q') or 200)
x_load = float(param.get('x_load') or 1.2)
H = float(param.get('H') or 12)
start = float(param.get('start') or -10)
end = float(param.get('end') or 10)
type = float(param.get('type') or 2)
# Calculate
x, y, z = model.point(q, x_load, H, start, end, type)
plt = plot.Plot()
img = plt.pcolor(x, y, z)
# Prepare data to view
data = {
<|code_end|>
. Use current file imports:
from src import view
from model.geotechnic import surcharge_load
from model.utils import plot
import cherrypy
and context (classes, functions, or code) from other files:
# Path: src/view.py
#
# Path: model/geotechnic/surcharge_load.py
# class Surcharge_Load:
# def __init__(self):
# def point(self, q, x_load, H, start, end, type):
# def strip(self, q, x_load, width, H, start, end, type):
# A = 1.77
# B = pow(m,2)
# C = B
# A = 0.28
# B = 0.16
# C = 1
# X,Y = np.meshgrid(x,y)
# Z = []
# Z = np.array(Z).reshape((len(y), len(x))).transpose()
# X,Y = np.meshgrid(x,y)
# Z = []
# Z = np.array(Z).reshape((len(y), len(x))).transpose()
#
# Path: model/utils/plot.py
# class Plot:
# def __init__(self):
# def pcolor(self, x, y, z):
# def line(self, x, y, xlabel="X", ylabel="Y", title="X vs Y"):
# def encode_base64(self, img):
. Output only the next line. | 'q': q,
|
Given the following code snippet before the placeholder: <|code_start|>
class Steel_Profile:
def index(self):
return self.iwf()
def iwf(self):
template = view.lookup.get_template('structure/steel_iwf_profile.mako')
model = steel_profile.Steel_Profile()
data = model.iwf_table()
<|code_end|>
, predict the next line using imports from the current file:
from src import view
from model.structure import steel_profile
and context including class names, function names, and sometimes code from other files:
# Path: src/view.py
#
# Path: model/structure/steel_profile.py
# class Steel_Profile:
# def __init__(self):
# def iwf_table(self):
# def coordinate_iwf(self, H, B, tw, tf):
# def angle_table(self):
# A = (2*b*tf + tw*h1 + (2*r)**2 - math.pi*r**2 )/100 #cm2
# A = float('{0:.2f}'.format(A))
# P = [(0,0), (B,0), (B,tf), (B/2.+tw,tf), (B/2.+tw,H-tf),
# (B,H-tf), (B,H), (0,H), (0,H-tf), (B/2.-tw, H-tf),
# (B/2.-tw, tf), (0,tf)]
# A1 = h*t - r2**2*(1-math.pi/4) #mm2
# A2 = (b1*t - r2**2*(1-math.pi/4)) #mm2
# A3 = r1**2 * (1-math.pi/4) #mm2
# A = (A1+A2+A3)/100 #cm2
# A = float('{0:.2f}'.format(A))
. Output only the next line. | return template.render(**data)
|
Based on the snippet: <|code_start|> def index(self):
pass
def response_spectrum(self, **var):
# Prepare view & model object
template = view.lookup.get_template('structure/earthquake_response_spectrum.mako')
model = earthquake.Earthquake()
# Prepare url params & cookie as default value
param = cherrypy.request.params
cookie = cherrypy.request.cookie
# Get url parameter or set default variable (if None)
ss = float(param.get('ss') or 1.3)
s1 = float(param.get('s1') or 0.6)
site_class = param.get('site_class') or "SD"
design_coefficient = float(param.get('design_coefficient') or 0.667)
# Calculate & get the plot image
x, y = model.response_spectrum(ss, s1, site_class, design_coefficient)
plt = plot.Plot()
img = plt.line(x, y, "Natural Period, T, (second)",
"Spectral Acceleration (Sa)",
"Response Spectrum Design")
# Prepare data to view
data = {
'ss': ss,
's1': s1, #m
'site_class': site_class, #m
<|code_end|>
, predict the immediate next line with the help of imports:
from src import view
from model.structure import earthquake
from model.utils import plot
import cherrypy
and context (classes, functions, sometimes code) from other files:
# Path: src/view.py
#
# Path: model/structure/earthquake.py
# class Earthquake:
# def __init__(self):
# def response_spectrum(self, ss, s1, soil_class, design_coefficient):
#
# Path: model/utils/plot.py
# class Plot:
# def __init__(self):
# def pcolor(self, x, y, z):
# def line(self, x, y, xlabel="X", ylabel="Y", title="X vs Y"):
# def encode_base64(self, img):
. Output only the next line. | 'design_coefficient': design_coefficient,
|
Predict the next line after this snippet: <|code_start|>class Earthquake:
def index(self):
pass
def response_spectrum(self, **var):
# Prepare view & model object
template = view.lookup.get_template('structure/earthquake_response_spectrum.mako')
model = earthquake.Earthquake()
# Prepare url params & cookie as default value
param = cherrypy.request.params
cookie = cherrypy.request.cookie
# Get url parameter or set default variable (if None)
ss = float(param.get('ss') or 1.3)
s1 = float(param.get('s1') or 0.6)
site_class = param.get('site_class') or "SD"
design_coefficient = float(param.get('design_coefficient') or 0.667)
# Calculate & get the plot image
x, y = model.response_spectrum(ss, s1, site_class, design_coefficient)
plt = plot.Plot()
img = plt.line(x, y, "Natural Period, T, (second)",
"Spectral Acceleration (Sa)",
"Response Spectrum Design")
# Prepare data to view
data = {
'ss': ss,
's1': s1, #m
<|code_end|>
using the current file's imports:
from src import view
from model.structure import earthquake
from model.utils import plot
import cherrypy
and any relevant context from other files:
# Path: src/view.py
#
# Path: model/structure/earthquake.py
# class Earthquake:
# def __init__(self):
# def response_spectrum(self, ss, s1, soil_class, design_coefficient):
#
# Path: model/utils/plot.py
# class Plot:
# def __init__(self):
# def pcolor(self, x, y, z):
# def line(self, x, y, xlabel="X", ylabel="Y", title="X vs Y"):
# def encode_base64(self, img):
. Output only the next line. | 'site_class': site_class, #m
|
Given snippet: <|code_start|>
class Converter:
def __init__(self):
self.model = converter.Converter()
def index(self):
template = view.lookup.get_template('math/unit_converter.mako')
model = converter.Converter()
distance = ""
pressure = ""
force = ""
for key, val in sorted(model.distance_unit.items()):
distance += "<option value='"+ key +"'>" + key + "</option>"
for key, val in sorted(model.pressure_unit.items()):
pressure += "<option value='"+ key +"'>" + key + "</option>"
for key, val in sorted(model.force_unit.items()):
force += "<option value='"+ key +"'>" + key + "</option>"
data = {
'distance': distance,
'pressure': pressure,
'force': force,
}
return template.render(**data)
def distance(self, val, from_, to):
data = self.model.distance(val, from_, to)
return data
def pressure(self, val, from_, to):
data = self.model.pressure(val, from_, to)
return data
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from src import view
from model.math import converter
and context:
# Path: src/view.py
#
# Path: model/math/converter.py
# class Converter:
# def __init__(self):
# def index(self):
# def convert(self, val, from_, to):
# def distance(self, val=1, from_='m', to='micron'):
# def force(self, val=1, from_='kgf', to='kgf'):
# def pressure(self, val=1, from_='pa', to='pa'):
which might include code, classes, or functions. Output only the next line. | def force(self, val, from_, to):
|
Based on the snippet: <|code_start|>
class Converter:
def __init__(self):
self.model = converter.Converter()
def index(self):
template = view.lookup.get_template('math/unit_converter.mako')
model = converter.Converter()
distance = ""
pressure = ""
force = ""
for key, val in sorted(model.distance_unit.items()):
distance += "<option value='"+ key +"'>" + key + "</option>"
for key, val in sorted(model.pressure_unit.items()):
pressure += "<option value='"+ key +"'>" + key + "</option>"
for key, val in sorted(model.force_unit.items()):
force += "<option value='"+ key +"'>" + key + "</option>"
data = {
'distance': distance,
<|code_end|>
, predict the immediate next line with the help of imports:
from src import view
from model.math import converter
and context (classes, functions, sometimes code) from other files:
# Path: src/view.py
#
# Path: model/math/converter.py
# class Converter:
# def __init__(self):
# def index(self):
# def convert(self, val, from_, to):
# def distance(self, val=1, from_='m', to='micron'):
# def force(self, val=1, from_='kgf', to='kgf'):
# def pressure(self, val=1, from_='pa', to='pa'):
. Output only the next line. | 'pressure': pressure,
|
Based on the snippet: <|code_start|> conc_unit_weight, fc, fus, slab_type, diameter, dy, dx)
# Prepare data to view
data = {
'ly': ly,
'lx': lx, #m
't': t,
'dl': dl,
'll': ll,
'include_self_weight': include_self_weight,
'kdl': kdl,
'kll': kll,
'conc_unit_weight': conc_unit_weight,
'fc': fc,
'fus': fus,
'slab_type': slab_type,
'diameter': diameter,
'dy': dy,
'dx': dx,
'Mlx': float('{0:.2f}'.format(Mlx)),
'Mly': float('{0:.2f}'.format(Mly)),
'Mtx': float('{0:.2f}'.format(Mtx)),
'Mty': float('{0:.2f}'.format(Mty)),
'slx': int(slx),
'sly': int(sly),
'stx': int(stx),
'sty': int(sty),
'error': error,
}
<|code_end|>
, predict the immediate next line with the help of imports:
from src import view
from model.material import concrete
from model.structure import concrete_slab
import cherrypy
and context (classes, functions, sometimes code) from other files:
# Path: src/view.py
#
# Path: model/material/concrete.py
# class Concrete:
# def __init__(self):
# def Gc(self, fc=None, Ec=None, concrete_poisson_ratio=0.2):
# def Mn(self, fyr, fc, height, width, n, diameter, cover):
# def As(self, n, diameter):
# def a(self, As, fyr, fc, width):
# def jd(self, d, a):
# def beta1(self, fc):
# def rho_balance(self, fc, fyr):
# def rho(self, n, diameter, width, height):
# def rho_max(self, fc, fyr):
# def As_max(self, fc, fyr, height, width):
# def As_min(self, fc, fyr, height, width, cover):
# def eps_s(self, d, As, fc, fyr, width, eps_cu=0.003):
# def neutral_axis_balance(self, eps_cu, eps_y, d):
# def neutral_axis_balance2(self, As, fyr, fc, width):
# def phi(self, eps_s):
# A = As*fyr # N
# B = 0.85*fc*width # N/mm
#
# Path: model/structure/concrete_slab.py
# class Slab:
# def __init__(self):
# def marcus_method(self, ly, lx, t, dl, ll,
# include_self_weight, kdl, kll,
# conc_unit_weight, fc, fus, slab_type,
# diameter, dy, dx):
# def error(self, Mlx, Mly, Mtx, Mty, error):
# X = float(ly/lx)
. Output only the next line. | return template.render(**data)
|
Predict the next line for this snippet: <|code_start|> model = concrete.Concrete()
# Prepare url params & cookie as default value
param = cherrypy.request.params
cookie = cherrypy.request.cookie
# Get url parameter or set default variable (if None)
fyr = float(param.get('fyr') or cookie['fyr'].value)
fc = float(param.get('fc') or cookie['fc'].value)
height = float(param.get('height') or 565)
width = float(param.get('width') or 250)
n = int(param.get('n') or 4)
diameter = float(param.get('diameter') or 13)
cover = float(param.get('cover') or 65)
# Calculate
mn = model.Mn(fyr, fc, height, width, n, diameter, cover)
rho = model.rho(n, diameter, width, height)
rho_max = model.rho_max(fc, fyr)
As = model.As(n, diameter)
As_max = model.As_max(fc, fyr, height, width)
As_min = model.As_min(fc, fyr, height, width, cover)
eps_s = model.eps_s(height-cover, As, fc, fyr, width)
phi = model.phi(eps_s)
# Prepare data to view
data = {
'fyr': fyr, #MPa
'fc': fc, #MPa
'width': width, #mm
<|code_end|>
with the help of current file imports:
from src import view
from model.material import concrete
from model.structure import concrete_slab
import cherrypy
and context from other files:
# Path: src/view.py
#
# Path: model/material/concrete.py
# class Concrete:
# def __init__(self):
# def Gc(self, fc=None, Ec=None, concrete_poisson_ratio=0.2):
# def Mn(self, fyr, fc, height, width, n, diameter, cover):
# def As(self, n, diameter):
# def a(self, As, fyr, fc, width):
# def jd(self, d, a):
# def beta1(self, fc):
# def rho_balance(self, fc, fyr):
# def rho(self, n, diameter, width, height):
# def rho_max(self, fc, fyr):
# def As_max(self, fc, fyr, height, width):
# def As_min(self, fc, fyr, height, width, cover):
# def eps_s(self, d, As, fc, fyr, width, eps_cu=0.003):
# def neutral_axis_balance(self, eps_cu, eps_y, d):
# def neutral_axis_balance2(self, As, fyr, fc, width):
# def phi(self, eps_s):
# A = As*fyr # N
# B = 0.85*fc*width # N/mm
#
# Path: model/structure/concrete_slab.py
# class Slab:
# def __init__(self):
# def marcus_method(self, ly, lx, t, dl, ll,
# include_self_weight, kdl, kll,
# conc_unit_weight, fc, fus, slab_type,
# diameter, dy, dx):
# def error(self, Mlx, Mly, Mtx, Mty, error):
# X = float(ly/lx)
, which may contain function names, class names, or code. Output only the next line. | 'height': height, #mm
|
Using the snippet: <|code_start|> model = concrete_slab.Slab()
# Prepare url params & cookie as default value
param = cherrypy.request.params
cookie = cherrypy.request.cookie
# Get url parameter or set default variable (if None)
ly = float(param.get('ly') or 4)
lx = float(param.get('lx') or 3)
t = float(param.get('t') or 0.12)
dl = float(param.get('dl') or 100)
ll = float(param.get('ll') or 250)
include_self_weight = param.get('include_self_weight') or 'Yes'
kdl = float(param.get('kdl') or 1.2)
kll = float(param.get('kll') or 1.6)
conc_unit_weight = float(param.get('conc_unit_weight') or cookie['conc_unit_weight'].value)
fc = float(param.get('fc') or cookie['fc'].value)
fus = float(param.get('fus') or cookie['fus'].value)
slab_type = param.get('slab_type') or '1'
diameter = float(param.get('diameter') or 10)
dy= float(param.get('dy') or 40)
dx= float(param.get('dx') or 50)
# Calculate
Mlx, Mly, Mtx, Mty, slx, sly, stx, sty, error = model.marcus_method(
ly, lx, t, dl, ll, include_self_weight, kdl, kll,
conc_unit_weight, fc, fus, slab_type, diameter, dy, dx)
# Prepare data to view
data = {
<|code_end|>
, determine the next line of code. You have imports:
from src import view
from model.material import concrete
from model.structure import concrete_slab
import cherrypy
and context (class names, function names, or code) available:
# Path: src/view.py
#
# Path: model/material/concrete.py
# class Concrete:
# def __init__(self):
# def Gc(self, fc=None, Ec=None, concrete_poisson_ratio=0.2):
# def Mn(self, fyr, fc, height, width, n, diameter, cover):
# def As(self, n, diameter):
# def a(self, As, fyr, fc, width):
# def jd(self, d, a):
# def beta1(self, fc):
# def rho_balance(self, fc, fyr):
# def rho(self, n, diameter, width, height):
# def rho_max(self, fc, fyr):
# def As_max(self, fc, fyr, height, width):
# def As_min(self, fc, fyr, height, width, cover):
# def eps_s(self, d, As, fc, fyr, width, eps_cu=0.003):
# def neutral_axis_balance(self, eps_cu, eps_y, d):
# def neutral_axis_balance2(self, As, fyr, fc, width):
# def phi(self, eps_s):
# A = As*fyr # N
# B = 0.85*fc*width # N/mm
#
# Path: model/structure/concrete_slab.py
# class Slab:
# def __init__(self):
# def marcus_method(self, ly, lx, t, dl, ll,
# include_self_weight, kdl, kll,
# conc_unit_weight, fc, fus, slab_type,
# diameter, dy, dx):
# def error(self, Mlx, Mly, Mtx, Mty, error):
# X = float(ly/lx)
. Output only the next line. | 'ly': ly,
|
Continue the code snippet: <|code_start|>
class About:
def index(self):
template = view.lookup.get_template('about/about.mako')
return template.render()
def license(self):
template = view.lookup.get_template('about/license.mako')
return template.render()
def technology(self):
template = view.lookup.get_template('about/technology.mako')
return template.render()
def home(self):
startup.check_options_value()
template = view.lookup.get_template('about/home.mako')
return template.render()
def options(self):
current = options.Options()
data = current.get_options()
template = view.lookup.get_template('about/options.mako')
return template.render(**data)
def set_options(self, **kwargs):
current = options.Options()
<|code_end|>
. Use current file imports:
from src import view
from model.options import options
from src import startup
import cherrypy
and context (classes, functions, or code) from other files:
# Path: src/view.py
#
# Path: model/options/options.py
# class Options:
# def __init__(self):
# def set_options(self, kwargs):
# def get_options(self):
# def get_cookie(self, key):
# def reset_options(self):
#
# Path: src/startup.py
# def check_options_value():
. Output only the next line. | current.set_options(kwargs)
|
Predict the next line for this snippet: <|code_start|>
urlpatterns = [
path("", bookmarks.user_bookmarks, name="cab_user_bookmarks"),
path("add/<int:snippet_id>/", bookmarks.add_bookmark, name="cab_bookmark_add"),
path("delete/<int:snippet_id>/", bookmarks.delete_bookmark, name="cab_bookmark_delete"),
<|code_end|>
with the help of current file imports:
from django.urls import path
from ..views import bookmarks
and context from other files:
# Path: cab/views/bookmarks.py
# def user_bookmarks(request):
# def add_bookmark(request, snippet_id):
# def delete_bookmark(request, snippet_id):
, which may contain function names, class names, or code. Output only the next line. | ] |
Given the code snippet: <|code_start|>
urlpatterns = [
path("languages/", popular.top_languages, name="cab_top_languages"),
path("bookmarked/", popular.top_bookmarked, name="cab_top_bookmarked"),
path("rated/", popular.top_rated, name="cab_top_rated"),
<|code_end|>
, generate the next line using the imports in this file:
from django.urls import path
from ..views import popular
and context (functions, classes, or occasionally code) from other files:
# Path: cab/views/popular.py
# def top_authors(request):
# def top_languages(request):
# def top_tags(request):
# def top_bookmarked(request):
# def top_rated(request):
. Output only the next line. | ] |
Here is a snippet: <|code_start|>
def update_rating_score(sender, instance, *args, **kwargs):
if instance.content_object and hasattr(instance.content_object, "update_rating"):
instance.content_object.update_rating()
def start_listening():
signals.post_save.connect(
<|code_end|>
. Write the next line using the current file imports:
from django.db.models import signals
from ratings.models import RatedItem
and context from other files:
# Path: ratings/models.py
# class RatedItem(RatedItemBase):
# object_id = models.IntegerField()
# content_type = models.ForeignKey(
# ContentType,
# related_name="rated_items",
# on_delete=models.CASCADE,
# )
# content_object = GenericForeignKey()
#
# @classmethod
# def lookup_kwargs(cls, instance):
# return {"object_id": instance.pk, "content_type": ContentType.objects.get_for_model(instance)}
#
# @classmethod
# def base_kwargs(cls, model_class):
# return {"content_type": ContentType.objects.get_for_model(model_class)}
, which may include functions, classes, or code. Output only the next line. | update_rating_score, |
Given snippet: <|code_start|>
class Food(models.Model):
name = models.CharField(max_length=50)
ratings = Ratings()
def __str__(self):
return self.name
class BeverageRating(RatedItemBase):
content_object = models.ForeignKey("Beverage", on_delete=models.CASCADE)
class Beverage(models.Model):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.db import models
from ..models import RatedItemBase, Ratings
and context:
# Path: ratings/models.py
# class RatedItemBase(models.Model):
# score = models.FloatField(default=0, db_index=True)
# user = models.ForeignKey(User, related_name="%(class)ss", on_delete=models.CASCADE)
# hashed = models.CharField(max_length=40, editable=False, db_index=True)
#
# class Meta:
# abstract = True
#
# def __str__(self):
# return "%s rated %s by %s" % (self.content_object, self.score, self.user)
#
# def save(self, *args, **kwargs):
# self.hashed = self.generate_hash()
# super(RatedItemBase, self).save(*args, **kwargs)
#
# def generate_hash(self):
# content_field = self._meta.get_field("content_object")
# related_object = getattr(self, content_field.name)
# uniq = "%s.%s" % (related_object._meta, related_object.pk)
# return hashlib.sha1(uniq.encode("ascii")).hexdigest()
#
# @classmethod
# def lookup_kwargs(cls, instance):
# return {"content_object": instance}
#
# @classmethod
# def base_kwargs(cls, model_class):
# return {}
#
# class Ratings:
# def __init__(self, rating_model=None):
# self.rating_model = rating_model or RatedItem
#
# def contribute_to_class(self, cls, name):
# # set up the ForeignRelatedObjectsDescriptor right hyah
# setattr(cls, name, _RatingsDescriptor(cls, self.rating_model, name))
# setattr(cls, "_ratings_field", name)
which might include code, classes, or functions. Output only the next line. | name = models.CharField(max_length=50) |
Predict the next line after this snippet: <|code_start|>
class Food(models.Model):
name = models.CharField(max_length=50)
ratings = Ratings()
def __str__(self):
return self.name
class BeverageRating(RatedItemBase):
content_object = models.ForeignKey("Beverage", on_delete=models.CASCADE)
class Beverage(models.Model):
<|code_end|>
using the current file's imports:
from django.db import models
from ..models import RatedItemBase, Ratings
and any relevant context from other files:
# Path: ratings/models.py
# class RatedItemBase(models.Model):
# score = models.FloatField(default=0, db_index=True)
# user = models.ForeignKey(User, related_name="%(class)ss", on_delete=models.CASCADE)
# hashed = models.CharField(max_length=40, editable=False, db_index=True)
#
# class Meta:
# abstract = True
#
# def __str__(self):
# return "%s rated %s by %s" % (self.content_object, self.score, self.user)
#
# def save(self, *args, **kwargs):
# self.hashed = self.generate_hash()
# super(RatedItemBase, self).save(*args, **kwargs)
#
# def generate_hash(self):
# content_field = self._meta.get_field("content_object")
# related_object = getattr(self, content_field.name)
# uniq = "%s.%s" % (related_object._meta, related_object.pk)
# return hashlib.sha1(uniq.encode("ascii")).hexdigest()
#
# @classmethod
# def lookup_kwargs(cls, instance):
# return {"content_object": instance}
#
# @classmethod
# def base_kwargs(cls, model_class):
# return {}
#
# class Ratings:
# def __init__(self, rating_model=None):
# self.rating_model = rating_model or RatedItem
#
# def contribute_to_class(self, cls, name):
# # set up the ForeignRelatedObjectsDescriptor right hyah
# setattr(cls, name, _RatingsDescriptor(cls, self.rating_model, name))
# setattr(cls, "_ratings_field", name)
. Output only the next line. | name = models.CharField(max_length=50) |
Given snippet: <|code_start|>
urlpatterns = [
path("", snippets.snippet_list, name="cab_snippet_list"),
path("<int:snippet_id>/", snippets.snippet_detail, name="cab_snippet_detail"),
path("<int:snippet_id>/rate/", snippets.rate_snippet, name="cab_snippet_rate"),
path("<int:snippet_id>/download/", snippets.download_snippet, name="cab_snippet_download"),
path("<int:snippet_id>/raw/", snippets.raw_snippet, name="cab_snippet_raw"),
path("<int:snippet_id>/edit/", snippets.edit_snippet, name="cab_snippet_edit"),
path("<int:snippet_id>/flag/", snippets.flag_snippet, name="cab_snippet_flag"),
path("add/", snippets.edit_snippet, name="cab_snippet_add"),
path("tag-hint/", snippets.tag_hint, name="cab_snippet_tag_hint"),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.urls import path
from ..views import snippets
and context:
# Path: cab/views/snippets.py
# def snippet_list(request, queryset=None, **kwargs):
# def snippet_detail(request, snippet_id):
# def download_snippet(request, snippet_id):
# def raw_snippet(request, snippet_id):
# def rate_snippet(request, snippet_id):
# def edit_snippet(request, snippet_id=None, template_name="cab/edit_snippet.html"):
# def flag_snippet(request, snippet_id, template_name="cab/flag_snippet.html"):
# def author_snippets(request, username):
# def matches_tag(request, slug):
# def search(request):
# def autocomplete(request):
# def tag_hint(request):
# def basic_search(request):
# def advanced_search(request):
which might include code, classes, or functions. Output only the next line. | ] |
Given the following code snippet before the placeholder: <|code_start|> raw_id_fields = ("author",)
actions = ["mark_as_inappropiate", "mark_as_spam"]
def mark_as_inappropiate(self, request, queryset):
for obj in queryset:
obj.mark_as_inappropiate()
self.message_user(request, "Snippets marked as inappropiate successfully")
mark_as_inappropiate.short_description = "Mark snippets as inappropiate"
def mark_as_spam(self, request, queryset):
for obj in queryset:
obj.mark_as_spam()
self.message_user(request, "Snippets marked as spam successfully")
mark_as_spam.short_description = "Mark snippets as spam"
class SnippetFlagAdmin(admin.ModelAdmin):
list_display = ("snippet", "flag")
list_filter = ("flag",)
actions = ["remove_and_ban"]
raw_id_fields = (
"snippet",
"user",
)
def remove_and_ban(self, request, queryset):
for obj in queryset:
obj.remove_and_ban()
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from .models import Language, Snippet, SnippetFlag
and context including class names, function names, and sometimes code from other files:
# Path: cab/models.py
# class Language(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(unique=True)
# language_code = models.CharField(max_length=50)
# mime_type = models.CharField(max_length=100)
# file_extension = models.CharField(max_length=10)
#
# objects = LanguageManager()
#
# class Meta:
# ordering = ("name",)
#
# def __str__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse("cab_language_detail", kwargs={"slug": self.slug})
#
# def get_lexer(self):
# return lexers.get_lexer_by_name(self.language_code)
#
# class Snippet(models.Model):
# title = models.CharField(max_length=255)
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# author = models.ForeignKey(User, on_delete=models.CASCADE)
# description = models.TextField()
# description_html = models.TextField(editable=False)
# code = models.TextField()
# highlighted_code = models.TextField(editable=False)
# version = models.CharField(max_length=5, choices=VERSIONS, default="0.0")
# pub_date = models.DateTimeField(auto_now_add=True)
# updated_date = models.DateTimeField(auto_now=True)
# bookmark_count = models.IntegerField(default=0) # denormalized count
# rating_score = models.IntegerField(default=0) # denormalized score
#
# ratings = Ratings()
# tags = TaggableManager(blank=True)
#
# objects = SnippetManager()
#
# class Meta:
# ordering = ("-pub_date",)
#
# def __str__(self):
# return self.title
#
# def save(self, *args, **kwargs):
# self.description_html = sanitize_markdown(self.description)
# self.highlighted_code = self.highlight()
# super(Snippet, self).save(*args, **kwargs)
#
# def get_absolute_url(self):
# return reverse("cab_snippet_detail", kwargs={"snippet_id": self.id})
#
# def highlight(self):
# return highlight(self.code, self.language.get_lexer(), formatters.HtmlFormatter(linenos=True))
#
# def get_tagstring(self):
# return ", ".join([t.name for t in self.tags.order_by("name").all()])
#
# def get_version(self):
# return dict(VERSIONS)[self.version]
#
# def update_rating(self):
# self.rating_score = self.ratings.cumulative_score() or 0
# self.save()
#
# def update_bookmark_count(self):
# self.bookmark_count = self.bookmarks.count() or 0
# self.save()
#
# def mark_as_inappropiate(self):
# snippet_flag = SnippetFlag(snippet=self, user=self.author, flag=SnippetFlag.FLAG_INAPPROPRIATE)
# snippet_flag.save()
#
# def mark_as_spam(self):
# snippet_flag = SnippetFlag(snippet=self, user=self.author, flag=SnippetFlag.FLAG_SPAM)
# snippet_flag.save()
#
# class SnippetFlag(models.Model):
# FLAG_SPAM = 1
# FLAG_INAPPROPRIATE = 2
# FLAG_CHOICES = (
# (FLAG_SPAM, "Spam"),
# (FLAG_INAPPROPRIATE, "Inappropriate"),
# )
# snippet = models.ForeignKey(Snippet, related_name="flags", on_delete=models.CASCADE)
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# flag = models.IntegerField(choices=FLAG_CHOICES)
#
# def __str__(self):
# return "%s flagged as %s by %s" % (
# self.snippet.title,
# self.get_flag_display(),
# self.user.username,
# )
#
# def remove_and_ban(self):
# user = self.snippet.author
# user.set_unusable_password()
# user.is_active = False
# user.save()
# self.snippet.delete()
. Output only the next line. | self.message_user(request, "Snippets removed successfully") |
Based on the snippet: <|code_start|>
class LanguageAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ["name"]}
class SnippetAdmin(admin.ModelAdmin):
list_display = ("id", "title", "author", "rating_score", "pub_date")
list_filter = ("language",)
date_hierarchy = "pub_date"
search_fields = (
"author__username",
"title",
"description",
"code",
)
raw_id_fields = ("author",)
actions = ["mark_as_inappropiate", "mark_as_spam"]
def mark_as_inappropiate(self, request, queryset):
for obj in queryset:
obj.mark_as_inappropiate()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib import admin
from .models import Language, Snippet, SnippetFlag
and context (classes, functions, sometimes code) from other files:
# Path: cab/models.py
# class Language(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(unique=True)
# language_code = models.CharField(max_length=50)
# mime_type = models.CharField(max_length=100)
# file_extension = models.CharField(max_length=10)
#
# objects = LanguageManager()
#
# class Meta:
# ordering = ("name",)
#
# def __str__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse("cab_language_detail", kwargs={"slug": self.slug})
#
# def get_lexer(self):
# return lexers.get_lexer_by_name(self.language_code)
#
# class Snippet(models.Model):
# title = models.CharField(max_length=255)
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# author = models.ForeignKey(User, on_delete=models.CASCADE)
# description = models.TextField()
# description_html = models.TextField(editable=False)
# code = models.TextField()
# highlighted_code = models.TextField(editable=False)
# version = models.CharField(max_length=5, choices=VERSIONS, default="0.0")
# pub_date = models.DateTimeField(auto_now_add=True)
# updated_date = models.DateTimeField(auto_now=True)
# bookmark_count = models.IntegerField(default=0) # denormalized count
# rating_score = models.IntegerField(default=0) # denormalized score
#
# ratings = Ratings()
# tags = TaggableManager(blank=True)
#
# objects = SnippetManager()
#
# class Meta:
# ordering = ("-pub_date",)
#
# def __str__(self):
# return self.title
#
# def save(self, *args, **kwargs):
# self.description_html = sanitize_markdown(self.description)
# self.highlighted_code = self.highlight()
# super(Snippet, self).save(*args, **kwargs)
#
# def get_absolute_url(self):
# return reverse("cab_snippet_detail", kwargs={"snippet_id": self.id})
#
# def highlight(self):
# return highlight(self.code, self.language.get_lexer(), formatters.HtmlFormatter(linenos=True))
#
# def get_tagstring(self):
# return ", ".join([t.name for t in self.tags.order_by("name").all()])
#
# def get_version(self):
# return dict(VERSIONS)[self.version]
#
# def update_rating(self):
# self.rating_score = self.ratings.cumulative_score() or 0
# self.save()
#
# def update_bookmark_count(self):
# self.bookmark_count = self.bookmarks.count() or 0
# self.save()
#
# def mark_as_inappropiate(self):
# snippet_flag = SnippetFlag(snippet=self, user=self.author, flag=SnippetFlag.FLAG_INAPPROPRIATE)
# snippet_flag.save()
#
# def mark_as_spam(self):
# snippet_flag = SnippetFlag(snippet=self, user=self.author, flag=SnippetFlag.FLAG_SPAM)
# snippet_flag.save()
#
# class SnippetFlag(models.Model):
# FLAG_SPAM = 1
# FLAG_INAPPROPRIATE = 2
# FLAG_CHOICES = (
# (FLAG_SPAM, "Spam"),
# (FLAG_INAPPROPRIATE, "Inappropriate"),
# )
# snippet = models.ForeignKey(Snippet, related_name="flags", on_delete=models.CASCADE)
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# flag = models.IntegerField(choices=FLAG_CHOICES)
#
# def __str__(self):
# return "%s flagged as %s by %s" % (
# self.snippet.title,
# self.get_flag_display(),
# self.user.username,
# )
#
# def remove_and_ban(self):
# user = self.snippet.author
# user.set_unusable_password()
# user.is_active = False
# user.save()
# self.snippet.delete()
. Output only the next line. | self.message_user(request, "Snippets marked as inappropiate successfully") |
Predict the next line after this snippet: <|code_start|>
class LanguageAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ["name"]}
class SnippetAdmin(admin.ModelAdmin):
list_display = ("id", "title", "author", "rating_score", "pub_date")
list_filter = ("language",)
date_hierarchy = "pub_date"
search_fields = (
"author__username",
"title",
"description",
"code",
)
raw_id_fields = ("author",)
actions = ["mark_as_inappropiate", "mark_as_spam"]
def mark_as_inappropiate(self, request, queryset):
for obj in queryset:
obj.mark_as_inappropiate()
self.message_user(request, "Snippets marked as inappropiate successfully")
mark_as_inappropiate.short_description = "Mark snippets as inappropiate"
def mark_as_spam(self, request, queryset):
for obj in queryset:
obj.mark_as_spam()
<|code_end|>
using the current file's imports:
from django.contrib import admin
from .models import Language, Snippet, SnippetFlag
and any relevant context from other files:
# Path: cab/models.py
# class Language(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(unique=True)
# language_code = models.CharField(max_length=50)
# mime_type = models.CharField(max_length=100)
# file_extension = models.CharField(max_length=10)
#
# objects = LanguageManager()
#
# class Meta:
# ordering = ("name",)
#
# def __str__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse("cab_language_detail", kwargs={"slug": self.slug})
#
# def get_lexer(self):
# return lexers.get_lexer_by_name(self.language_code)
#
# class Snippet(models.Model):
# title = models.CharField(max_length=255)
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# author = models.ForeignKey(User, on_delete=models.CASCADE)
# description = models.TextField()
# description_html = models.TextField(editable=False)
# code = models.TextField()
# highlighted_code = models.TextField(editable=False)
# version = models.CharField(max_length=5, choices=VERSIONS, default="0.0")
# pub_date = models.DateTimeField(auto_now_add=True)
# updated_date = models.DateTimeField(auto_now=True)
# bookmark_count = models.IntegerField(default=0) # denormalized count
# rating_score = models.IntegerField(default=0) # denormalized score
#
# ratings = Ratings()
# tags = TaggableManager(blank=True)
#
# objects = SnippetManager()
#
# class Meta:
# ordering = ("-pub_date",)
#
# def __str__(self):
# return self.title
#
# def save(self, *args, **kwargs):
# self.description_html = sanitize_markdown(self.description)
# self.highlighted_code = self.highlight()
# super(Snippet, self).save(*args, **kwargs)
#
# def get_absolute_url(self):
# return reverse("cab_snippet_detail", kwargs={"snippet_id": self.id})
#
# def highlight(self):
# return highlight(self.code, self.language.get_lexer(), formatters.HtmlFormatter(linenos=True))
#
# def get_tagstring(self):
# return ", ".join([t.name for t in self.tags.order_by("name").all()])
#
# def get_version(self):
# return dict(VERSIONS)[self.version]
#
# def update_rating(self):
# self.rating_score = self.ratings.cumulative_score() or 0
# self.save()
#
# def update_bookmark_count(self):
# self.bookmark_count = self.bookmarks.count() or 0
# self.save()
#
# def mark_as_inappropiate(self):
# snippet_flag = SnippetFlag(snippet=self, user=self.author, flag=SnippetFlag.FLAG_INAPPROPRIATE)
# snippet_flag.save()
#
# def mark_as_spam(self):
# snippet_flag = SnippetFlag(snippet=self, user=self.author, flag=SnippetFlag.FLAG_SPAM)
# snippet_flag.save()
#
# class SnippetFlag(models.Model):
# FLAG_SPAM = 1
# FLAG_INAPPROPRIATE = 2
# FLAG_CHOICES = (
# (FLAG_SPAM, "Spam"),
# (FLAG_INAPPROPRIATE, "Inappropriate"),
# )
# snippet = models.ForeignKey(Snippet, related_name="flags", on_delete=models.CASCADE)
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# flag = models.IntegerField(choices=FLAG_CHOICES)
#
# def __str__(self):
# return "%s flagged as %s by %s" % (
# self.snippet.title,
# self.get_flag_display(),
# self.user.username,
# )
#
# def remove_and_ban(self):
# user = self.snippet.author
# user.set_unusable_password()
# user.is_active = False
# user.save()
# self.snippet.delete()
. Output only the next line. | self.message_user(request, "Snippets marked as spam successfully") |
Based on the snippet: <|code_start|>
urlpatterns = [
path("", popular.top_authors, name="cab_top_authors"),
path("<username>/", snippets.author_snippets, name="cab_author_snippets"),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.urls import path
from ..views import popular, snippets
and context (classes, functions, sometimes code) from other files:
# Path: cab/views/popular.py
# def top_authors(request):
# def top_languages(request):
# def top_tags(request):
# def top_bookmarked(request):
# def top_rated(request):
#
# Path: cab/views/snippets.py
# def snippet_list(request, queryset=None, **kwargs):
# def snippet_detail(request, snippet_id):
# def download_snippet(request, snippet_id):
# def raw_snippet(request, snippet_id):
# def rate_snippet(request, snippet_id):
# def edit_snippet(request, snippet_id=None, template_name="cab/edit_snippet.html"):
# def flag_snippet(request, snippet_id, template_name="cab/flag_snippet.html"):
# def author_snippets(request, username):
# def matches_tag(request, slug):
# def search(request):
# def autocomplete(request):
# def tag_hint(request):
# def basic_search(request):
# def advanced_search(request):
. Output only the next line. | ] |
Here is a snippet: <|code_start|>
urlpatterns = [
path("", popular.top_authors, name="cab_top_authors"),
path("<username>/", snippets.author_snippets, name="cab_author_snippets"),
<|code_end|>
. Write the next line using the current file imports:
from django.urls import path
from ..views import popular, snippets
and context from other files:
# Path: cab/views/popular.py
# def top_authors(request):
# def top_languages(request):
# def top_tags(request):
# def top_bookmarked(request):
# def top_rated(request):
#
# Path: cab/views/snippets.py
# def snippet_list(request, queryset=None, **kwargs):
# def snippet_detail(request, snippet_id):
# def download_snippet(request, snippet_id):
# def raw_snippet(request, snippet_id):
# def rate_snippet(request, snippet_id):
# def edit_snippet(request, snippet_id=None, template_name="cab/edit_snippet.html"):
# def flag_snippet(request, snippet_id, template_name="cab/flag_snippet.html"):
# def author_snippets(request, username):
# def matches_tag(request, slug):
# def search(request):
# def autocomplete(request):
# def tag_hint(request):
# def basic_search(request):
# def advanced_search(request):
, which may include functions, classes, or code. Output only the next line. | ] |
Predict the next line for this snippet: <|code_start|>
urlpatterns = [
path("", languages.language_list, name="cab_language_list"),
path("<slug:slug>/", languages.language_detail, name="cab_language_detail"),
<|code_end|>
with the help of current file imports:
from django.urls import path
from ..views import languages
and context from other files:
# Path: cab/views/languages.py
# def language_list(request):
# def language_detail(request, slug):
, which may contain function names, class names, or code. Output only the next line. | ] |
Based on the snippet: <|code_start|>
def language_list(request):
return object_list(
request,
queryset=Language.objects.all(),
paginate_by=20,
)
def language_detail(request, slug):
language = get_object_or_404(Language, slug=slug)
return month_object_list(
request,
queryset=language.snippet_set.all(),
paginate_by=20,
template_name="cab/language_detail.html",
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import get_object_or_404
from ..models import Language
from ..utils import month_object_list, object_list
and context (classes, functions, sometimes code) from other files:
# Path: cab/models.py
# class Language(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(unique=True)
# language_code = models.CharField(max_length=50)
# mime_type = models.CharField(max_length=100)
# file_extension = models.CharField(max_length=10)
#
# objects = LanguageManager()
#
# class Meta:
# ordering = ("name",)
#
# def __str__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse("cab_language_detail", kwargs={"slug": self.slug})
#
# def get_lexer(self):
# return lexers.get_lexer_by_name(self.language_code)
#
# Path: cab/utils.py
# def month_object_list(request, queryset, *args, **kwargs):
# extra_context = kwargs.pop("extra_context", {})
#
# if "months" in request.GET and request.GET["months"].isdigit():
# months = int(request.GET["months"])
# queryset = queryset.filter(pub_date__gt=get_past_datetime(months))
# extra_context["months"] = months
#
# kwargs["extra_context"] = extra_context
#
# return object_list(request, queryset, *args, **kwargs)
#
# def object_list(
# request,
# queryset,
# paginate_by=None,
# page=None,
# allow_empty=True,
# template_name=None,
# template_loader=loader,
# extra_context=None,
# template_object_name="object",
# content_type=None,
# ):
# """
# Generic list of objects.
#
# Templates: ``<app_label>/<model_name>_list.html``
# Context:
# object_list
# list of objects
# is_paginated
# are the results paginated?
# results_per_page
# number of objects per page (if paginated)
# has_next
# is there a next page?
# has_previous
# is there a prev page?
# page
# the current page
# next
# the next page
# previous
# the previous page
# pages
# number of pages, total
# hits
# number of objects, total
# last_on_page
# the result number of the last of object in the
# object_list (1-indexed)
# first_on_page
# the result number of the first object in the
# object_list (1-indexed)
# page_range:
# A list of the page numbers (1-indexed).
# """
# if extra_context is None:
# extra_context = {}
# queryset = queryset._clone()
# if paginate_by:
# paginator = Paginator(queryset, paginate_by, allow_empty_first_page=allow_empty)
# if not page:
# page = request.GET.get("page", 1)
#
# if page == "last":
# page_number = paginator.num_pages
# else:
# try:
# page_number = int(page)
# except ValueError:
# # Page is not 'last', nor can it be converted to an int.
# raise Http404
# try:
# page_obj = paginator.page(page_number)
# except InvalidPage:
# raise Http404
# try:
# next_page = page_obj.next_page_number()
# except InvalidPage:
# next_page = None
# try:
# previous_page = page_obj.previous_page_number()
# except InvalidPage:
# previous_page = None
#
# c = {
# "%s_list" % template_object_name: page_obj.object_list,
# "paginator": paginator,
# "page_obj": page_obj,
# "is_paginated": page_obj.has_other_pages(),
# # Legacy template context stuff. New templates should use page_obj
# # to access this instead.
# "results_per_page": paginator.per_page,
# "has_next": page_obj.has_next(),
# "has_previous": page_obj.has_previous(),
# "page": page_obj.number,
# "next": next_page,
# "previous": previous_page,
# "first_on_page": page_obj.start_index(),
# "last_on_page": page_obj.end_index(),
# "pages": paginator.num_pages,
# "hits": paginator.count,
# "page_range": paginator.page_range,
# }
# else:
# c = {
# "%s_list" % template_object_name: queryset,
# "paginator": None,
# "page_obj": None,
# "is_paginated": False,
# }
# if not allow_empty and len(queryset) == 0:
# raise Http404
#
# for key, value in extra_context.items():
# if callable(value):
# c[key] = value()
# else:
# c[key] = value
# if not template_name:
# model = queryset.model
# template_name = "%s/%s_list.html" % (model._meta.app_label, model._meta.object_name.lower())
# t = template_loader.get_template(template_name)
# return HttpResponse(t.render(c, request=request), content_type=content_type)
. Output only the next line. | extra_context={"language": language}, |
Here is a snippet: <|code_start|>
def language_list(request):
return object_list(
request,
queryset=Language.objects.all(),
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import get_object_or_404
from ..models import Language
from ..utils import month_object_list, object_list
and context from other files:
# Path: cab/models.py
# class Language(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(unique=True)
# language_code = models.CharField(max_length=50)
# mime_type = models.CharField(max_length=100)
# file_extension = models.CharField(max_length=10)
#
# objects = LanguageManager()
#
# class Meta:
# ordering = ("name",)
#
# def __str__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse("cab_language_detail", kwargs={"slug": self.slug})
#
# def get_lexer(self):
# return lexers.get_lexer_by_name(self.language_code)
#
# Path: cab/utils.py
# def month_object_list(request, queryset, *args, **kwargs):
# extra_context = kwargs.pop("extra_context", {})
#
# if "months" in request.GET and request.GET["months"].isdigit():
# months = int(request.GET["months"])
# queryset = queryset.filter(pub_date__gt=get_past_datetime(months))
# extra_context["months"] = months
#
# kwargs["extra_context"] = extra_context
#
# return object_list(request, queryset, *args, **kwargs)
#
# def object_list(
# request,
# queryset,
# paginate_by=None,
# page=None,
# allow_empty=True,
# template_name=None,
# template_loader=loader,
# extra_context=None,
# template_object_name="object",
# content_type=None,
# ):
# """
# Generic list of objects.
#
# Templates: ``<app_label>/<model_name>_list.html``
# Context:
# object_list
# list of objects
# is_paginated
# are the results paginated?
# results_per_page
# number of objects per page (if paginated)
# has_next
# is there a next page?
# has_previous
# is there a prev page?
# page
# the current page
# next
# the next page
# previous
# the previous page
# pages
# number of pages, total
# hits
# number of objects, total
# last_on_page
# the result number of the last of object in the
# object_list (1-indexed)
# first_on_page
# the result number of the first object in the
# object_list (1-indexed)
# page_range:
# A list of the page numbers (1-indexed).
# """
# if extra_context is None:
# extra_context = {}
# queryset = queryset._clone()
# if paginate_by:
# paginator = Paginator(queryset, paginate_by, allow_empty_first_page=allow_empty)
# if not page:
# page = request.GET.get("page", 1)
#
# if page == "last":
# page_number = paginator.num_pages
# else:
# try:
# page_number = int(page)
# except ValueError:
# # Page is not 'last', nor can it be converted to an int.
# raise Http404
# try:
# page_obj = paginator.page(page_number)
# except InvalidPage:
# raise Http404
# try:
# next_page = page_obj.next_page_number()
# except InvalidPage:
# next_page = None
# try:
# previous_page = page_obj.previous_page_number()
# except InvalidPage:
# previous_page = None
#
# c = {
# "%s_list" % template_object_name: page_obj.object_list,
# "paginator": paginator,
# "page_obj": page_obj,
# "is_paginated": page_obj.has_other_pages(),
# # Legacy template context stuff. New templates should use page_obj
# # to access this instead.
# "results_per_page": paginator.per_page,
# "has_next": page_obj.has_next(),
# "has_previous": page_obj.has_previous(),
# "page": page_obj.number,
# "next": next_page,
# "previous": previous_page,
# "first_on_page": page_obj.start_index(),
# "last_on_page": page_obj.end_index(),
# "pages": paginator.num_pages,
# "hits": paginator.count,
# "page_range": paginator.page_range,
# }
# else:
# c = {
# "%s_list" % template_object_name: queryset,
# "paginator": None,
# "page_obj": None,
# "is_paginated": False,
# }
# if not allow_empty and len(queryset) == 0:
# raise Http404
#
# for key, value in extra_context.items():
# if callable(value):
# c[key] = value()
# else:
# c[key] = value
# if not template_name:
# model = queryset.model
# template_name = "%s/%s_list.html" % (model._meta.app_label, model._meta.object_name.lower())
# t = template_loader.get_template(template_name)
# return HttpResponse(t.render(c, request=request), content_type=content_type)
, which may include functions, classes, or code. Output only the next line. | paginate_by=20, |
Here is a snippet: <|code_start|>
def language_list(request):
return object_list(
request,
queryset=Language.objects.all(),
paginate_by=20,
)
def language_detail(request, slug):
language = get_object_or_404(Language, slug=slug)
return month_object_list(
request,
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import get_object_or_404
from ..models import Language
from ..utils import month_object_list, object_list
and context from other files:
# Path: cab/models.py
# class Language(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(unique=True)
# language_code = models.CharField(max_length=50)
# mime_type = models.CharField(max_length=100)
# file_extension = models.CharField(max_length=10)
#
# objects = LanguageManager()
#
# class Meta:
# ordering = ("name",)
#
# def __str__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse("cab_language_detail", kwargs={"slug": self.slug})
#
# def get_lexer(self):
# return lexers.get_lexer_by_name(self.language_code)
#
# Path: cab/utils.py
# def month_object_list(request, queryset, *args, **kwargs):
# extra_context = kwargs.pop("extra_context", {})
#
# if "months" in request.GET and request.GET["months"].isdigit():
# months = int(request.GET["months"])
# queryset = queryset.filter(pub_date__gt=get_past_datetime(months))
# extra_context["months"] = months
#
# kwargs["extra_context"] = extra_context
#
# return object_list(request, queryset, *args, **kwargs)
#
# def object_list(
# request,
# queryset,
# paginate_by=None,
# page=None,
# allow_empty=True,
# template_name=None,
# template_loader=loader,
# extra_context=None,
# template_object_name="object",
# content_type=None,
# ):
# """
# Generic list of objects.
#
# Templates: ``<app_label>/<model_name>_list.html``
# Context:
# object_list
# list of objects
# is_paginated
# are the results paginated?
# results_per_page
# number of objects per page (if paginated)
# has_next
# is there a next page?
# has_previous
# is there a prev page?
# page
# the current page
# next
# the next page
# previous
# the previous page
# pages
# number of pages, total
# hits
# number of objects, total
# last_on_page
# the result number of the last of object in the
# object_list (1-indexed)
# first_on_page
# the result number of the first object in the
# object_list (1-indexed)
# page_range:
# A list of the page numbers (1-indexed).
# """
# if extra_context is None:
# extra_context = {}
# queryset = queryset._clone()
# if paginate_by:
# paginator = Paginator(queryset, paginate_by, allow_empty_first_page=allow_empty)
# if not page:
# page = request.GET.get("page", 1)
#
# if page == "last":
# page_number = paginator.num_pages
# else:
# try:
# page_number = int(page)
# except ValueError:
# # Page is not 'last', nor can it be converted to an int.
# raise Http404
# try:
# page_obj = paginator.page(page_number)
# except InvalidPage:
# raise Http404
# try:
# next_page = page_obj.next_page_number()
# except InvalidPage:
# next_page = None
# try:
# previous_page = page_obj.previous_page_number()
# except InvalidPage:
# previous_page = None
#
# c = {
# "%s_list" % template_object_name: page_obj.object_list,
# "paginator": paginator,
# "page_obj": page_obj,
# "is_paginated": page_obj.has_other_pages(),
# # Legacy template context stuff. New templates should use page_obj
# # to access this instead.
# "results_per_page": paginator.per_page,
# "has_next": page_obj.has_next(),
# "has_previous": page_obj.has_previous(),
# "page": page_obj.number,
# "next": next_page,
# "previous": previous_page,
# "first_on_page": page_obj.start_index(),
# "last_on_page": page_obj.end_index(),
# "pages": paginator.num_pages,
# "hits": paginator.count,
# "page_range": paginator.page_range,
# }
# else:
# c = {
# "%s_list" % template_object_name: queryset,
# "paginator": None,
# "page_obj": None,
# "is_paginated": False,
# }
# if not allow_empty and len(queryset) == 0:
# raise Http404
#
# for key, value in extra_context.items():
# if callable(value):
# c[key] = value()
# else:
# c[key] = value
# if not template_name:
# model = queryset.model
# template_name = "%s/%s_list.html" % (model._meta.app_label, model._meta.object_name.lower())
# t = template_loader.get_template(template_name)
# return HttpResponse(t.render(c, request=request), content_type=content_type)
, which may include functions, classes, or code. Output only the next line. | queryset=language.snippet_set.all(), |
Using the snippet: <|code_start|>
urlpatterns = [
path("", basic_search, name="cab_search"),
path("autocomplete/", autocomplete, name="snippet_autocomplete"),
path("advanced/", advanced_search, name="cab_search_advanced"),
<|code_end|>
, determine the next line of code. You have imports:
from django.urls import path
from ..views.snippets import advanced_search, autocomplete, basic_search
and context (class names, function names, or code) available:
# Path: cab/views/snippets.py
# def advanced_search(request):
#
# snippet_qs = Snippet.objects.annotate(
# search=SearchVector(
# "title",
# "description",
# "language__name",
# "version",
# "pub_date",
# "bookmark_count",
# "rating_score",
# "author__username",
# )
# )
# form = AdvancedSearchForm(request.GET)
# if form.is_valid():
# snippet_qs = form.search(snippet_qs)
#
# return snippet_list(
# request,
# queryset=snippet_qs,
# template_name="search/advanced_search.html",
# extra_context={"form": form},
# )
#
# def autocomplete(request):
#
# q = request.GET.get("q", "")
# results = []
# if len(q) > 2:
# result_set = Snippet.objects.annotate(search=SearchVector("title")).filter(search=q)[:10]
# for obj in result_set:
# url = obj.get_absolute_url()
# results.append({"title": obj.title, "author": obj.author.username, "url": url})
# return HttpResponse(json.dumps(results), content_type="application/json")
#
# def basic_search(request):
# q = request.GET.get("q")
# snippet_qs = Snippet.objects.annotate(search=SearchVector("title", "description", "author__username"))
# form = AdvancedSearchForm(request.GET)
#
# if form.is_valid():
# snippet_qs = form.search(snippet_qs)
#
# return snippet_list(
# request,
# queryset=snippet_qs,
# template_name="search/search.html",
# extra_context={"query": q, "form": form},
# )
. Output only the next line. | ] |
Predict the next line after this snippet: <|code_start|>
urlpatterns = [
path("", basic_search, name="cab_search"),
path("autocomplete/", autocomplete, name="snippet_autocomplete"),
path("advanced/", advanced_search, name="cab_search_advanced"),
<|code_end|>
using the current file's imports:
from django.urls import path
from ..views.snippets import advanced_search, autocomplete, basic_search
and any relevant context from other files:
# Path: cab/views/snippets.py
# def advanced_search(request):
#
# snippet_qs = Snippet.objects.annotate(
# search=SearchVector(
# "title",
# "description",
# "language__name",
# "version",
# "pub_date",
# "bookmark_count",
# "rating_score",
# "author__username",
# )
# )
# form = AdvancedSearchForm(request.GET)
# if form.is_valid():
# snippet_qs = form.search(snippet_qs)
#
# return snippet_list(
# request,
# queryset=snippet_qs,
# template_name="search/advanced_search.html",
# extra_context={"form": form},
# )
#
# def autocomplete(request):
#
# q = request.GET.get("q", "")
# results = []
# if len(q) > 2:
# result_set = Snippet.objects.annotate(search=SearchVector("title")).filter(search=q)[:10]
# for obj in result_set:
# url = obj.get_absolute_url()
# results.append({"title": obj.title, "author": obj.author.username, "url": url})
# return HttpResponse(json.dumps(results), content_type="application/json")
#
# def basic_search(request):
# q = request.GET.get("q")
# snippet_qs = Snippet.objects.annotate(search=SearchVector("title", "description", "author__username"))
# form = AdvancedSearchForm(request.GET)
#
# if form.is_valid():
# snippet_qs = form.search(snippet_qs)
#
# return snippet_list(
# request,
# queryset=snippet_qs,
# template_name="search/search.html",
# extra_context={"query": q, "form": form},
# )
. Output only the next line. | ] |
Using the snippet: <|code_start|>
urlpatterns = [
path("", basic_search, name="cab_search"),
path("autocomplete/", autocomplete, name="snippet_autocomplete"),
path("advanced/", advanced_search, name="cab_search_advanced"),
<|code_end|>
, determine the next line of code. You have imports:
from django.urls import path
from ..views.snippets import advanced_search, autocomplete, basic_search
and context (class names, function names, or code) available:
# Path: cab/views/snippets.py
# def advanced_search(request):
#
# snippet_qs = Snippet.objects.annotate(
# search=SearchVector(
# "title",
# "description",
# "language__name",
# "version",
# "pub_date",
# "bookmark_count",
# "rating_score",
# "author__username",
# )
# )
# form = AdvancedSearchForm(request.GET)
# if form.is_valid():
# snippet_qs = form.search(snippet_qs)
#
# return snippet_list(
# request,
# queryset=snippet_qs,
# template_name="search/advanced_search.html",
# extra_context={"form": form},
# )
#
# def autocomplete(request):
#
# q = request.GET.get("q", "")
# results = []
# if len(q) > 2:
# result_set = Snippet.objects.annotate(search=SearchVector("title")).filter(search=q)[:10]
# for obj in result_set:
# url = obj.get_absolute_url()
# results.append({"title": obj.title, "author": obj.author.username, "url": url})
# return HttpResponse(json.dumps(results), content_type="application/json")
#
# def basic_search(request):
# q = request.GET.get("q")
# snippet_qs = Snippet.objects.annotate(search=SearchVector("title", "description", "author__username"))
# form = AdvancedSearchForm(request.GET)
#
# if form.is_valid():
# snippet_qs = form.search(snippet_qs)
#
# return snippet_list(
# request,
# queryset=snippet_qs,
# template_name="search/search.html",
# extra_context={"query": q, "form": form},
# )
. Output only the next line. | ] |
Given the following code snippet before the placeholder: <|code_start|>
class RatedItemBase(models.Model):
score = models.FloatField(default=0, db_index=True)
user = models.ForeignKey(User, related_name="%(class)ss", on_delete=models.CASCADE)
hashed = models.CharField(max_length=40, editable=False, db_index=True)
class Meta:
abstract = True
def __str__(self):
return "%s rated %s by %s" % (self.content_object, self.score, self.user)
def save(self, *args, **kwargs):
self.hashed = self.generate_hash()
super(RatedItemBase, self).save(*args, **kwargs)
<|code_end|>
, predict the next line using imports from the current file:
import hashlib
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.query import QuerySet
from generic_aggregation import generic_annotate
from .utils import is_gfk, recommended_items
from ratings.utils import calculate_similar_items
and context including class names, function names, and sometimes code from other files:
# Path: ratings/utils.py
# def is_gfk(content_field):
# return isinstance(content_field, GenericForeignKey)
#
# def recommended_items(ratings_queryset, user):
# from ratings.models import SimilarItem
#
# scores = {}
# total_sim = {}
#
# for item in ratings_queryset.filter(user=user):
# similar_items = SimilarItem.objects.get_for_item(item.content_object)
# for similar_item in similar_items:
#
# actual = similar_item.similar_object
# lookup_kwargs = ratings_queryset.model.lookup_kwargs(actual)
# lookup_kwargs["user"] = user
#
# if ratings_queryset.filter(**lookup_kwargs):
# continue
#
# scores.setdefault(actual, 0)
# scores[actual] += similar_item.score * item.score
#
# total_sim.setdefault(actual, 0)
# total_sim[actual] += similar_item.score
#
# rankings = [(score / total_sim[item], item) for item, score in scores.items()]
#
# rankings.sort()
# rankings.reverse()
# return rankings
. Output only the next line. | def generate_hash(self): |
Predict the next line after this snippet: <|code_start|> def save(self, *args, **kwargs):
self.hashed = self.generate_hash()
super(RatedItemBase, self).save(*args, **kwargs)
def generate_hash(self):
content_field = self._meta.get_field("content_object")
related_object = getattr(self, content_field.name)
uniq = "%s.%s" % (related_object._meta, related_object.pk)
return hashlib.sha1(uniq.encode("ascii")).hexdigest()
@classmethod
def lookup_kwargs(cls, instance):
return {"content_object": instance}
@classmethod
def base_kwargs(cls, model_class):
return {}
class RatedItem(RatedItemBase):
object_id = models.IntegerField()
content_type = models.ForeignKey(
ContentType,
related_name="rated_items",
on_delete=models.CASCADE,
)
content_object = GenericForeignKey()
@classmethod
def lookup_kwargs(cls, instance):
<|code_end|>
using the current file's imports:
import hashlib
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.query import QuerySet
from generic_aggregation import generic_annotate
from .utils import is_gfk, recommended_items
from ratings.utils import calculate_similar_items
and any relevant context from other files:
# Path: ratings/utils.py
# def is_gfk(content_field):
# return isinstance(content_field, GenericForeignKey)
#
# def recommended_items(ratings_queryset, user):
# from ratings.models import SimilarItem
#
# scores = {}
# total_sim = {}
#
# for item in ratings_queryset.filter(user=user):
# similar_items = SimilarItem.objects.get_for_item(item.content_object)
# for similar_item in similar_items:
#
# actual = similar_item.similar_object
# lookup_kwargs = ratings_queryset.model.lookup_kwargs(actual)
# lookup_kwargs["user"] = user
#
# if ratings_queryset.filter(**lookup_kwargs):
# continue
#
# scores.setdefault(actual, 0)
# scores[actual] += similar_item.score * item.score
#
# total_sim.setdefault(actual, 0)
# total_sim[actual] += similar_item.score
#
# rankings = [(score / total_sim[item], item) for item, score in scores.items()]
#
# rankings.sort()
# rankings.reverse()
# return rankings
. Output only the next line. | return {"object_id": instance.pk, "content_type": ContentType.objects.get_for_model(instance)} |
Predict the next line for this snippet: <|code_start|>
class FullCycleCase(FullCycleBaseCase, WandTestCase):
def runner(self):
with Image(filename=root('resources', self.filename)) as im:
if self.level > 0:
im.rotate(degree=90.0)
if self.level > 1:
size = (int(im.width * 0.4 + 0.5),
int(im.height * 0.4 + 0.5))
im.resize(size[0], size[1], 'catrom')
if self.level > 2:
self.blur(im, 2.5 * 4, 4)
im.compression_quality = 85
<|code_end|>
with the help of current file imports:
from io import BytesIO
from .base import rpartial, root, FullCycleBaseCase
from .wand import WandTestCase, Image
and context from other files:
# Path: testsuite/cases/base.py
# def rpartial(func, *args, **keywords):
# """
# right partial — same as functools.partial, but pass function args first
# """
# def newfunc(*fargs, **fkeywords):
# newkeywords = keywords.copy()
# newkeywords.update(fkeywords)
# return func(*(fargs + args), **newkeywords)
# newfunc.func = func
# newfunc.args = args
# newfunc.keywords = keywords
# return newfunc
#
# def root(*chunks):
# return os.path.abspath(os.path.join(
# os.path.dirname(__file__), '..', *chunks))
#
# class FullCycleBaseCase(BaseTestCase):
# def handle_args(self, level, name, filename, filetype):
# self.level = level
# self.name = name
# self.filename = filename
# self.filetype = filetype
#
# def create_test_data(self):
# return ()
#
# def readable_args(self):
# return [self.name]
#
# Path: testsuite/cases/wand.py
# class WandTestCase(BaseTestCase):
# def __init__(self, *args, **kwargs):
# def create_test_data(self):
# def __del__(self):
# def blur(self, radius, sigma):
# def hald_lut(self, hald_image):
, which may contain function names, class names, or code. Output only the next line. | im.format = self.filetype |
Based on the snippet: <|code_start|>
class FullCycleCase(FullCycleBaseCase, WandTestCase):
def runner(self):
with Image(filename=root('resources', self.filename)) as im:
if self.level > 0:
im.rotate(degree=90.0)
if self.level > 1:
size = (int(im.width * 0.4 + 0.5),
int(im.height * 0.4 + 0.5))
im.resize(size[0], size[1], 'catrom')
if self.level > 2:
self.blur(im, 2.5 * 4, 4)
im.compression_quality = 85
<|code_end|>
, predict the immediate next line with the help of imports:
from io import BytesIO
from .base import rpartial, root, FullCycleBaseCase
from .wand import WandTestCase, Image
and context (classes, functions, sometimes code) from other files:
# Path: testsuite/cases/base.py
# def rpartial(func, *args, **keywords):
# """
# right partial — same as functools.partial, but pass function args first
# """
# def newfunc(*fargs, **fkeywords):
# newkeywords = keywords.copy()
# newkeywords.update(fkeywords)
# return func(*(fargs + args), **newkeywords)
# newfunc.func = func
# newfunc.args = args
# newfunc.keywords = keywords
# return newfunc
#
# def root(*chunks):
# return os.path.abspath(os.path.join(
# os.path.dirname(__file__), '..', *chunks))
#
# class FullCycleBaseCase(BaseTestCase):
# def handle_args(self, level, name, filename, filetype):
# self.level = level
# self.name = name
# self.filename = filename
# self.filetype = filetype
#
# def create_test_data(self):
# return ()
#
# def readable_args(self):
# return [self.name]
#
# Path: testsuite/cases/wand.py
# class WandTestCase(BaseTestCase):
# def __init__(self, *args, **kwargs):
# def create_test_data(self):
# def __del__(self):
# def blur(self, radius, sigma):
# def hald_lut(self, hald_image):
. Output only the next line. | im.format = self.filetype |
Predict the next line after this snippet: <|code_start|>
class FullCycleCase(FullCycleBaseCase, WandTestCase):
def runner(self):
with Image(filename=root('resources', self.filename)) as im:
if self.level > 0:
im.rotate(degree=90.0)
if self.level > 1:
size = (int(im.width * 0.4 + 0.5),
int(im.height * 0.4 + 0.5))
im.resize(size[0], size[1], 'catrom')
if self.level > 2:
self.blur(im, 2.5 * 4, 4)
<|code_end|>
using the current file's imports:
from io import BytesIO
from .base import rpartial, root, FullCycleBaseCase
from .wand import WandTestCase, Image
and any relevant context from other files:
# Path: testsuite/cases/base.py
# def rpartial(func, *args, **keywords):
# """
# right partial — same as functools.partial, but pass function args first
# """
# def newfunc(*fargs, **fkeywords):
# newkeywords = keywords.copy()
# newkeywords.update(fkeywords)
# return func(*(fargs + args), **newkeywords)
# newfunc.func = func
# newfunc.args = args
# newfunc.keywords = keywords
# return newfunc
#
# def root(*chunks):
# return os.path.abspath(os.path.join(
# os.path.dirname(__file__), '..', *chunks))
#
# class FullCycleBaseCase(BaseTestCase):
# def handle_args(self, level, name, filename, filetype):
# self.level = level
# self.name = name
# self.filename = filename
# self.filetype = filetype
#
# def create_test_data(self):
# return ()
#
# def readable_args(self):
# return [self.name]
#
# Path: testsuite/cases/wand.py
# class WandTestCase(BaseTestCase):
# def __init__(self, *args, **kwargs):
# def create_test_data(self):
# def __del__(self):
# def blur(self, radius, sigma):
# def hald_lut(self, hald_image):
. Output only the next line. | im.compression_quality = 85 |
Next line prediction: <|code_start|>
class FullCycleCase(FullCycleBaseCase, WandTestCase):
def runner(self):
with Image(filename=root('resources', self.filename)) as im:
if self.level > 0:
im.rotate(degree=90.0)
if self.level > 1:
size = (int(im.width * 0.4 + 0.5),
int(im.height * 0.4 + 0.5))
im.resize(size[0], size[1], 'catrom')
if self.level > 2:
self.blur(im, 2.5 * 4, 4)
im.compression_quality = 85
im.format = self.filetype
<|code_end|>
. Use current file imports:
(from io import BytesIO
from .base import rpartial, root, FullCycleBaseCase
from .wand import WandTestCase, Image)
and context including class names, function names, or small code snippets from other files:
# Path: testsuite/cases/base.py
# def rpartial(func, *args, **keywords):
# """
# right partial — same as functools.partial, but pass function args first
# """
# def newfunc(*fargs, **fkeywords):
# newkeywords = keywords.copy()
# newkeywords.update(fkeywords)
# return func(*(fargs + args), **newkeywords)
# newfunc.func = func
# newfunc.args = args
# newfunc.keywords = keywords
# return newfunc
#
# def root(*chunks):
# return os.path.abspath(os.path.join(
# os.path.dirname(__file__), '..', *chunks))
#
# class FullCycleBaseCase(BaseTestCase):
# def handle_args(self, level, name, filename, filetype):
# self.level = level
# self.name = name
# self.filename = filename
# self.filetype = filetype
#
# def create_test_data(self):
# return ()
#
# def readable_args(self):
# return [self.name]
#
# Path: testsuite/cases/wand.py
# class WandTestCase(BaseTestCase):
# def __init__(self, *args, **kwargs):
# def create_test_data(self):
# def __del__(self):
# def blur(self, radius, sigma):
# def hald_lut(self, hald_image):
. Output only the next line. | im.save(file=BytesIO()) |
Here is a snippet: <|code_start|>
class FullCycleCase(FullCycleBaseCase, WandTestCase):
def runner(self):
with Image(filename=root('resources', self.filename)) as im:
if self.level > 0:
im.rotate(degree=90.0)
if self.level > 1:
size = (int(im.width * 0.4 + 0.5),
int(im.height * 0.4 + 0.5))
im.resize(size[0], size[1], 'catrom')
if self.level > 2:
<|code_end|>
. Write the next line using the current file imports:
from io import BytesIO
from .base import rpartial, root, FullCycleBaseCase
from .wand import WandTestCase, Image
and context from other files:
# Path: testsuite/cases/base.py
# def rpartial(func, *args, **keywords):
# """
# right partial — same as functools.partial, but pass function args first
# """
# def newfunc(*fargs, **fkeywords):
# newkeywords = keywords.copy()
# newkeywords.update(fkeywords)
# return func(*(fargs + args), **newkeywords)
# newfunc.func = func
# newfunc.args = args
# newfunc.keywords = keywords
# return newfunc
#
# def root(*chunks):
# return os.path.abspath(os.path.join(
# os.path.dirname(__file__), '..', *chunks))
#
# class FullCycleBaseCase(BaseTestCase):
# def handle_args(self, level, name, filename, filetype):
# self.level = level
# self.name = name
# self.filename = filename
# self.filetype = filetype
#
# def create_test_data(self):
# return ()
#
# def readable_args(self):
# return [self.name]
#
# Path: testsuite/cases/wand.py
# class WandTestCase(BaseTestCase):
# def __init__(self, *args, **kwargs):
# def create_test_data(self):
# def __del__(self):
# def blur(self, radius, sigma):
# def hald_lut(self, hald_image):
, which may include functions, classes, or code. Output only the next line. | self.blur(im, 2.5 * 4, 4) |
Continue the code snippet: <|code_start|>
class ScaleCase(BaseScaleCase, PgmagickTestCase):
def runner(self, im):
im = Image(im)
im.filterType(self.filter)
im.zoom(Geometry(self.dest_size[0], self.dest_size[1]))
cases = [
rpartial(ScaleCase, size, flt, hpass=hpass, vpass=vpass)
for hpass, vpass in [
# (True, False),
# (False, True),
(True, True),
] for size in [
0.01,
0.125,
0.8,
2.14,
] for flt in [
# FilterTypes.BoxFilter,
FilterTypes.TriangleFilter,
# FilterTypes.HammingFilter,
FilterTypes.CatromFilter,
FilterTypes.LanczosFilter,
]
<|code_end|>
. Use current file imports:
from .base import rpartial, BaseScaleCase
from .pgmagick import Image, FilterTypes, Geometry, PgmagickTestCase
and context (classes, functions, or code) from other files:
# Path: testsuite/cases/base.py
# def rpartial(func, *args, **keywords):
# """
# right partial — same as functools.partial, but pass function args first
# """
# def newfunc(*fargs, **fkeywords):
# newkeywords = keywords.copy()
# newkeywords.update(fkeywords)
# return func(*(fargs + args), **newkeywords)
# newfunc.func = func
# newfunc.args = args
# newfunc.keywords = keywords
# return newfunc
#
# class BaseScaleCase:
# def handle_args(self, scale, filter, hpass=True, vpass=True):
# self.scale = scale
# self.filter = filter
# self.hpass = hpass
# self.vpass = vpass
# self.dest_size = (
# int(round(scale * self.size[0])) if hpass else self.size[0],
# int(round(scale * self.size[1])) if vpass else self.size[1],
# )
#
# def readable_args(self):
# return [
# "x".join(map(str, self.dest_size)),
# self.filter_ids.get(self.filter, self.filter),
# ]
#
# def readable_name(self):
# return 'to ' + super().readable_name()
#
# Path: testsuite/cases/pgmagick.py
# class PgmagickTestCase(BaseTestCase):
# def create_test_data(self):
. 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.