Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|># coding: utf-8 def test_to_json_schema(): struct = Dictionary({ 'list': List( <|code_end|> , predict the immediate next line with the help of imports: from jinja2schema import core from jinja2schema.model import Dictionary, Scalar, List, Unknown, Tuple, Number, Boolean, String and context (classes, functions, sometimes code) from other files: # Path: jinja2schema/core.py # def parse(template, jinja2_env=None): # def _ignore_constants(var): # def infer_from_ast(ast, ignore_constants=True, config=Config()): # def infer(template, config=Config()): # def encode_common_attrs(self, var): # def encode(self, var): # def encode(self, var): # def to_json_schema(var, jsonschema_encoder=JSONSchemaDraft4Encoder): # class JSONSchemaDraft4Encoder(object): # class StringJSONSchemaDraft4Encoder(JSONSchemaDraft4Encoder): # # Path: jinja2schema/model.py # class Dictionary(Variable): # """A dictionary. # # Implements some methods of Python :class:`dict`. # # .. automethod:: __setitem__ # .. automethod:: __getitem__ # .. automethod:: __delitem__ # .. automethod:: get # .. automethod:: items # .. automethod:: iteritems # .. automethod:: keys # .. automethod:: iterkeys # .. automethod:: pop # """ # # def __init__(self, data=None, **kwargs): # self.data = data or {} # super(Dictionary, self).__init__(**kwargs) # # def __eq__(self, other): # return super(Dictionary, self).__eq__(other) and self.data == other.data # # def __repr__(self): # return pprint.pformat(self.data) # # def clone(self): # rv = super(Dictionary, self).clone() # rv.data = {} # for k, v in _compat.iteritems(self.data): # rv.data[k] = v.clone() # return rv # # @classmethod # def from_ast(cls, ast, data=None, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(data, **kwargs) # # def __setitem__(self, key, value): # self.data[key] = value # # def __getitem__(self, key): # return self.data[key] # # def __delitem__(self, key): # del self.data[key] # # def __contains__(self, key): # return key in self.data # # def get(self, name, default=None): # if name in self: # return self[name] # else: # return default # # def items(self): # return self.data.items() # # def iteritems(self): # return _compat.iteritems(self.data) # # def keys(self): # return self.data.keys() # # def iterkeys(self): # return _compat.iterkeys(self.data) # # def pop(self, key, default=None): # return self.data.pop(key, default) # # class Scalar(Variable): # """A scalar. Either string, number, boolean or ``None``.""" # def __repr__(self): # return '<scalar>' # # class List(Variable): # """A list which items are of the same type. # # .. attribute:: item # # A structure of list items, subclass of :class:`Variable`. # """ # def __init__(self, item, **kwargs): # self.item = item # super(List, self).__init__(**kwargs) # # def __eq__(self, other): # return super(List, self).__eq__(other) and self.item == other.item # # def __repr__(self): # return pprint.pformat([self.item]) # # def clone(self): # rv = super(List, self).clone() # rv.item = self.item.clone() # return rv # # @classmethod # def from_ast(cls, ast, item, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(item, **kwargs) # # class Unknown(Variable): # """A variable which type is unknown.""" # def __repr__(self): # return '<unknown>' # # class Tuple(Variable): # """A tuple. # # .. attribute:: items # # A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown. # # .. attribute:: items # # Whether new elements can be added to the tuple in the process of merge or not. # """ # def __init__(self, items, **kwargs): # self.items = tuple(items) if items is not None else None # self.may_be_extended = kwargs.pop('may_be_extended', False) # super(Tuple, self).__init__(**kwargs) # # def __eq__(self, other): # return super(Tuple, self).__eq__(other) and self.items == other.items # # def __repr__(self): # return pprint.pformat(self.items) # # def clone(self): # rv = super(Tuple, self).clone() # rv.items = self.items and tuple(s.clone() for s in self.items) # return rv # # @classmethod # def from_ast(cls, ast, items, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(items, **kwargs) # # class Number(Scalar): # """A number.""" # def __repr__(self): # return '<number>' # # class Boolean(Scalar): # """A boolean.""" # def __repr__(self): # return '<boolean>' # # class String(Scalar): # """A string.""" # def __repr__(self): # return '<string>' . Output only the next line.
Tuple((
Based on the snippet: <|code_start|># coding: utf-8 def test_to_json_schema(): struct = Dictionary({ 'list': List( Tuple(( Dictionary({ 'field': Scalar(label='field', linenos=[3]), }, label='a', linenos=[3]), Scalar(label='b', linenos=[4]) ), linenos=[2]), label='list', linenos=[2] ), 'x': Unknown(may_be_defined=True), <|code_end|> , predict the immediate next line with the help of imports: from jinja2schema import core from jinja2schema.model import Dictionary, Scalar, List, Unknown, Tuple, Number, Boolean, String and context (classes, functions, sometimes code) from other files: # Path: jinja2schema/core.py # def parse(template, jinja2_env=None): # def _ignore_constants(var): # def infer_from_ast(ast, ignore_constants=True, config=Config()): # def infer(template, config=Config()): # def encode_common_attrs(self, var): # def encode(self, var): # def encode(self, var): # def to_json_schema(var, jsonschema_encoder=JSONSchemaDraft4Encoder): # class JSONSchemaDraft4Encoder(object): # class StringJSONSchemaDraft4Encoder(JSONSchemaDraft4Encoder): # # Path: jinja2schema/model.py # class Dictionary(Variable): # """A dictionary. # # Implements some methods of Python :class:`dict`. # # .. automethod:: __setitem__ # .. automethod:: __getitem__ # .. automethod:: __delitem__ # .. automethod:: get # .. automethod:: items # .. automethod:: iteritems # .. automethod:: keys # .. automethod:: iterkeys # .. automethod:: pop # """ # # def __init__(self, data=None, **kwargs): # self.data = data or {} # super(Dictionary, self).__init__(**kwargs) # # def __eq__(self, other): # return super(Dictionary, self).__eq__(other) and self.data == other.data # # def __repr__(self): # return pprint.pformat(self.data) # # def clone(self): # rv = super(Dictionary, self).clone() # rv.data = {} # for k, v in _compat.iteritems(self.data): # rv.data[k] = v.clone() # return rv # # @classmethod # def from_ast(cls, ast, data=None, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(data, **kwargs) # # def __setitem__(self, key, value): # self.data[key] = value # # def __getitem__(self, key): # return self.data[key] # # def __delitem__(self, key): # del self.data[key] # # def __contains__(self, key): # return key in self.data # # def get(self, name, default=None): # if name in self: # return self[name] # else: # return default # # def items(self): # return self.data.items() # # def iteritems(self): # return _compat.iteritems(self.data) # # def keys(self): # return self.data.keys() # # def iterkeys(self): # return _compat.iterkeys(self.data) # # def pop(self, key, default=None): # return self.data.pop(key, default) # # class Scalar(Variable): # """A scalar. Either string, number, boolean or ``None``.""" # def __repr__(self): # return '<scalar>' # # class List(Variable): # """A list which items are of the same type. # # .. attribute:: item # # A structure of list items, subclass of :class:`Variable`. # """ # def __init__(self, item, **kwargs): # self.item = item # super(List, self).__init__(**kwargs) # # def __eq__(self, other): # return super(List, self).__eq__(other) and self.item == other.item # # def __repr__(self): # return pprint.pformat([self.item]) # # def clone(self): # rv = super(List, self).clone() # rv.item = self.item.clone() # return rv # # @classmethod # def from_ast(cls, ast, item, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(item, **kwargs) # # class Unknown(Variable): # """A variable which type is unknown.""" # def __repr__(self): # return '<unknown>' # # class Tuple(Variable): # """A tuple. # # .. attribute:: items # # A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown. # # .. attribute:: items # # Whether new elements can be added to the tuple in the process of merge or not. # """ # def __init__(self, items, **kwargs): # self.items = tuple(items) if items is not None else None # self.may_be_extended = kwargs.pop('may_be_extended', False) # super(Tuple, self).__init__(**kwargs) # # def __eq__(self, other): # return super(Tuple, self).__eq__(other) and self.items == other.items # # def __repr__(self): # return pprint.pformat(self.items) # # def clone(self): # rv = super(Tuple, self).clone() # rv.items = self.items and tuple(s.clone() for s in self.items) # return rv # # @classmethod # def from_ast(cls, ast, items, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(items, **kwargs) # # class Number(Scalar): # """A number.""" # def __repr__(self): # return '<number>' # # class Boolean(Scalar): # """A boolean.""" # def __repr__(self): # return '<boolean>' # # class String(Scalar): # """A string.""" # def __repr__(self): # return '<string>' . Output only the next line.
'number_var': Number(),
Predict the next line for this snippet: <|code_start|># coding: utf-8 def test_to_json_schema(): struct = Dictionary({ 'list': List( Tuple(( Dictionary({ 'field': Scalar(label='field', linenos=[3]), }, label='a', linenos=[3]), Scalar(label='b', linenos=[4]) ), linenos=[2]), label='list', linenos=[2] ), 'x': Unknown(may_be_defined=True), 'number_var': Number(), 'string_var': String(), <|code_end|> with the help of current file imports: from jinja2schema import core from jinja2schema.model import Dictionary, Scalar, List, Unknown, Tuple, Number, Boolean, String and context from other files: # Path: jinja2schema/core.py # def parse(template, jinja2_env=None): # def _ignore_constants(var): # def infer_from_ast(ast, ignore_constants=True, config=Config()): # def infer(template, config=Config()): # def encode_common_attrs(self, var): # def encode(self, var): # def encode(self, var): # def to_json_schema(var, jsonschema_encoder=JSONSchemaDraft4Encoder): # class JSONSchemaDraft4Encoder(object): # class StringJSONSchemaDraft4Encoder(JSONSchemaDraft4Encoder): # # Path: jinja2schema/model.py # class Dictionary(Variable): # """A dictionary. # # Implements some methods of Python :class:`dict`. # # .. automethod:: __setitem__ # .. automethod:: __getitem__ # .. automethod:: __delitem__ # .. automethod:: get # .. automethod:: items # .. automethod:: iteritems # .. automethod:: keys # .. automethod:: iterkeys # .. automethod:: pop # """ # # def __init__(self, data=None, **kwargs): # self.data = data or {} # super(Dictionary, self).__init__(**kwargs) # # def __eq__(self, other): # return super(Dictionary, self).__eq__(other) and self.data == other.data # # def __repr__(self): # return pprint.pformat(self.data) # # def clone(self): # rv = super(Dictionary, self).clone() # rv.data = {} # for k, v in _compat.iteritems(self.data): # rv.data[k] = v.clone() # return rv # # @classmethod # def from_ast(cls, ast, data=None, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(data, **kwargs) # # def __setitem__(self, key, value): # self.data[key] = value # # def __getitem__(self, key): # return self.data[key] # # def __delitem__(self, key): # del self.data[key] # # def __contains__(self, key): # return key in self.data # # def get(self, name, default=None): # if name in self: # return self[name] # else: # return default # # def items(self): # return self.data.items() # # def iteritems(self): # return _compat.iteritems(self.data) # # def keys(self): # return self.data.keys() # # def iterkeys(self): # return _compat.iterkeys(self.data) # # def pop(self, key, default=None): # return self.data.pop(key, default) # # class Scalar(Variable): # """A scalar. Either string, number, boolean or ``None``.""" # def __repr__(self): # return '<scalar>' # # class List(Variable): # """A list which items are of the same type. # # .. attribute:: item # # A structure of list items, subclass of :class:`Variable`. # """ # def __init__(self, item, **kwargs): # self.item = item # super(List, self).__init__(**kwargs) # # def __eq__(self, other): # return super(List, self).__eq__(other) and self.item == other.item # # def __repr__(self): # return pprint.pformat([self.item]) # # def clone(self): # rv = super(List, self).clone() # rv.item = self.item.clone() # return rv # # @classmethod # def from_ast(cls, ast, item, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(item, **kwargs) # # class Unknown(Variable): # """A variable which type is unknown.""" # def __repr__(self): # return '<unknown>' # # class Tuple(Variable): # """A tuple. # # .. attribute:: items # # A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown. # # .. attribute:: items # # Whether new elements can be added to the tuple in the process of merge or not. # """ # def __init__(self, items, **kwargs): # self.items = tuple(items) if items is not None else None # self.may_be_extended = kwargs.pop('may_be_extended', False) # super(Tuple, self).__init__(**kwargs) # # def __eq__(self, other): # return super(Tuple, self).__eq__(other) and self.items == other.items # # def __repr__(self): # return pprint.pformat(self.items) # # def clone(self): # rv = super(Tuple, self).clone() # rv.items = self.items and tuple(s.clone() for s in self.items) # return rv # # @classmethod # def from_ast(cls, ast, items, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(items, **kwargs) # # class Number(Scalar): # """A number.""" # def __repr__(self): # return '<number>' # # class Boolean(Scalar): # """A boolean.""" # def __repr__(self): # return '<boolean>' # # class String(Scalar): # """A string.""" # def __repr__(self): # return '<string>' , which may contain function names, class names, or code. Output only the next line.
'boolean_var': Boolean(),
Based on the snippet: <|code_start|># coding: utf-8 def test_to_json_schema(): struct = Dictionary({ 'list': List( Tuple(( Dictionary({ 'field': Scalar(label='field', linenos=[3]), }, label='a', linenos=[3]), Scalar(label='b', linenos=[4]) ), linenos=[2]), label='list', linenos=[2] ), 'x': Unknown(may_be_defined=True), 'number_var': Number(), <|code_end|> , predict the immediate next line with the help of imports: from jinja2schema import core from jinja2schema.model import Dictionary, Scalar, List, Unknown, Tuple, Number, Boolean, String and context (classes, functions, sometimes code) from other files: # Path: jinja2schema/core.py # def parse(template, jinja2_env=None): # def _ignore_constants(var): # def infer_from_ast(ast, ignore_constants=True, config=Config()): # def infer(template, config=Config()): # def encode_common_attrs(self, var): # def encode(self, var): # def encode(self, var): # def to_json_schema(var, jsonschema_encoder=JSONSchemaDraft4Encoder): # class JSONSchemaDraft4Encoder(object): # class StringJSONSchemaDraft4Encoder(JSONSchemaDraft4Encoder): # # Path: jinja2schema/model.py # class Dictionary(Variable): # """A dictionary. # # Implements some methods of Python :class:`dict`. # # .. automethod:: __setitem__ # .. automethod:: __getitem__ # .. automethod:: __delitem__ # .. automethod:: get # .. automethod:: items # .. automethod:: iteritems # .. automethod:: keys # .. automethod:: iterkeys # .. automethod:: pop # """ # # def __init__(self, data=None, **kwargs): # self.data = data or {} # super(Dictionary, self).__init__(**kwargs) # # def __eq__(self, other): # return super(Dictionary, self).__eq__(other) and self.data == other.data # # def __repr__(self): # return pprint.pformat(self.data) # # def clone(self): # rv = super(Dictionary, self).clone() # rv.data = {} # for k, v in _compat.iteritems(self.data): # rv.data[k] = v.clone() # return rv # # @classmethod # def from_ast(cls, ast, data=None, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(data, **kwargs) # # def __setitem__(self, key, value): # self.data[key] = value # # def __getitem__(self, key): # return self.data[key] # # def __delitem__(self, key): # del self.data[key] # # def __contains__(self, key): # return key in self.data # # def get(self, name, default=None): # if name in self: # return self[name] # else: # return default # # def items(self): # return self.data.items() # # def iteritems(self): # return _compat.iteritems(self.data) # # def keys(self): # return self.data.keys() # # def iterkeys(self): # return _compat.iterkeys(self.data) # # def pop(self, key, default=None): # return self.data.pop(key, default) # # class Scalar(Variable): # """A scalar. Either string, number, boolean or ``None``.""" # def __repr__(self): # return '<scalar>' # # class List(Variable): # """A list which items are of the same type. # # .. attribute:: item # # A structure of list items, subclass of :class:`Variable`. # """ # def __init__(self, item, **kwargs): # self.item = item # super(List, self).__init__(**kwargs) # # def __eq__(self, other): # return super(List, self).__eq__(other) and self.item == other.item # # def __repr__(self): # return pprint.pformat([self.item]) # # def clone(self): # rv = super(List, self).clone() # rv.item = self.item.clone() # return rv # # @classmethod # def from_ast(cls, ast, item, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(item, **kwargs) # # class Unknown(Variable): # """A variable which type is unknown.""" # def __repr__(self): # return '<unknown>' # # class Tuple(Variable): # """A tuple. # # .. attribute:: items # # A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown. # # .. attribute:: items # # Whether new elements can be added to the tuple in the process of merge or not. # """ # def __init__(self, items, **kwargs): # self.items = tuple(items) if items is not None else None # self.may_be_extended = kwargs.pop('may_be_extended', False) # super(Tuple, self).__init__(**kwargs) # # def __eq__(self, other): # return super(Tuple, self).__eq__(other) and self.items == other.items # # def __repr__(self): # return pprint.pformat(self.items) # # def clone(self): # rv = super(Tuple, self).clone() # rv.items = self.items and tuple(s.clone() for s in self.items) # return rv # # @classmethod # def from_ast(cls, ast, items, **kwargs): # kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs) # return cls(items, **kwargs) # # class Number(Scalar): # """A number.""" # def __repr__(self): # return '<number>' # # class Boolean(Scalar): # """A boolean.""" # def __repr__(self): # return '<boolean>' # # class String(Scalar): # """A string.""" # def __repr__(self): # return '<string>' . Output only the next line.
'string_var': String(),
Given snippet: <|code_start|> Add a order number to make schema sortable. """ ORDER_NUMBER_SUB_COUNTER = True """Independent subsection order numbers Use a separate counter in subsections as order number creator. """ def __init__(self, TYPE_OF_VARIABLE_INDEXED_WITH_VARIABLE_TYPE='dictionary', TYPE_OF_VARIABLE_INDEXED_WITH_INTEGER_TYPE='list', BOOLEAN_CONDITIONS=False, PACKAGE_NAME='', TEMPLATE_DIR='templates', ORDER_NUMBER=False, ORDER_NUMBER_SUB_COUNTER=True): if TYPE_OF_VARIABLE_INDEXED_WITH_VARIABLE_TYPE not in ('dictionary', 'list'): raise ValueError('TYPE_OF_VARIABLE_INDEXED_WITH_VARIABLE_TYPE must be' 'either "dictionary" or "list"') if TYPE_OF_VARIABLE_INDEXED_WITH_INTEGER_TYPE not in ('dictionary', 'list', 'tuple'): raise ValueError('TYPE_OF_VARIABLE_INDEXED_WITH_VARIABLE_TYPE must be' 'either "dictionary", "tuple" or "list"') self.TYPE_OF_VARIABLE_INDEXED_WITH_INTEGER_TYPE = TYPE_OF_VARIABLE_INDEXED_WITH_INTEGER_TYPE self.TYPE_OF_VARIABLE_INDEXED_WITH_VARIABLE_TYPE = TYPE_OF_VARIABLE_INDEXED_WITH_VARIABLE_TYPE self.BOOLEAN_CONDITIONS = BOOLEAN_CONDITIONS self.PACKAGE_NAME = PACKAGE_NAME self.TEMPLATE_DIR = TEMPLATE_DIR self.ORDER_NUMBER = ORDER_NUMBER <|code_end|> , continue by predicting the next line. Consider current file imports: from .order_number import OrderNumber and context: # Path: jinja2schema/order_number.py # class OrderNumber(object): # """A base Order Number class. # # .. attribute:: number # # Initial counter value. # # .. attribute:: enabled # # Counter enabled or return None. # # """ # # def __init__(self, number=0, enabled=False, sub_counter_enabled=True): # self.start = number # self.number = self.start # self.order_enabled = enabled # self.sub_counter_enabled = sub_counter_enabled # # def get_next(self): # if self.order_enabled: # self.number += 1 # return self.number # return None # # @contextmanager # def sub_counter(self): # if self.sub_counter_enabled: # counter = self.number # self.number = self.start # yield # self.number = counter # return # yield which might include code, classes, or functions. Output only the next line.
self.ORDER_OBJECT = OrderNumber(number=1, enabled=self.ORDER_NUMBER,
Given snippet: <|code_start|> self.protocol.on(pattern, callback) log.msg('Registered %s for channel: %s' % (callback, pattern)) def cancel(self, pattern, callback): if not self.protocol: raise Exception('Event bus is not connected yet!') self.protocol.cancel(pattern, callback) log.msg('unRegistered %s for channel: %s' % (callback, pattern)) def once(self, pattern, callback): if not self.protocol: raise Exception('Event bus is not connected yet!') def _once_and_remove(*args, **kwargs): self.protocol.cancel(pattern, _once_and_remove) callback(*args, **kwargs) self.protocol.on(pattern, _once_and_remove) log.msg('Registered %s for single invocation on channel: %s' % (callback, pattern)) def wait_for_event(self, pattern, timeout=False): d = defer.Deferred() def _on_message(channel, message): if not d.called: d.callback(message) self.on(pattern, _on_message) if not timeout == 0: <|code_end|> , continue by predicting the next line. Consider current file imports: import json import txredisapi as redis from twisted.internet import reactor, defer from twisted.python import log from mcloud.util import txtimeout and context: # Path: mcloud/util.py # def txtimeout(deferred, timeout, fail): # # def _raise(): # deferred.errback(Failure(TxTimeoutEception(fail))) # # delayedCall = reactor.callLater(timeout, _raise) # # def gotResult(result): # if delayedCall.active(): # delayedCall.cancel() # return result # deferred.addBoth(gotResult) # # return deferred which might include code, classes, or functions. Output only the next line.
return txtimeout(d, timeout, lambda: d.callback(None))
Given the code snippet: <|code_start|> def test_inject_services(): class Boo(): pass class Baz(): pass def configure(binder): binder.bind(Boo, Baz()) <|code_end|> , generate the next line using the imports in this file: import inject from mcloud.util import inject_services and context (functions, classes, or occasionally code) from other files: # Path: mcloud/util.py # @contextmanager # def inject_services(configurator): # inject.clear_and_configure(configurator) # yield # inject.clear() . Output only the next line.
with inject_services(configure):
Continue the code snippet: <|code_start|> protocol.sendClose() self.clients = [] def register_task(self, name, callback): """ Add new task to task list """ self.tasks[name] = callback def bind(self): """ Start listening on the port specified """ factory = WebSocketServerFactory(debug=False) factory.noisy = False factory.server = self factory.protocol = MdcloudWebsocketServerProtocol web_resource = File(resource_filename(__name__, 'static/build/client')) rootResource = WSGIRootResource(web_resource, {'ws': WebSocketResource(factory)}) if not self.no_ssl and self.settings and self.settings.ssl.enabled: print '*' * 60 print 'Running in secure mode' print 'Ssl key: %s' % self.settings.ssl.key print 'Ssl certificate: %s' % self.settings.ssl.cert print '*' * 60 <|code_end|> . Use current file imports: import json import os import sys import inject import txredisapi from autobahn.twisted.resource import WSGIRootResource, WebSocketResource from mcloud.ssl import listen_ssl from mcloud.events import EventBus from twisted.internet import reactor, defer from twisted.internet.defer import inlineCallbacks, AlreadyCalledError, CancelledError from autobahn.twisted.websocket import WebSocketServerFactory from autobahn.twisted.websocket import WebSocketClientFactory from twisted.python.failure import Failure from twisted.web.server import Site from twisted.python import log from twisted.web.static import File from pkg_resources import resource_filename from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketServerProtocol from mcloud.ssl import CtxFactory from twisted.python import log and context (classes, functions, or code) from other files: # Path: mcloud/ssl.py # def listen_ssl(port, resource, interface): # # settings = inject.instance('settings') # # from OpenSSL import SSL # # from twisted.internet import ssl # # myContextFactory = ssl.DefaultOpenSSLContextFactory( # settings.ssl.key, settings.ssl.cert, sslmethod=SSL.SSLv23_METHOD # ) # ctx = myContextFactory.getContext() # # ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_CLIENT_ONCE | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verifyCallback) # ctx.set_session_cache_mode(SSL.SESS_CACHE_BOTH) # # # Since we have self-signed certs we have to explicitly # # tell the server to trust them. # # ctx.load_verify_locations(settings.ssl.ca) # ctx.set_session_id(str(datetime.datetime.now())) # # reactor.listenSSL(port, resource, myContextFactory, interface=interface) # # Path: mcloud/events.py # class EventBus(object): # redis = None # protocol = None # # def __init__(self, redis_connection): # super(EventBus, self).__init__() # self.redis = redis_connection # # def fire_event(self, event_name, data=None, *args, **kwargs): # if not data: # if kwargs: # data = kwargs # elif args: # data = args # # if not isinstance(data, basestring): # data = 'j:' + json.dumps(data) # else: # data = 'b:' + str(data) # # return self.redis.publish(event_name, data) # # # def connect(self, host="127.0.0.1", port=6379): # log.msg('Event bus connected') # d = defer.Deferred() # reactor.connectTCP(host, port, EventBusFactory(d, self)) # return d # # def on(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # self.protocol.on(pattern, callback) # log.msg('Registered %s for channel: %s' % (callback, pattern)) # # def cancel(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # self.protocol.cancel(pattern, callback) # log.msg('unRegistered %s for channel: %s' % (callback, pattern)) # # def once(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # # def _once_and_remove(*args, **kwargs): # self.protocol.cancel(pattern, _once_and_remove) # callback(*args, **kwargs) # # self.protocol.on(pattern, _once_and_remove) # log.msg('Registered %s for single invocation on channel: %s' % (callback, pattern)) # # def wait_for_event(self, pattern, timeout=False): # d = defer.Deferred() # # def _on_message(channel, message): # if not d.called: # d.callback(message) # # self.on(pattern, _on_message) # # if not timeout == 0: # return txtimeout(d, timeout, lambda: d.callback(None)) # else: # return d . Output only the next line.
listen_ssl(self.port, Site(rootResource), interface=self.settings.websocket_ip)
Given snippet: <|code_start|> class ApiError(Exception): pass class ApiRpcServer(object): redis = inject.attr(txredisapi.Connection) <|code_end|> , continue by predicting the next line. Consider current file imports: import json import os import sys import inject import txredisapi from autobahn.twisted.resource import WSGIRootResource, WebSocketResource from mcloud.ssl import listen_ssl from mcloud.events import EventBus from twisted.internet import reactor, defer from twisted.internet.defer import inlineCallbacks, AlreadyCalledError, CancelledError from autobahn.twisted.websocket import WebSocketServerFactory from autobahn.twisted.websocket import WebSocketClientFactory from twisted.python.failure import Failure from twisted.web.server import Site from twisted.python import log from twisted.web.static import File from pkg_resources import resource_filename from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketServerProtocol from mcloud.ssl import CtxFactory from twisted.python import log and context: # Path: mcloud/ssl.py # def listen_ssl(port, resource, interface): # # settings = inject.instance('settings') # # from OpenSSL import SSL # # from twisted.internet import ssl # # myContextFactory = ssl.DefaultOpenSSLContextFactory( # settings.ssl.key, settings.ssl.cert, sslmethod=SSL.SSLv23_METHOD # ) # ctx = myContextFactory.getContext() # # ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_CLIENT_ONCE | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verifyCallback) # ctx.set_session_cache_mode(SSL.SESS_CACHE_BOTH) # # # Since we have self-signed certs we have to explicitly # # tell the server to trust them. # # ctx.load_verify_locations(settings.ssl.ca) # ctx.set_session_id(str(datetime.datetime.now())) # # reactor.listenSSL(port, resource, myContextFactory, interface=interface) # # Path: mcloud/events.py # class EventBus(object): # redis = None # protocol = None # # def __init__(self, redis_connection): # super(EventBus, self).__init__() # self.redis = redis_connection # # def fire_event(self, event_name, data=None, *args, **kwargs): # if not data: # if kwargs: # data = kwargs # elif args: # data = args # # if not isinstance(data, basestring): # data = 'j:' + json.dumps(data) # else: # data = 'b:' + str(data) # # return self.redis.publish(event_name, data) # # # def connect(self, host="127.0.0.1", port=6379): # log.msg('Event bus connected') # d = defer.Deferred() # reactor.connectTCP(host, port, EventBusFactory(d, self)) # return d # # def on(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # self.protocol.on(pattern, callback) # log.msg('Registered %s for channel: %s' % (callback, pattern)) # # def cancel(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # self.protocol.cancel(pattern, callback) # log.msg('unRegistered %s for channel: %s' % (callback, pattern)) # # def once(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # # def _once_and_remove(*args, **kwargs): # self.protocol.cancel(pattern, _once_and_remove) # callback(*args, **kwargs) # # self.protocol.on(pattern, _once_and_remove) # log.msg('Registered %s for single invocation on channel: %s' % (callback, pattern)) # # def wait_for_event(self, pattern, timeout=False): # d = defer.Deferred() # # def _on_message(channel, message): # if not d.called: # d.callback(message) # # self.on(pattern, _on_message) # # if not timeout == 0: # return txtimeout(d, timeout, lambda: d.callback(None)) # else: # return d which might include code, classes, or functions. Output only the next line.
eb = inject.attr(EventBus)
Here is a snippet: <|code_start|>html_theme_path = ['themes/cloud.modera.org'] html_theme = 'docs_theme' # html_theme = 'basic' plantuml = 'java -jar %s/plantuml.jar' % os.path.dirname(__file__) # if not on_rtd: # only import and set the theme if we're building docs locally # import sphinx_rtd_theme # html_theme = 'sphinx_rtd_theme' # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # show todos todo_include_todos = True # Add any paths that contain templates here, relative to this directory. # templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. <|code_end|> . Write the next line using the current file imports: import os import sys from mcloud import metadata and context from other files: # Path: mcloud/metadata.py , which may include functions, classes, or code. Output only the next line.
project = metadata.project
Given the code snippet: <|code_start|> def green(text): print(color_text(text, color='green')) def yellow(text): print(color_text(text, color='blue', bcolor='yellow')) def info(text): print() class ShellCancelInterruptHandler(object): def interrupt(self, last=None): if last is None: print('Hit Ctrl+D for exit.') <|code_end|> , generate the next line using the imports in this file: import sys import readline import inject import os from autobahn.twisted.util import sleep from bashutils.colors import color_text from mcloud.interrupt import InterruptCancel from mcloud.rpc_client import subparsers, arg_parser, ApiRpcClient, ClientProcessInterruptHandler from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from mcloud.logo import logo and context (functions, classes, or occasionally code) from other files: # Path: mcloud/interrupt.py # class InterruptCancel(Exception): # pass # # Path: mcloud/rpc_client.py # def format_epilog(): # def __init__(self, config, command): # def call(self, to=None, **kwargs): # def load_commands(config): # def cli(help_, arguments=None, by_ref=False, name=None): # def cmd_decorator(func): # def _run(*args, **kwargs): # def arg(*args, **kwargs): # def __init__(self, client): # def interrupt(self, last=None): # def __init__(self, host=None, port=None, settings=None): # def override_host(self, host): # def _remote_exec(self, task_name, *args, **kwargs): # def print_progress(self, message): # def _exec_remote_with_pty(self, task_name, *args): # def print_app_details(self, app): # def print_app_list(self, data): # def format_app_srv(self, app, service): # def format_domain(self, domain, ssl): # def parse_app_ref(self, ref, args, require_service=False, app_only=False, require_app=True, require_host=False): # def get_app(self, app_name): # def on_vars_result(self, data): # def get_volume_config(self, destination): # def on_result(volume_port): # def shell(self, **kwargs): # def list(self, follow=False, **kwargs): # def _print(data): # def init(self, ref, path, config=None, env=None, deployment=None, sync=False, **kwargs): # def represent_ordereddict(self, dumper, data): # def config(self, ref, diff=False, config=None, update=False, set_env=None, **kwargs): # def remove(self, ref, **kwargs): # def set_deployment(self, ref, deployment, **kwargs): # def start(self, ref, init=False, env=None, deployment=None, **kwargs): # def create(self, ref, **kwargs): # def destroy(self, ref, scrub_data, **kwargs): # def restart(self, ref, **kwargs): # def rebuild(self, ref, scrub_data, **kwargs): # def stop(self, ref, **kwargs): # def status(self, ref, follow=False, **kwargs): # def _print(data): # def machine(self, command, **kwargs): # def deployments(self, **kwargs): # def deployment_create(self, deployment, ip_host=None, port=None, tls=None, local=True, **kwargs): # def deployment_update(self, deployment, ip_host=None, port=None, tls=None, local=None, **kwargs): # def deployment_set_default(self, deployment, host, **kwargs): # def deployment_set(self, deployment, ca=False, cert=False, key=False, infile=None, remove=None, **kwargs): # def deployment_remove(self, deployment, **kwargs): # def publish(self, ref, domain, ssl=False, port=None, **kwargs): # def unpublish(self, ref, domain, ssl=False, **kwargs): # def run(self, ref, command, no_tty=False, **kwargs): # def logs(self, ref, follow=False, **kwargs): # def inspect(self, ref, **kwargs): # def push(self, volume, host, **kwargs): # def sync(self, source, destination, **kwargs): # def backup(self, source, volume, destination, **kwargs): # def restore(self, source, volume, destination, **kwargs): # def set(self, name, val, **kwargs): # def unset(self, name, **kwargs): # def vars(self, **kwargs): # def clean(self, **kwargs): # def dns(self, **kwargs): # def ps(self, **kwargs): # def kill(self, task_id=None, **kwargs): # class LocalCommand(object): # class CommandFailedException(Exception): # class ClientProcessInterruptHandler(object): # class ApiRpcClient(object): . Output only the next line.
raise InterruptCancel()
Given the following code snippet before the placeholder: <|code_start|> settings = inject.instance('settings') interrupt_manager = inject.instance('interrupt_manager') readline.parse_and_bind('tab: complete') if host_ref: app, host = host_ref.split('@') state = { 'app': app, 'host': host, } else: state = { 'app': None, 'host': 'me', } def use(name, **kwargs): if '@' in name: app, host = name.split('@') if host.strip() == '': host = 'me' if app.strip() == '': app = None state['app'] = app state['host'] = host else: state['app'] = name <|code_end|> , predict the next line using imports from the current file: import sys import readline import inject import os from autobahn.twisted.util import sleep from bashutils.colors import color_text from mcloud.interrupt import InterruptCancel from mcloud.rpc_client import subparsers, arg_parser, ApiRpcClient, ClientProcessInterruptHandler from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from mcloud.logo import logo and context including class names, function names, and sometimes code from other files: # Path: mcloud/interrupt.py # class InterruptCancel(Exception): # pass # # Path: mcloud/rpc_client.py # def format_epilog(): # def __init__(self, config, command): # def call(self, to=None, **kwargs): # def load_commands(config): # def cli(help_, arguments=None, by_ref=False, name=None): # def cmd_decorator(func): # def _run(*args, **kwargs): # def arg(*args, **kwargs): # def __init__(self, client): # def interrupt(self, last=None): # def __init__(self, host=None, port=None, settings=None): # def override_host(self, host): # def _remote_exec(self, task_name, *args, **kwargs): # def print_progress(self, message): # def _exec_remote_with_pty(self, task_name, *args): # def print_app_details(self, app): # def print_app_list(self, data): # def format_app_srv(self, app, service): # def format_domain(self, domain, ssl): # def parse_app_ref(self, ref, args, require_service=False, app_only=False, require_app=True, require_host=False): # def get_app(self, app_name): # def on_vars_result(self, data): # def get_volume_config(self, destination): # def on_result(volume_port): # def shell(self, **kwargs): # def list(self, follow=False, **kwargs): # def _print(data): # def init(self, ref, path, config=None, env=None, deployment=None, sync=False, **kwargs): # def represent_ordereddict(self, dumper, data): # def config(self, ref, diff=False, config=None, update=False, set_env=None, **kwargs): # def remove(self, ref, **kwargs): # def set_deployment(self, ref, deployment, **kwargs): # def start(self, ref, init=False, env=None, deployment=None, **kwargs): # def create(self, ref, **kwargs): # def destroy(self, ref, scrub_data, **kwargs): # def restart(self, ref, **kwargs): # def rebuild(self, ref, scrub_data, **kwargs): # def stop(self, ref, **kwargs): # def status(self, ref, follow=False, **kwargs): # def _print(data): # def machine(self, command, **kwargs): # def deployments(self, **kwargs): # def deployment_create(self, deployment, ip_host=None, port=None, tls=None, local=True, **kwargs): # def deployment_update(self, deployment, ip_host=None, port=None, tls=None, local=None, **kwargs): # def deployment_set_default(self, deployment, host, **kwargs): # def deployment_set(self, deployment, ca=False, cert=False, key=False, infile=None, remove=None, **kwargs): # def deployment_remove(self, deployment, **kwargs): # def publish(self, ref, domain, ssl=False, port=None, **kwargs): # def unpublish(self, ref, domain, ssl=False, **kwargs): # def run(self, ref, command, no_tty=False, **kwargs): # def logs(self, ref, follow=False, **kwargs): # def inspect(self, ref, **kwargs): # def push(self, volume, host, **kwargs): # def sync(self, source, destination, **kwargs): # def backup(self, source, volume, destination, **kwargs): # def restore(self, source, volume, destination, **kwargs): # def set(self, name, val, **kwargs): # def unset(self, name, **kwargs): # def vars(self, **kwargs): # def clean(self, **kwargs): # def dns(self, **kwargs): # def ps(self, **kwargs): # def kill(self, task_id=None, **kwargs): # class LocalCommand(object): # class CommandFailedException(Exception): # class ClientProcessInterruptHandler(object): # class ApiRpcClient(object): . Output only the next line.
cmd = subparsers.add_parser('use')
Given the following code snippet before the placeholder: <|code_start|> pass interrupt_manager.append(ShellCancelInterruptHandler()) # prevent stop reactor on Ctrl + C line = '' while line != 'exit': print('') prompt = 'mcloud: %s@%s> ' % (state['app'] or '~', state['host']) try: line = None yield sleep(0.05) line = raw_input(color_text(prompt, color='white', bcolor='blue') + ' ').strip() if line.startswith('!'): os.system(line[1:]) continue if line == '': continue if line == 'exit': break readline.write_history_file(histfile) params = line.split(' ') <|code_end|> , predict the next line using imports from the current file: import sys import readline import inject import os from autobahn.twisted.util import sleep from bashutils.colors import color_text from mcloud.interrupt import InterruptCancel from mcloud.rpc_client import subparsers, arg_parser, ApiRpcClient, ClientProcessInterruptHandler from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from mcloud.logo import logo and context including class names, function names, and sometimes code from other files: # Path: mcloud/interrupt.py # class InterruptCancel(Exception): # pass # # Path: mcloud/rpc_client.py # def format_epilog(): # def __init__(self, config, command): # def call(self, to=None, **kwargs): # def load_commands(config): # def cli(help_, arguments=None, by_ref=False, name=None): # def cmd_decorator(func): # def _run(*args, **kwargs): # def arg(*args, **kwargs): # def __init__(self, client): # def interrupt(self, last=None): # def __init__(self, host=None, port=None, settings=None): # def override_host(self, host): # def _remote_exec(self, task_name, *args, **kwargs): # def print_progress(self, message): # def _exec_remote_with_pty(self, task_name, *args): # def print_app_details(self, app): # def print_app_list(self, data): # def format_app_srv(self, app, service): # def format_domain(self, domain, ssl): # def parse_app_ref(self, ref, args, require_service=False, app_only=False, require_app=True, require_host=False): # def get_app(self, app_name): # def on_vars_result(self, data): # def get_volume_config(self, destination): # def on_result(volume_port): # def shell(self, **kwargs): # def list(self, follow=False, **kwargs): # def _print(data): # def init(self, ref, path, config=None, env=None, deployment=None, sync=False, **kwargs): # def represent_ordereddict(self, dumper, data): # def config(self, ref, diff=False, config=None, update=False, set_env=None, **kwargs): # def remove(self, ref, **kwargs): # def set_deployment(self, ref, deployment, **kwargs): # def start(self, ref, init=False, env=None, deployment=None, **kwargs): # def create(self, ref, **kwargs): # def destroy(self, ref, scrub_data, **kwargs): # def restart(self, ref, **kwargs): # def rebuild(self, ref, scrub_data, **kwargs): # def stop(self, ref, **kwargs): # def status(self, ref, follow=False, **kwargs): # def _print(data): # def machine(self, command, **kwargs): # def deployments(self, **kwargs): # def deployment_create(self, deployment, ip_host=None, port=None, tls=None, local=True, **kwargs): # def deployment_update(self, deployment, ip_host=None, port=None, tls=None, local=None, **kwargs): # def deployment_set_default(self, deployment, host, **kwargs): # def deployment_set(self, deployment, ca=False, cert=False, key=False, infile=None, remove=None, **kwargs): # def deployment_remove(self, deployment, **kwargs): # def publish(self, ref, domain, ssl=False, port=None, **kwargs): # def unpublish(self, ref, domain, ssl=False, **kwargs): # def run(self, ref, command, no_tty=False, **kwargs): # def logs(self, ref, follow=False, **kwargs): # def inspect(self, ref, **kwargs): # def push(self, volume, host, **kwargs): # def sync(self, source, destination, **kwargs): # def backup(self, source, volume, destination, **kwargs): # def restore(self, source, volume, destination, **kwargs): # def set(self, name, val, **kwargs): # def unset(self, name, **kwargs): # def vars(self, **kwargs): # def clean(self, **kwargs): # def dns(self, **kwargs): # def ps(self, **kwargs): # def kill(self, task_id=None, **kwargs): # class LocalCommand(object): # class CommandFailedException(Exception): # class ClientProcessInterruptHandler(object): # class ApiRpcClient(object): . Output only the next line.
args = arg_parser.parse_args(params)
Continue the code snippet: <|code_start|> readline.write_history_file(histfile) params = line.split(' ') args = arg_parser.parse_args(params) args.argv0 = sys.argv[0] if args.host: host = args.host elif state['host'] == 'me' or not state['host']: # manual variable if 'MCLOUD_HOST' in os.environ: host = os.environ['MCLOUD_HOST'] # automatic when using docker container-link elif 'MCLOUD_PORT' in os.environ: host = os.environ['MCLOUD_PORT'] if host.startswith('tcp://'): host = host[6:] else: host = '127.0.0.1' else: host = state['host'] if ':' in host: host, port = host.split(':') else: port = 7080 <|code_end|> . Use current file imports: import sys import readline import inject import os from autobahn.twisted.util import sleep from bashutils.colors import color_text from mcloud.interrupt import InterruptCancel from mcloud.rpc_client import subparsers, arg_parser, ApiRpcClient, ClientProcessInterruptHandler from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from mcloud.logo import logo and context (classes, functions, or code) from other files: # Path: mcloud/interrupt.py # class InterruptCancel(Exception): # pass # # Path: mcloud/rpc_client.py # def format_epilog(): # def __init__(self, config, command): # def call(self, to=None, **kwargs): # def load_commands(config): # def cli(help_, arguments=None, by_ref=False, name=None): # def cmd_decorator(func): # def _run(*args, **kwargs): # def arg(*args, **kwargs): # def __init__(self, client): # def interrupt(self, last=None): # def __init__(self, host=None, port=None, settings=None): # def override_host(self, host): # def _remote_exec(self, task_name, *args, **kwargs): # def print_progress(self, message): # def _exec_remote_with_pty(self, task_name, *args): # def print_app_details(self, app): # def print_app_list(self, data): # def format_app_srv(self, app, service): # def format_domain(self, domain, ssl): # def parse_app_ref(self, ref, args, require_service=False, app_only=False, require_app=True, require_host=False): # def get_app(self, app_name): # def on_vars_result(self, data): # def get_volume_config(self, destination): # def on_result(volume_port): # def shell(self, **kwargs): # def list(self, follow=False, **kwargs): # def _print(data): # def init(self, ref, path, config=None, env=None, deployment=None, sync=False, **kwargs): # def represent_ordereddict(self, dumper, data): # def config(self, ref, diff=False, config=None, update=False, set_env=None, **kwargs): # def remove(self, ref, **kwargs): # def set_deployment(self, ref, deployment, **kwargs): # def start(self, ref, init=False, env=None, deployment=None, **kwargs): # def create(self, ref, **kwargs): # def destroy(self, ref, scrub_data, **kwargs): # def restart(self, ref, **kwargs): # def rebuild(self, ref, scrub_data, **kwargs): # def stop(self, ref, **kwargs): # def status(self, ref, follow=False, **kwargs): # def _print(data): # def machine(self, command, **kwargs): # def deployments(self, **kwargs): # def deployment_create(self, deployment, ip_host=None, port=None, tls=None, local=True, **kwargs): # def deployment_update(self, deployment, ip_host=None, port=None, tls=None, local=None, **kwargs): # def deployment_set_default(self, deployment, host, **kwargs): # def deployment_set(self, deployment, ca=False, cert=False, key=False, infile=None, remove=None, **kwargs): # def deployment_remove(self, deployment, **kwargs): # def publish(self, ref, domain, ssl=False, port=None, **kwargs): # def unpublish(self, ref, domain, ssl=False, **kwargs): # def run(self, ref, command, no_tty=False, **kwargs): # def logs(self, ref, follow=False, **kwargs): # def inspect(self, ref, **kwargs): # def push(self, volume, host, **kwargs): # def sync(self, source, destination, **kwargs): # def backup(self, source, volume, destination, **kwargs): # def restore(self, source, volume, destination, **kwargs): # def set(self, name, val, **kwargs): # def unset(self, name, **kwargs): # def vars(self, **kwargs): # def clean(self, **kwargs): # def dns(self, **kwargs): # def ps(self, **kwargs): # def kill(self, task_id=None, **kwargs): # class LocalCommand(object): # class CommandFailedException(Exception): # class ClientProcessInterruptHandler(object): # class ApiRpcClient(object): . Output only the next line.
client = ApiRpcClient(host=host, port=port, settings=settings)
Based on the snippet: <|code_start|> params = line.split(' ') args = arg_parser.parse_args(params) args.argv0 = sys.argv[0] if args.host: host = args.host elif state['host'] == 'me' or not state['host']: # manual variable if 'MCLOUD_HOST' in os.environ: host = os.environ['MCLOUD_HOST'] # automatic when using docker container-link elif 'MCLOUD_PORT' in os.environ: host = os.environ['MCLOUD_PORT'] if host.startswith('tcp://'): host = host[6:] else: host = '127.0.0.1' else: host = state['host'] if ':' in host: host, port = host.split(':') else: port = 7080 client = ApiRpcClient(host=host, port=port, settings=settings) <|code_end|> , predict the immediate next line with the help of imports: import sys import readline import inject import os from autobahn.twisted.util import sleep from bashutils.colors import color_text from mcloud.interrupt import InterruptCancel from mcloud.rpc_client import subparsers, arg_parser, ApiRpcClient, ClientProcessInterruptHandler from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from mcloud.logo import logo and context (classes, functions, sometimes code) from other files: # Path: mcloud/interrupt.py # class InterruptCancel(Exception): # pass # # Path: mcloud/rpc_client.py # def format_epilog(): # def __init__(self, config, command): # def call(self, to=None, **kwargs): # def load_commands(config): # def cli(help_, arguments=None, by_ref=False, name=None): # def cmd_decorator(func): # def _run(*args, **kwargs): # def arg(*args, **kwargs): # def __init__(self, client): # def interrupt(self, last=None): # def __init__(self, host=None, port=None, settings=None): # def override_host(self, host): # def _remote_exec(self, task_name, *args, **kwargs): # def print_progress(self, message): # def _exec_remote_with_pty(self, task_name, *args): # def print_app_details(self, app): # def print_app_list(self, data): # def format_app_srv(self, app, service): # def format_domain(self, domain, ssl): # def parse_app_ref(self, ref, args, require_service=False, app_only=False, require_app=True, require_host=False): # def get_app(self, app_name): # def on_vars_result(self, data): # def get_volume_config(self, destination): # def on_result(volume_port): # def shell(self, **kwargs): # def list(self, follow=False, **kwargs): # def _print(data): # def init(self, ref, path, config=None, env=None, deployment=None, sync=False, **kwargs): # def represent_ordereddict(self, dumper, data): # def config(self, ref, diff=False, config=None, update=False, set_env=None, **kwargs): # def remove(self, ref, **kwargs): # def set_deployment(self, ref, deployment, **kwargs): # def start(self, ref, init=False, env=None, deployment=None, **kwargs): # def create(self, ref, **kwargs): # def destroy(self, ref, scrub_data, **kwargs): # def restart(self, ref, **kwargs): # def rebuild(self, ref, scrub_data, **kwargs): # def stop(self, ref, **kwargs): # def status(self, ref, follow=False, **kwargs): # def _print(data): # def machine(self, command, **kwargs): # def deployments(self, **kwargs): # def deployment_create(self, deployment, ip_host=None, port=None, tls=None, local=True, **kwargs): # def deployment_update(self, deployment, ip_host=None, port=None, tls=None, local=None, **kwargs): # def deployment_set_default(self, deployment, host, **kwargs): # def deployment_set(self, deployment, ca=False, cert=False, key=False, infile=None, remove=None, **kwargs): # def deployment_remove(self, deployment, **kwargs): # def publish(self, ref, domain, ssl=False, port=None, **kwargs): # def unpublish(self, ref, domain, ssl=False, **kwargs): # def run(self, ref, command, no_tty=False, **kwargs): # def logs(self, ref, follow=False, **kwargs): # def inspect(self, ref, **kwargs): # def push(self, volume, host, **kwargs): # def sync(self, source, destination, **kwargs): # def backup(self, source, volume, destination, **kwargs): # def restore(self, source, volume, destination, **kwargs): # def set(self, name, val, **kwargs): # def unset(self, name, **kwargs): # def vars(self, **kwargs): # def clean(self, **kwargs): # def dns(self, **kwargs): # def ps(self, **kwargs): # def kill(self, task_id=None, **kwargs): # class LocalCommand(object): # class CommandFailedException(Exception): # class ClientProcessInterruptHandler(object): # class ApiRpcClient(object): . Output only the next line.
interrupt_manager.append(ClientProcessInterruptHandler(client))
Predict the next line after this snippet: <|code_start|> # no image or build {'foo': {}}, # some random key { 'foo': { 'build1': 'boo' } } ]) def test_validate_invalid(config): c = YamlConfig() with pytest.raises(ValueError): assert c.validate(config) def test_process(): c = YamlConfig() flexmock(c) c.should_receive('process_image_build').once() c.should_receive('process_volumes_build').once() c.should_receive('process_command_build').once() c.process({ 'nginx': {'foo': 'bar'} }, path='foo') <|code_end|> using the current file's imports: from collections import OrderedDict from flexmock import flexmock from mcloud.config import YamlConfig, Service, UnknownServiceError, ConfigParseError from mcloud.container import PrebuiltImageBuilder, DockerfileImageBuilder, InlineDockerfileImageBuilder import os import pytest and any relevant context from other files: # Path: mcloud/config.py # class IConfig(Interface): # class ConfigParseError(Exception): # class UnknownServiceError(Exception): # class OrderedDictYAMLLoader(yaml.Loader): # class YamlConfig(IConfig): # def get_services(self): # def __init__(self, *args, **kwargs): # def construct_yaml_map(self, node): # def construct_mapping(self, node, deep=False): # def __init__(self, file=None, source=None, app_name=None, path=None, env=None): # def get_services(self): # def get_volumes(self): # def get_command_host(self, name=None): # def get_commands(self): # def get_service(self, name): # def load(self, process=True, client=None): # def export(self): # def filter_env(self, config): # def prepare(self, config): # def validate(self, config): # def process_command_build(self, service, config, path): # def process_other_settings_build(self, service, config, path): # def sanitize_path(self, path): # def process_volumes_build(self, service, config, path): # def process_env_build(self, service, config, path): # def process_image_build(self, service, config, path): # def process_local_config(self, config): # def process(self, config, path, app_name=None, client=None): # # Path: mcloud/container.py # class PrebuiltImageBuilder(IImageBuilder): # def __init__(self, image): # super(PrebuiltImageBuilder, self).__init__() # # self.image = image # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # # log.msg('[%s] Building image "%s".', ticket_id, self.image) # # name = self.image # tag = None # if ':' in name: # name, tag = name.split(':') # # images = yield service.client.images(name=name) # # if tag: # images = [x for x in images if self.image in x['RepoTags']] # # if not images: # log.msg('[%s] Image is not there. Pulling "%s" ...', ticket_id, self.image) # # yield service.client.pull(name, ticket_id, tag) # # log.msg('[%s] Image "%s" is ready to use.', ticket_id, self.image) # defer.returnValue(self.image) # # class DockerfileImageBuilder(IImageBuilder): # def __init__(self, path): # super(DockerfileImageBuilder, self).__init__() # self.path = path # # self.image_id = None # # def create_archive(self): # d = defer.Deferred() # # def archive(): # memfile = StringIO() # try: # t = tarfile.open(mode='w', fileobj=memfile) # t.add(self.path, arcname='.') # d.callback(memfile.getvalue()) # except OSError as e: # d.errback(CanNotAccessPath('Can not access %s: %s' % (self.path, str(e)))) # except Exception as e: # d.errback(e) # finally: # memfile.close() # # reactor.callLater(0, archive) # return d # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # archive = yield self.create_archive() # ret = yield service.client.build_image(archive, ticket_id=ticket_id) # defer.returnValue(ret) # # class InlineDockerfileImageBuilder(VirtualFolderImageBuilder): # def __init__(self, source): # super(InlineDockerfileImageBuilder, self).__init__({ # 'Dockerfile': source # }) . Output only the next line.
assert isinstance(c.services['nginx'], Service)
Given the code snippet: <|code_start|> assert isinstance(s.image_builder, InlineDockerfileImageBuilder) assert s.image_builder.files['Dockerfile'] == 'FROM foo\nWORKDIR boo' def test_build_image_dockerfile_no_path(): s = Service() c = YamlConfig() with pytest.raises(ConfigParseError): c.process_image_build(s, {'build': 'foo/bar'}, None) def test_build_image_empty(): s = Service() c = YamlConfig() with pytest.raises(ValueError) as e: c.process_image_build(s, {}, '/base/path') def test_get_service(): c = YamlConfig() c.services = {'foo': 'bar'} assert c.get_service('foo') == 'bar' def test_get_service_no(): c = YamlConfig() c.services = {'foo': 'bar'} <|code_end|> , generate the next line using the imports in this file: from collections import OrderedDict from flexmock import flexmock from mcloud.config import YamlConfig, Service, UnknownServiceError, ConfigParseError from mcloud.container import PrebuiltImageBuilder, DockerfileImageBuilder, InlineDockerfileImageBuilder import os import pytest and context (functions, classes, or occasionally code) from other files: # Path: mcloud/config.py # class IConfig(Interface): # class ConfigParseError(Exception): # class UnknownServiceError(Exception): # class OrderedDictYAMLLoader(yaml.Loader): # class YamlConfig(IConfig): # def get_services(self): # def __init__(self, *args, **kwargs): # def construct_yaml_map(self, node): # def construct_mapping(self, node, deep=False): # def __init__(self, file=None, source=None, app_name=None, path=None, env=None): # def get_services(self): # def get_volumes(self): # def get_command_host(self, name=None): # def get_commands(self): # def get_service(self, name): # def load(self, process=True, client=None): # def export(self): # def filter_env(self, config): # def prepare(self, config): # def validate(self, config): # def process_command_build(self, service, config, path): # def process_other_settings_build(self, service, config, path): # def sanitize_path(self, path): # def process_volumes_build(self, service, config, path): # def process_env_build(self, service, config, path): # def process_image_build(self, service, config, path): # def process_local_config(self, config): # def process(self, config, path, app_name=None, client=None): # # Path: mcloud/container.py # class PrebuiltImageBuilder(IImageBuilder): # def __init__(self, image): # super(PrebuiltImageBuilder, self).__init__() # # self.image = image # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # # log.msg('[%s] Building image "%s".', ticket_id, self.image) # # name = self.image # tag = None # if ':' in name: # name, tag = name.split(':') # # images = yield service.client.images(name=name) # # if tag: # images = [x for x in images if self.image in x['RepoTags']] # # if not images: # log.msg('[%s] Image is not there. Pulling "%s" ...', ticket_id, self.image) # # yield service.client.pull(name, ticket_id, tag) # # log.msg('[%s] Image "%s" is ready to use.', ticket_id, self.image) # defer.returnValue(self.image) # # class DockerfileImageBuilder(IImageBuilder): # def __init__(self, path): # super(DockerfileImageBuilder, self).__init__() # self.path = path # # self.image_id = None # # def create_archive(self): # d = defer.Deferred() # # def archive(): # memfile = StringIO() # try: # t = tarfile.open(mode='w', fileobj=memfile) # t.add(self.path, arcname='.') # d.callback(memfile.getvalue()) # except OSError as e: # d.errback(CanNotAccessPath('Can not access %s: %s' % (self.path, str(e)))) # except Exception as e: # d.errback(e) # finally: # memfile.close() # # reactor.callLater(0, archive) # return d # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # archive = yield self.create_archive() # ret = yield service.client.build_image(archive, ticket_id=ticket_id) # defer.returnValue(ret) # # class InlineDockerfileImageBuilder(VirtualFolderImageBuilder): # def __init__(self, source): # super(InlineDockerfileImageBuilder, self).__init__({ # 'Dockerfile': source # }) . Output only the next line.
with pytest.raises(UnknownServiceError):
Continue the code snippet: <|code_start|>def test_load_config(tmpdir): p = tmpdir.join('mcloud.yml') p.write('foo: bar') config = YamlConfig(file=p.realpath(), app_name='myapp') flexmock(config).should_receive('prepare').with_args({'foo': 'bar'}).once().and_return({'foo': 'bar1'}) flexmock(config).should_receive('validate').with_args({'foo': 'bar1'}).once() flexmock(config).should_receive('process').with_args(OrderedDict([('foo', 'bar1')]), path=None, app_name='myapp', client='booo').once() config.load(client='booo') def test_load_config_from_config(): config = YamlConfig(source='{"foo": "bar"}', app_name='myapp') flexmock(config).should_receive('prepare').with_args({'foo': 'bar'}).once().and_return({'foo': 'bar1'}) flexmock(config).should_receive('validate').with_args({'foo': 'bar1'}).once() flexmock(config).should_receive('process').with_args(OrderedDict([('foo', 'bar1')]), path=None, app_name='myapp', client='booo').once() config.load(client='booo') def test_load_config_not_valid(tmpdir): p = tmpdir.join('mcloud.yml') p.write('foo: bar') config = YamlConfig(file=p.realpath(), app_name='myapp') flexmock(config).should_receive('prepare').with_args({'foo': 'bar'}).once().and_return({'foo': 'bar1'}) flexmock(config).should_receive('validate').with_args({'foo': 'bar1'}).once().and_raise(ValueError('boo')) flexmock(config).should_receive('process').times(0) <|code_end|> . Use current file imports: from collections import OrderedDict from flexmock import flexmock from mcloud.config import YamlConfig, Service, UnknownServiceError, ConfigParseError from mcloud.container import PrebuiltImageBuilder, DockerfileImageBuilder, InlineDockerfileImageBuilder import os import pytest and context (classes, functions, or code) from other files: # Path: mcloud/config.py # class IConfig(Interface): # class ConfigParseError(Exception): # class UnknownServiceError(Exception): # class OrderedDictYAMLLoader(yaml.Loader): # class YamlConfig(IConfig): # def get_services(self): # def __init__(self, *args, **kwargs): # def construct_yaml_map(self, node): # def construct_mapping(self, node, deep=False): # def __init__(self, file=None, source=None, app_name=None, path=None, env=None): # def get_services(self): # def get_volumes(self): # def get_command_host(self, name=None): # def get_commands(self): # def get_service(self, name): # def load(self, process=True, client=None): # def export(self): # def filter_env(self, config): # def prepare(self, config): # def validate(self, config): # def process_command_build(self, service, config, path): # def process_other_settings_build(self, service, config, path): # def sanitize_path(self, path): # def process_volumes_build(self, service, config, path): # def process_env_build(self, service, config, path): # def process_image_build(self, service, config, path): # def process_local_config(self, config): # def process(self, config, path, app_name=None, client=None): # # Path: mcloud/container.py # class PrebuiltImageBuilder(IImageBuilder): # def __init__(self, image): # super(PrebuiltImageBuilder, self).__init__() # # self.image = image # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # # log.msg('[%s] Building image "%s".', ticket_id, self.image) # # name = self.image # tag = None # if ':' in name: # name, tag = name.split(':') # # images = yield service.client.images(name=name) # # if tag: # images = [x for x in images if self.image in x['RepoTags']] # # if not images: # log.msg('[%s] Image is not there. Pulling "%s" ...', ticket_id, self.image) # # yield service.client.pull(name, ticket_id, tag) # # log.msg('[%s] Image "%s" is ready to use.', ticket_id, self.image) # defer.returnValue(self.image) # # class DockerfileImageBuilder(IImageBuilder): # def __init__(self, path): # super(DockerfileImageBuilder, self).__init__() # self.path = path # # self.image_id = None # # def create_archive(self): # d = defer.Deferred() # # def archive(): # memfile = StringIO() # try: # t = tarfile.open(mode='w', fileobj=memfile) # t.add(self.path, arcname='.') # d.callback(memfile.getvalue()) # except OSError as e: # d.errback(CanNotAccessPath('Can not access %s: %s' % (self.path, str(e)))) # except Exception as e: # d.errback(e) # finally: # memfile.close() # # reactor.callLater(0, archive) # return d # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # archive = yield self.create_archive() # ret = yield service.client.build_image(archive, ticket_id=ticket_id) # defer.returnValue(ret) # # class InlineDockerfileImageBuilder(VirtualFolderImageBuilder): # def __init__(self, source): # super(InlineDockerfileImageBuilder, self).__init__({ # 'Dockerfile': source # }) . Output only the next line.
with pytest.raises(ConfigParseError):
Given the following code snippet before the placeholder: <|code_start|> c = YamlConfig(env='dev') c.process_env_build(s, {}, '/base/path') assert s.env == {'env': 'dev'} def test_build_build_env_several(): s = Service() c = YamlConfig(env='prod') c.process_env_build(s, {'env': { 'foo1': 'bar1', 'foo2': 'bar2', 'foo3': 'bar3', }}, '/base/path') assert s.env == { 'env': 'prod', 'foo1': 'bar1', 'foo2': 'bar2', 'foo3': 'bar3', } def test_build_image_image(): s = Service() c = YamlConfig() c.process_image_build(s, {'image': 'foo/bar'}, '/base/path') <|code_end|> , predict the next line using imports from the current file: from collections import OrderedDict from flexmock import flexmock from mcloud.config import YamlConfig, Service, UnknownServiceError, ConfigParseError from mcloud.container import PrebuiltImageBuilder, DockerfileImageBuilder, InlineDockerfileImageBuilder import os import pytest and context including class names, function names, and sometimes code from other files: # Path: mcloud/config.py # class IConfig(Interface): # class ConfigParseError(Exception): # class UnknownServiceError(Exception): # class OrderedDictYAMLLoader(yaml.Loader): # class YamlConfig(IConfig): # def get_services(self): # def __init__(self, *args, **kwargs): # def construct_yaml_map(self, node): # def construct_mapping(self, node, deep=False): # def __init__(self, file=None, source=None, app_name=None, path=None, env=None): # def get_services(self): # def get_volumes(self): # def get_command_host(self, name=None): # def get_commands(self): # def get_service(self, name): # def load(self, process=True, client=None): # def export(self): # def filter_env(self, config): # def prepare(self, config): # def validate(self, config): # def process_command_build(self, service, config, path): # def process_other_settings_build(self, service, config, path): # def sanitize_path(self, path): # def process_volumes_build(self, service, config, path): # def process_env_build(self, service, config, path): # def process_image_build(self, service, config, path): # def process_local_config(self, config): # def process(self, config, path, app_name=None, client=None): # # Path: mcloud/container.py # class PrebuiltImageBuilder(IImageBuilder): # def __init__(self, image): # super(PrebuiltImageBuilder, self).__init__() # # self.image = image # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # # log.msg('[%s] Building image "%s".', ticket_id, self.image) # # name = self.image # tag = None # if ':' in name: # name, tag = name.split(':') # # images = yield service.client.images(name=name) # # if tag: # images = [x for x in images if self.image in x['RepoTags']] # # if not images: # log.msg('[%s] Image is not there. Pulling "%s" ...', ticket_id, self.image) # # yield service.client.pull(name, ticket_id, tag) # # log.msg('[%s] Image "%s" is ready to use.', ticket_id, self.image) # defer.returnValue(self.image) # # class DockerfileImageBuilder(IImageBuilder): # def __init__(self, path): # super(DockerfileImageBuilder, self).__init__() # self.path = path # # self.image_id = None # # def create_archive(self): # d = defer.Deferred() # # def archive(): # memfile = StringIO() # try: # t = tarfile.open(mode='w', fileobj=memfile) # t.add(self.path, arcname='.') # d.callback(memfile.getvalue()) # except OSError as e: # d.errback(CanNotAccessPath('Can not access %s: %s' % (self.path, str(e)))) # except Exception as e: # d.errback(e) # finally: # memfile.close() # # reactor.callLater(0, archive) # return d # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # archive = yield self.create_archive() # ret = yield service.client.build_image(archive, ticket_id=ticket_id) # defer.returnValue(ret) # # class InlineDockerfileImageBuilder(VirtualFolderImageBuilder): # def __init__(self, source): # super(InlineDockerfileImageBuilder, self).__init__({ # 'Dockerfile': source # }) . Output only the next line.
assert isinstance(s.image_builder, PrebuiltImageBuilder)
Given snippet: <|code_start|> c.process_env_build(s, {'env': { 'foo1': 'bar1', 'foo2': 'bar2', 'foo3': 'bar3', }}, '/base/path') assert s.env == { 'env': 'prod', 'foo1': 'bar1', 'foo2': 'bar2', 'foo3': 'bar3', } def test_build_image_image(): s = Service() c = YamlConfig() c.process_image_build(s, {'image': 'foo/bar'}, '/base/path') assert isinstance(s.image_builder, PrebuiltImageBuilder) assert s.image_builder.image == 'foo/bar' def test_build_image_dockerfile(): s = Service() c = YamlConfig() c.process_image_build(s, {'build': 'foo/bar'}, '/base/path') <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import OrderedDict from flexmock import flexmock from mcloud.config import YamlConfig, Service, UnknownServiceError, ConfigParseError from mcloud.container import PrebuiltImageBuilder, DockerfileImageBuilder, InlineDockerfileImageBuilder import os import pytest and context: # Path: mcloud/config.py # class IConfig(Interface): # class ConfigParseError(Exception): # class UnknownServiceError(Exception): # class OrderedDictYAMLLoader(yaml.Loader): # class YamlConfig(IConfig): # def get_services(self): # def __init__(self, *args, **kwargs): # def construct_yaml_map(self, node): # def construct_mapping(self, node, deep=False): # def __init__(self, file=None, source=None, app_name=None, path=None, env=None): # def get_services(self): # def get_volumes(self): # def get_command_host(self, name=None): # def get_commands(self): # def get_service(self, name): # def load(self, process=True, client=None): # def export(self): # def filter_env(self, config): # def prepare(self, config): # def validate(self, config): # def process_command_build(self, service, config, path): # def process_other_settings_build(self, service, config, path): # def sanitize_path(self, path): # def process_volumes_build(self, service, config, path): # def process_env_build(self, service, config, path): # def process_image_build(self, service, config, path): # def process_local_config(self, config): # def process(self, config, path, app_name=None, client=None): # # Path: mcloud/container.py # class PrebuiltImageBuilder(IImageBuilder): # def __init__(self, image): # super(PrebuiltImageBuilder, self).__init__() # # self.image = image # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # # log.msg('[%s] Building image "%s".', ticket_id, self.image) # # name = self.image # tag = None # if ':' in name: # name, tag = name.split(':') # # images = yield service.client.images(name=name) # # if tag: # images = [x for x in images if self.image in x['RepoTags']] # # if not images: # log.msg('[%s] Image is not there. Pulling "%s" ...', ticket_id, self.image) # # yield service.client.pull(name, ticket_id, tag) # # log.msg('[%s] Image "%s" is ready to use.', ticket_id, self.image) # defer.returnValue(self.image) # # class DockerfileImageBuilder(IImageBuilder): # def __init__(self, path): # super(DockerfileImageBuilder, self).__init__() # self.path = path # # self.image_id = None # # def create_archive(self): # d = defer.Deferred() # # def archive(): # memfile = StringIO() # try: # t = tarfile.open(mode='w', fileobj=memfile) # t.add(self.path, arcname='.') # d.callback(memfile.getvalue()) # except OSError as e: # d.errback(CanNotAccessPath('Can not access %s: %s' % (self.path, str(e)))) # except Exception as e: # d.errback(e) # finally: # memfile.close() # # reactor.callLater(0, archive) # return d # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # archive = yield self.create_archive() # ret = yield service.client.build_image(archive, ticket_id=ticket_id) # defer.returnValue(ret) # # class InlineDockerfileImageBuilder(VirtualFolderImageBuilder): # def __init__(self, source): # super(InlineDockerfileImageBuilder, self).__init__({ # 'Dockerfile': source # }) which might include code, classes, or functions. Output only the next line.
assert isinstance(s.image_builder, DockerfileImageBuilder)
Using the snippet: <|code_start|> 'foo2': 'bar2', 'foo3': 'bar3', } def test_build_image_image(): s = Service() c = YamlConfig() c.process_image_build(s, {'image': 'foo/bar'}, '/base/path') assert isinstance(s.image_builder, PrebuiltImageBuilder) assert s.image_builder.image == 'foo/bar' def test_build_image_dockerfile(): s = Service() c = YamlConfig() c.process_image_build(s, {'build': 'foo/bar'}, '/base/path') assert isinstance(s.image_builder, DockerfileImageBuilder) assert s.image_builder.path == '/base/path/foo/bar' def test_build_inline_dockerfile(): s = Service() c = YamlConfig() c.process_image_build(s, {'dockerfile': 'FROM foo\nWORKDIR boo'}, '/base/path') <|code_end|> , determine the next line of code. You have imports: from collections import OrderedDict from flexmock import flexmock from mcloud.config import YamlConfig, Service, UnknownServiceError, ConfigParseError from mcloud.container import PrebuiltImageBuilder, DockerfileImageBuilder, InlineDockerfileImageBuilder import os import pytest and context (class names, function names, or code) available: # Path: mcloud/config.py # class IConfig(Interface): # class ConfigParseError(Exception): # class UnknownServiceError(Exception): # class OrderedDictYAMLLoader(yaml.Loader): # class YamlConfig(IConfig): # def get_services(self): # def __init__(self, *args, **kwargs): # def construct_yaml_map(self, node): # def construct_mapping(self, node, deep=False): # def __init__(self, file=None, source=None, app_name=None, path=None, env=None): # def get_services(self): # def get_volumes(self): # def get_command_host(self, name=None): # def get_commands(self): # def get_service(self, name): # def load(self, process=True, client=None): # def export(self): # def filter_env(self, config): # def prepare(self, config): # def validate(self, config): # def process_command_build(self, service, config, path): # def process_other_settings_build(self, service, config, path): # def sanitize_path(self, path): # def process_volumes_build(self, service, config, path): # def process_env_build(self, service, config, path): # def process_image_build(self, service, config, path): # def process_local_config(self, config): # def process(self, config, path, app_name=None, client=None): # # Path: mcloud/container.py # class PrebuiltImageBuilder(IImageBuilder): # def __init__(self, image): # super(PrebuiltImageBuilder, self).__init__() # # self.image = image # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # # log.msg('[%s] Building image "%s".', ticket_id, self.image) # # name = self.image # tag = None # if ':' in name: # name, tag = name.split(':') # # images = yield service.client.images(name=name) # # if tag: # images = [x for x in images if self.image in x['RepoTags']] # # if not images: # log.msg('[%s] Image is not there. Pulling "%s" ...', ticket_id, self.image) # # yield service.client.pull(name, ticket_id, tag) # # log.msg('[%s] Image "%s" is ready to use.', ticket_id, self.image) # defer.returnValue(self.image) # # class DockerfileImageBuilder(IImageBuilder): # def __init__(self, path): # super(DockerfileImageBuilder, self).__init__() # self.path = path # # self.image_id = None # # def create_archive(self): # d = defer.Deferred() # # def archive(): # memfile = StringIO() # try: # t = tarfile.open(mode='w', fileobj=memfile) # t.add(self.path, arcname='.') # d.callback(memfile.getvalue()) # except OSError as e: # d.errback(CanNotAccessPath('Can not access %s: %s' % (self.path, str(e)))) # except Exception as e: # d.errback(e) # finally: # memfile.close() # # reactor.callLater(0, archive) # return d # # @defer.inlineCallbacks # def build_image(self, ticket_id, service): # archive = yield self.create_archive() # ret = yield service.client.build_image(archive, ticket_id=ticket_id) # defer.returnValue(ret) # # class InlineDockerfileImageBuilder(VirtualFolderImageBuilder): # def __init__(self, source): # super(InlineDockerfileImageBuilder, self).__init__({ # 'Dockerfile': source # }) . Output only the next line.
assert isinstance(s.image_builder, InlineDockerfileImageBuilder)
Predict the next line for this snippet: <|code_start|> @pytest.inlineCallbacks def test_events(): inject.clear() rc = yield redis.Connection(dbid=2) yield rc.flushdb() <|code_end|> with the help of current file imports: import inject import pytest import txredisapi as redis from mcloud.events import EventBus from twisted.internet import reactor and context from other files: # Path: mcloud/events.py # class EventBus(object): # redis = None # protocol = None # # def __init__(self, redis_connection): # super(EventBus, self).__init__() # self.redis = redis_connection # # def fire_event(self, event_name, data=None, *args, **kwargs): # if not data: # if kwargs: # data = kwargs # elif args: # data = args # # if not isinstance(data, basestring): # data = 'j:' + json.dumps(data) # else: # data = 'b:' + str(data) # # return self.redis.publish(event_name, data) # # # def connect(self, host="127.0.0.1", port=6379): # log.msg('Event bus connected') # d = defer.Deferred() # reactor.connectTCP(host, port, EventBusFactory(d, self)) # return d # # def on(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # self.protocol.on(pattern, callback) # log.msg('Registered %s for channel: %s' % (callback, pattern)) # # def cancel(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # self.protocol.cancel(pattern, callback) # log.msg('unRegistered %s for channel: %s' % (callback, pattern)) # # def once(self, pattern, callback): # if not self.protocol: # raise Exception('Event bus is not connected yet!') # # def _once_and_remove(*args, **kwargs): # self.protocol.cancel(pattern, _once_and_remove) # callback(*args, **kwargs) # # self.protocol.on(pattern, _once_and_remove) # log.msg('Registered %s for single invocation on channel: %s' % (callback, pattern)) # # def wait_for_event(self, pattern, timeout=False): # d = defer.Deferred() # # def _on_message(channel, message): # if not d.called: # d.callback(message) # # self.on(pattern, _on_message) # # if not timeout == 0: # return txtimeout(d, timeout, lambda: d.callback(None)) # else: # return d , which may contain function names, class names, or code. Output only the next line.
eb = EventBus(rc)
Using the snippet: <|code_start|> else: return [params] @staticmethod def _default_flatten(numq): if numq == 1: return lambda x: x else: return lambda x: itertools.chain(*x) def add_and_matches(self, matcher, lhs, params, numq=1, flatten=None): """ Add AND conditions to match to `params`. :type matcher: str or callable :arg matcher: if `str`, `matcher.format` is used. :type lhs: str :arg lhs: the first argument to `matcher`. :type params: list :arg params: each element should be able to feed into sqlite '?'. :type numq: int :arg numq: number of parameters for each condition. :type flatten: None or callable :arg flatten: when `numq > 1`, it should return a list of length `numq * len(params)`. """ params = self._adapt_params(params) qs = ['?'] * numq flatten = flatten or self._default_flatten(numq) <|code_end|> , determine the next line of code. You have imports: import itertools from .iterutils import repeat and context (class names, function names, or code) available: # Path: rash/utils/iterutils.py # def repeat(item, num): # return itertools.islice(itertools.repeat(item), num) . Output only the next line.
expr = repeat(adapt_matcher(matcher)(lhs, *qs), len(params))
Next line prediction: <|code_start|># Copyright (C) 2013- Takafumi Arakaki # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class TestExpandQuery(BaseTestCase): def setUp(self): self.config = Configuration() self.config.search.alias['test'] = ["--include-pattern", "*test*"] self.config.search.alias['build'] = ["--include-pattern", "*build*"] def test_alias_no_query_no_expansion(self): <|code_end|> . Use current file imports: (from ..config import Configuration from ..query import expand_query from .utils import BaseTestCase) and context including class names, function names, or small code snippets from other files: # Path: rash/config.py # class Configuration(object): # # """ # RASH configuration interface. # # If you define an object named :data:`config` in the # :term:`configuration file`, it is going to be loaded by RASH. # :data:`config` must be an instance of :class:`Configuration`. # # .. glossary:: # # configuration file # In unix-like systems, it's :file:`~/.config/rash/config.py` or # different place if you set :envvar:`XDG_CONFIG_HOME`. In Mac # OS, it's :file:`~/Library/Application Support/RASH/config.py`. # Use ``rash locate config`` to locate the exact place. # # Example: # # >>> from rash.config import Configuration # >>> config = Configuration() # >>> config.isearch.query = '-u .' # # Here is a list of configuration variables you can set: # # =========================== =========================================== # Configuration variables # =========================== =========================================== # |record.environ| Environment variables to record. # |search.alias| Search query alias. # |search.kwds_adapter| Transform keyword arguments. # |isearch.query| Default isearch query. # |isearch.query_template| Transform default query. # |isearch.base_query| Default isearch base query. # =========================== =========================================== # # .. |record.environ| replace:: # :attr:`config.record.environ <RecordConfig.environ>` # .. |search.alias| replace:: # :attr:`config.search.alias <SearchConfig.alias>` # .. |search.kwds_adapter| replace:: # :attr:`config.search.kwds_adapter <SearchConfig.kwds_adapter>` # .. |isearch.query| replace:: # :attr:`config.isearch.query <ISearchConfig.query>` # .. |isearch.query_template| replace:: # :attr:`config.isearch.query_template <ISearchConfig.query_template>` # .. |isearch.base_query| replace:: # :attr:`config.isearch.base_query <ISearchConfig.base_query>` # # """ # # def __init__(self): # self.record = RecordConfig() # self.search = SearchConfig() # self.isearch = ISearchConfig() # # Path: rash/query.py # def expand_query(config, kwds): # """ # Expand `kwds` based on `config.search.query_expander`. # # :type config: .config.Configuration # :type kwds: dict # :rtype: dict # :return: Return `kwds`, modified in place. # # """ # pattern = [] # for query in kwds.pop('pattern', []): # expansion = config.search.alias.get(query) # if expansion is None: # pattern.append(query) # else: # parser = SafeArgumentParser() # search_add_arguments(parser) # ns = parser.parse_args(expansion) # for (key, value) in vars(ns).items(): # if isinstance(value, (list, tuple)): # if not kwds.get(key): # kwds[key] = value # else: # kwds[key].extend(value) # else: # kwds[key] = value # kwds['pattern'] = pattern # return config.search.kwds_adapter(kwds) # # Path: rash/tests/utils.py # class BaseTestCase(unittest.TestCase): # # if not hasattr(unittest.TestCase, 'assertIn'): # def assertIn(self, member, container): # self.assertTrue(member in container) # # if not hasattr(unittest.TestCase, 'assertNotIn'): # def assertNotIn(self, member, container): # self.assertTrue(member not in container) # # if not hasattr(unittest.TestCase, 'assertIsInstance'): # def assertIsInstance(self, obj, cls, msg=None): # self.assertTrue(isinstance(obj, cls), msg) # # if not hasattr(unittest.TestCase, 'assertSetEqual'): # def assertSetEqual(self, set1, set2, msg=None): # self.assertEqual(set1, set2, msg) . Output only the next line.
kwds = expand_query(self.config, {})
Given the code snippet: <|code_start|> :type data: dict :rtype: str .. [#] PID of the shell, i.e., PPID of this Python process. """ host = data['environ']['HOST'] tty = data['environ'].get('TTY') or 'NO_TTY' return ':'.join(map(str, [ host, tty, os.getppid(), data['start']])) def record_run(record_type, print_session_id, **kwds): """ Record shell history. """ if print_session_id and record_type != 'init': raise RuntimeError( '--print-session-id should be used with --record-type=init') cfstore = ConfigStore() # SOMEDAY: Pass a list of environment variables to shell by "rash # init" and don't read configuration in "rash record" command. It # is faster. config = cfstore.get_config() envkeys = config.record.environ[record_type] json_path = os.path.join(cfstore.record_path, record_type, time.strftime('%Y-%m-%d-%H%M%S.json')) <|code_end|> , generate the next line using the imports in this file: import os import time import json import platform from .utils.pathutils import mkdirp from .utils.py3compat import getcwd from .config import ConfigStore from .utils.termdetection import detect_terminal and context (functions, classes, or occasionally code) from other files: # Path: rash/utils/pathutils.py # def mkdirp(path): # """ # Make directory at `path` if it does not exist. # """ # if not os.path.isdir(path): # os.makedirs(path) # # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # def nested(*managers): # # Path: rash/config.py # class ConfigStore(object): # # """ # Configuration and data file store. # # RASH stores data in the following directory in Linux:: # # * ~/.config/ # $XDG_CONFIG_HOME # `--* rash/ # base_path # |--* daemon.pid # PID of daemon process # |--* daemon.log # Log file for daemon # `--* data/ # data_path # |--* db.sqlite # db_path ("indexed" record) # `--* record/ # record_path ("raw" record) # |--* command/ # command log # `--* init/ # initialization log # # In Mac OS and Windows, :attr:`base_path` may be different but # structure in the directory is the same. # # """ # # def __init__(self, base_path=None): # self.base_path = base_path or get_config_directory('RASH') # """ # Root directory for any RASH related data files (``~/.config/rash``). # """ # # self.config_path = os.path.join(self.base_path, 'config.py') # """ # File to store user configuration (``~/.config/rash/config.py``). # """ # # self.data_path = os.path.join(self.base_path, 'data') # """ # Directory to store data collected by RASH (``~/.config/rash/data``). # """ # # self.record_path = os.path.join(self.data_path, 'record') # """ # Shell history is stored in this directory at the first stage. # """ # # self.db_path = os.path.join(self.data_path, 'db.sqlite') # """ # Shell history is stored in the DB at this path. # """ # # self.daemon_pid_path = os.path.join(self.base_path, 'daemon.pid') # """ # A file to store daemon PID (``~/.config/rash/daemon.pid``). # """ # # self.daemon_log_path = os.path.join(self.base_path, 'daemon.log') # """ # Daemon log file (``~/.config/rash/daemon.log``). # """ # # self.daemon_log_level = 'INFO' # FIXME: make this configurable # """ # Daemon log level. # """ # # mkdirp(self.record_path) # # def get_config(self): # """ # Load user configuration or return default when not found. # # :rtype: :class:`Configuration` # # """ # if not self._config: # namespace = {} # if os.path.exists(self.config_path): # execfile(self.config_path, namespace) # self._config = namespace.get('config') or Configuration() # return self._config # _config = None . Output only the next line.
mkdirp(os.path.dirname(json_path))
Here is a snippet: <|code_start|> return ':'.join(map(str, [ host, tty, os.getppid(), data['start']])) def record_run(record_type, print_session_id, **kwds): """ Record shell history. """ if print_session_id and record_type != 'init': raise RuntimeError( '--print-session-id should be used with --record-type=init') cfstore = ConfigStore() # SOMEDAY: Pass a list of environment variables to shell by "rash # init" and don't read configuration in "rash record" command. It # is faster. config = cfstore.get_config() envkeys = config.record.environ[record_type] json_path = os.path.join(cfstore.record_path, record_type, time.strftime('%Y-%m-%d-%H%M%S.json')) mkdirp(os.path.dirname(json_path)) # Command line options directly map to record keys data = dict((k, v) for (k, v) in kwds.items() if v is not None) data.update( environ=get_environ(envkeys), ) # Automatically set some missing variables: <|code_end|> . Write the next line using the current file imports: import os import time import json import platform from .utils.pathutils import mkdirp from .utils.py3compat import getcwd from .config import ConfigStore from .utils.termdetection import detect_terminal and context from other files: # Path: rash/utils/pathutils.py # def mkdirp(path): # """ # Make directory at `path` if it does not exist. # """ # if not os.path.isdir(path): # os.makedirs(path) # # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # def nested(*managers): # # Path: rash/config.py # class ConfigStore(object): # # """ # Configuration and data file store. # # RASH stores data in the following directory in Linux:: # # * ~/.config/ # $XDG_CONFIG_HOME # `--* rash/ # base_path # |--* daemon.pid # PID of daemon process # |--* daemon.log # Log file for daemon # `--* data/ # data_path # |--* db.sqlite # db_path ("indexed" record) # `--* record/ # record_path ("raw" record) # |--* command/ # command log # `--* init/ # initialization log # # In Mac OS and Windows, :attr:`base_path` may be different but # structure in the directory is the same. # # """ # # def __init__(self, base_path=None): # self.base_path = base_path or get_config_directory('RASH') # """ # Root directory for any RASH related data files (``~/.config/rash``). # """ # # self.config_path = os.path.join(self.base_path, 'config.py') # """ # File to store user configuration (``~/.config/rash/config.py``). # """ # # self.data_path = os.path.join(self.base_path, 'data') # """ # Directory to store data collected by RASH (``~/.config/rash/data``). # """ # # self.record_path = os.path.join(self.data_path, 'record') # """ # Shell history is stored in this directory at the first stage. # """ # # self.db_path = os.path.join(self.data_path, 'db.sqlite') # """ # Shell history is stored in the DB at this path. # """ # # self.daemon_pid_path = os.path.join(self.base_path, 'daemon.pid') # """ # A file to store daemon PID (``~/.config/rash/daemon.pid``). # """ # # self.daemon_log_path = os.path.join(self.base_path, 'daemon.log') # """ # Daemon log file (``~/.config/rash/daemon.log``). # """ # # self.daemon_log_level = 'INFO' # FIXME: make this configurable # """ # Daemon log level. # """ # # mkdirp(self.record_path) # # def get_config(self): # """ # Load user configuration or return default when not found. # # :rtype: :class:`Configuration` # # """ # if not self._config: # namespace = {} # if os.path.exists(self.config_path): # execfile(self.config_path, namespace) # self._config = namespace.get('config') or Configuration() # return self._config # _config = None , which may include functions, classes, or code. Output only the next line.
data.setdefault('cwd', getcwd())
Given snippet: <|code_start|> setifnonempty('TTY', get_tty()) if needset('RASH_SPENV_TERMINAL'): setifnonempty('RASH_SPENV_TERMINAL', detect_terminal()) return subenv def generate_session_id(data): """ Generate session ID based on HOST, TTY, PID [#]_ and start time. :type data: dict :rtype: str .. [#] PID of the shell, i.e., PPID of this Python process. """ host = data['environ']['HOST'] tty = data['environ'].get('TTY') or 'NO_TTY' return ':'.join(map(str, [ host, tty, os.getppid(), data['start']])) def record_run(record_type, print_session_id, **kwds): """ Record shell history. """ if print_session_id and record_type != 'init': raise RuntimeError( '--print-session-id should be used with --record-type=init') <|code_end|> , continue by predicting the next line. Consider current file imports: import os import time import json import platform from .utils.pathutils import mkdirp from .utils.py3compat import getcwd from .config import ConfigStore from .utils.termdetection import detect_terminal and context: # Path: rash/utils/pathutils.py # def mkdirp(path): # """ # Make directory at `path` if it does not exist. # """ # if not os.path.isdir(path): # os.makedirs(path) # # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # def nested(*managers): # # Path: rash/config.py # class ConfigStore(object): # # """ # Configuration and data file store. # # RASH stores data in the following directory in Linux:: # # * ~/.config/ # $XDG_CONFIG_HOME # `--* rash/ # base_path # |--* daemon.pid # PID of daemon process # |--* daemon.log # Log file for daemon # `--* data/ # data_path # |--* db.sqlite # db_path ("indexed" record) # `--* record/ # record_path ("raw" record) # |--* command/ # command log # `--* init/ # initialization log # # In Mac OS and Windows, :attr:`base_path` may be different but # structure in the directory is the same. # # """ # # def __init__(self, base_path=None): # self.base_path = base_path or get_config_directory('RASH') # """ # Root directory for any RASH related data files (``~/.config/rash``). # """ # # self.config_path = os.path.join(self.base_path, 'config.py') # """ # File to store user configuration (``~/.config/rash/config.py``). # """ # # self.data_path = os.path.join(self.base_path, 'data') # """ # Directory to store data collected by RASH (``~/.config/rash/data``). # """ # # self.record_path = os.path.join(self.data_path, 'record') # """ # Shell history is stored in this directory at the first stage. # """ # # self.db_path = os.path.join(self.data_path, 'db.sqlite') # """ # Shell history is stored in the DB at this path. # """ # # self.daemon_pid_path = os.path.join(self.base_path, 'daemon.pid') # """ # A file to store daemon PID (``~/.config/rash/daemon.pid``). # """ # # self.daemon_log_path = os.path.join(self.base_path, 'daemon.log') # """ # Daemon log file (``~/.config/rash/daemon.log``). # """ # # self.daemon_log_level = 'INFO' # FIXME: make this configurable # """ # Daemon log level. # """ # # mkdirp(self.record_path) # # def get_config(self): # """ # Load user configuration or return default when not found. # # :rtype: :class:`Configuration` # # """ # if not self._config: # namespace = {} # if os.path.exists(self.config_path): # execfile(self.config_path, namespace) # self._config = namespace.get('config') or Configuration() # return self._config # _config = None which might include code, classes, or functions. Output only the next line.
cfstore = ConfigStore()
Here is a snippet: <|code_start|># You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class ConfigStore(object): """ Configuration and data file store. RASH stores data in the following directory in Linux:: * ~/.config/ # $XDG_CONFIG_HOME `--* rash/ # base_path |--* daemon.pid # PID of daemon process |--* daemon.log # Log file for daemon `--* data/ # data_path |--* db.sqlite # db_path ("indexed" record) `--* record/ # record_path ("raw" record) |--* command/ # command log `--* init/ # initialization log In Mac OS and Windows, :attr:`base_path` may be different but structure in the directory is the same. """ def __init__(self, base_path=None): <|code_end|> . Write the next line using the current file imports: import os from .utils.confutils import get_config_directory from .utils.pathutils import mkdirp and context from other files: # Path: rash/utils/confutils.py # def get_config_directory(appname): # """ # Get OS-specific configuration directory. # # :type appname: str # :arg appname: capitalized name of the application # # """ # if platform.system().lower() == 'windows': # path = os.path.join(os.getenv('APPDATA') or '~', appname, appname) # elif platform.system().lower() == 'darwin': # path = os.path.join('~', 'Library', 'Application Support', appname) # else: # path = os.path.join(os.getenv('XDG_CONFIG_HOME') or '~/.config', # appname.lower()) # return os.path.expanduser(path) # # Path: rash/utils/pathutils.py # def mkdirp(path): # """ # Make directory at `path` if it does not exist. # """ # if not os.path.isdir(path): # os.makedirs(path) , which may include functions, classes, or code. Output only the next line.
self.base_path = base_path or get_config_directory('RASH')
Next line prediction: <|code_start|> self.data_path = os.path.join(self.base_path, 'data') """ Directory to store data collected by RASH (``~/.config/rash/data``). """ self.record_path = os.path.join(self.data_path, 'record') """ Shell history is stored in this directory at the first stage. """ self.db_path = os.path.join(self.data_path, 'db.sqlite') """ Shell history is stored in the DB at this path. """ self.daemon_pid_path = os.path.join(self.base_path, 'daemon.pid') """ A file to store daemon PID (``~/.config/rash/daemon.pid``). """ self.daemon_log_path = os.path.join(self.base_path, 'daemon.log') """ Daemon log file (``~/.config/rash/daemon.log``). """ self.daemon_log_level = 'INFO' # FIXME: make this configurable """ Daemon log level. """ <|code_end|> . Use current file imports: (import os from .utils.confutils import get_config_directory from .utils.pathutils import mkdirp) and context including class names, function names, or small code snippets from other files: # Path: rash/utils/confutils.py # def get_config_directory(appname): # """ # Get OS-specific configuration directory. # # :type appname: str # :arg appname: capitalized name of the application # # """ # if platform.system().lower() == 'windows': # path = os.path.join(os.getenv('APPDATA') or '~', appname, appname) # elif platform.system().lower() == 'darwin': # path = os.path.join('~', 'Library', 'Application Support', appname) # else: # path = os.path.join(os.getenv('XDG_CONFIG_HOME') or '~/.config', # appname.lower()) # return os.path.expanduser(path) # # Path: rash/utils/pathutils.py # def mkdirp(path): # """ # Make directory at `path` if it does not exist. # """ # if not os.path.isdir(path): # os.makedirs(path) . Output only the next line.
mkdirp(self.record_path)
Predict the next line for this snippet: <|code_start|> if len(queue) > num: queue.pop(0) yield False for _ in queue: yield False def _forward_shifted_predicate(predicate, num, iterative, include_zero=True): counter = 0 for elem in iterative: if predicate(elem): counter = num yield include_zero elif counter > 0: yield True counter -= 1 else: yield False def include_before(predicate, num, iterative): """ Return elements in `iterative` including `num`-before elements. >>> list(include_before(lambda x: x == 'd', 2, 'abcded')) ['b', 'c', 'd', 'e', 'd'] """ (it0, it1) = itertools.tee(iterative) ps = _backward_shifted_predicate(predicate, num, it1) <|code_end|> with the help of current file imports: import itertools from .py3compat import zip and context from other files: # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # def nested(*managers): , which may contain function names, class names, or code. Output only the next line.
return (e for (e, p) in zip(it0, ps) if p)
Based on the snippet: <|code_start|> self.assertEqual(len(records['exit']), 1) self.assertEqual(len(records['command']), 1) command_data = [d['data'] for d in records['command']] self.assertEqual(command_data[0]['pipestatus'], [1, 0]) test_pipe_status_script = None """Set this to a shell script for :meth:`test_pipe_status`.""" def test_non_existing_directory(self): main_script = """ _rash-precmd mkdir non_existing_directory _rash-precmd cd non_existing_directory _rash-precmd rmdir ../non_existing_directory _rash-precmd : _rash-precmd cd .. """ script = self.get_script(main_script) (stdout, stderr) = self.run_shell(script) self.assertNotIn('Traceback', stderr) <|code_end|> , predict the immediate next line with the help of imports: import os import sys import subprocess import unittest import tempfile import shutil import textwrap import json import time from ..utils.py3compat import PY3 from ..config import ConfigStore from ..tests.utils import BaseTestCase, skipIf from ..record import get_environ and context (classes, functions, sometimes code) from other files: # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # # Path: rash/config.py # class ConfigStore(object): # # """ # Configuration and data file store. # # RASH stores data in the following directory in Linux:: # # * ~/.config/ # $XDG_CONFIG_HOME # `--* rash/ # base_path # |--* daemon.pid # PID of daemon process # |--* daemon.log # Log file for daemon # `--* data/ # data_path # |--* db.sqlite # db_path ("indexed" record) # `--* record/ # record_path ("raw" record) # |--* command/ # command log # `--* init/ # initialization log # # In Mac OS and Windows, :attr:`base_path` may be different but # structure in the directory is the same. # # """ # # def __init__(self, base_path=None): # self.base_path = base_path or get_config_directory('RASH') # """ # Root directory for any RASH related data files (``~/.config/rash``). # """ # # self.config_path = os.path.join(self.base_path, 'config.py') # """ # File to store user configuration (``~/.config/rash/config.py``). # """ # # self.data_path = os.path.join(self.base_path, 'data') # """ # Directory to store data collected by RASH (``~/.config/rash/data``). # """ # # self.record_path = os.path.join(self.data_path, 'record') # """ # Shell history is stored in this directory at the first stage. # """ # # self.db_path = os.path.join(self.data_path, 'db.sqlite') # """ # Shell history is stored in the DB at this path. # """ # # self.daemon_pid_path = os.path.join(self.base_path, 'daemon.pid') # """ # A file to store daemon PID (``~/.config/rash/daemon.pid``). # """ # # self.daemon_log_path = os.path.join(self.base_path, 'daemon.log') # """ # Daemon log file (``~/.config/rash/daemon.log``). # """ # # self.daemon_log_level = 'INFO' # FIXME: make this configurable # """ # Daemon log level. # """ # # mkdirp(self.record_path) # # def get_config(self): # """ # Load user configuration or return default when not found. # # :rtype: :class:`Configuration` # # """ # if not self._config: # namespace = {} # if os.path.exists(self.config_path): # execfile(self.config_path, namespace) # self._config = namespace.get('config') or Configuration() # return self._config # _config = None # # Path: rash/tests/utils.py # class BaseTestCase(unittest.TestCase): # # if not hasattr(unittest.TestCase, 'assertIn'): # def assertIn(self, member, container): # self.assertTrue(member in container) # # if not hasattr(unittest.TestCase, 'assertNotIn'): # def assertNotIn(self, member, container): # self.assertTrue(member not in container) # # if not hasattr(unittest.TestCase, 'assertIsInstance'): # def assertIsInstance(self, obj, cls, msg=None): # self.assertTrue(isinstance(obj, cls), msg) # # if not hasattr(unittest.TestCase, 'assertSetEqual'): # def assertSetEqual(self, set1, set2, msg=None): # self.assertEqual(set1, set2, msg) # # def skipIf(condition, reason): # def decorator(func): # @functools.wraps(func) # def wrapper(*args, **kwds): # if condition: # print("Skipping {0} because:".format(func.__name__)) # print(reason) # else: # return func(*args, **kwds) # return wrapper # return decorator . Output only the next line.
@skipIf(PY3, "watchdog does not support Python 3")
Using the snippet: <|code_start|> run_cli, ['init', '--shell', 'UNKNOWN_SHELL'], stderr=subprocess.PIPE) class FunctionalTestMixIn(object): """ MixIn class for isolating functional test environment. SOMEDAY: Make FunctionalTestMixIn work in non-*nix systems. (I think) This isolation does not work in Mac OS in Windows! I can workaround this by adding --config-dir global option to specify configuration directory from command line, rather than using $HOME. """ def setUp(self): self.home_dir = tempfile.mkdtemp(prefix='rash-test-') self.config_dir = os.path.join(self.home_dir, '.config') self.conf_base_path = os.path.join(self.config_dir, 'rash') self.environ = os.environ.copy() self.environ['HOME'] = self.home_dir # FIXME: run the test w/o $TERM self.environ['TERM'] = 'xterm-256color' # Make sure that $XDG_CONFIG_HOME does not confuse sub processes if 'XDG_CONFIG_HOME' in self.environ: del self.environ['XDG_CONFIG_HOME'] <|code_end|> , determine the next line of code. You have imports: import os import sys import subprocess import unittest import tempfile import shutil import textwrap import json import time from ..utils.py3compat import PY3 from ..config import ConfigStore from ..tests.utils import BaseTestCase, skipIf from ..record import get_environ and context (class names, function names, or code) available: # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # # Path: rash/config.py # class ConfigStore(object): # # """ # Configuration and data file store. # # RASH stores data in the following directory in Linux:: # # * ~/.config/ # $XDG_CONFIG_HOME # `--* rash/ # base_path # |--* daemon.pid # PID of daemon process # |--* daemon.log # Log file for daemon # `--* data/ # data_path # |--* db.sqlite # db_path ("indexed" record) # `--* record/ # record_path ("raw" record) # |--* command/ # command log # `--* init/ # initialization log # # In Mac OS and Windows, :attr:`base_path` may be different but # structure in the directory is the same. # # """ # # def __init__(self, base_path=None): # self.base_path = base_path or get_config_directory('RASH') # """ # Root directory for any RASH related data files (``~/.config/rash``). # """ # # self.config_path = os.path.join(self.base_path, 'config.py') # """ # File to store user configuration (``~/.config/rash/config.py``). # """ # # self.data_path = os.path.join(self.base_path, 'data') # """ # Directory to store data collected by RASH (``~/.config/rash/data``). # """ # # self.record_path = os.path.join(self.data_path, 'record') # """ # Shell history is stored in this directory at the first stage. # """ # # self.db_path = os.path.join(self.data_path, 'db.sqlite') # """ # Shell history is stored in the DB at this path. # """ # # self.daemon_pid_path = os.path.join(self.base_path, 'daemon.pid') # """ # A file to store daemon PID (``~/.config/rash/daemon.pid``). # """ # # self.daemon_log_path = os.path.join(self.base_path, 'daemon.log') # """ # Daemon log file (``~/.config/rash/daemon.log``). # """ # # self.daemon_log_level = 'INFO' # FIXME: make this configurable # """ # Daemon log level. # """ # # mkdirp(self.record_path) # # def get_config(self): # """ # Load user configuration or return default when not found. # # :rtype: :class:`Configuration` # # """ # if not self._config: # namespace = {} # if os.path.exists(self.config_path): # execfile(self.config_path, namespace) # self._config = namespace.get('config') or Configuration() # return self._config # _config = None # # Path: rash/tests/utils.py # class BaseTestCase(unittest.TestCase): # # if not hasattr(unittest.TestCase, 'assertIn'): # def assertIn(self, member, container): # self.assertTrue(member in container) # # if not hasattr(unittest.TestCase, 'assertNotIn'): # def assertNotIn(self, member, container): # self.assertTrue(member not in container) # # if not hasattr(unittest.TestCase, 'assertIsInstance'): # def assertIsInstance(self, obj, cls, msg=None): # self.assertTrue(isinstance(obj, cls), msg) # # if not hasattr(unittest.TestCase, 'assertSetEqual'): # def assertSetEqual(self, set1, set2, msg=None): # self.assertEqual(set1, set2, msg) # # def skipIf(condition, reason): # def decorator(func): # @functools.wraps(func) # def wrapper(*args, **kwds): # if condition: # print("Skipping {0} because:".format(func.__name__)) # print(reason) # else: # return func(*args, **kwds) # return wrapper # return decorator . Output only the next line.
self.cfstore = ConfigStore(self.conf_base_path)
Given the following code snippet before the placeholder: <|code_start|> try: if os.path.exists(self.cfstore.daemon_pid_path): with open(self.cfstore.daemon_pid_path) as f: pid = f.read().strip() print("Daemon (PID={0}) may be left alive. Killing it..." .format(pid)) subprocess.call(['kill', pid]) except Exception as e: print("Got error while trying to kill daemon: {0}" .format(e)) try: shutil.rmtree(self.home_dir) except OSError: print("Failed to remove self.home_dir={0}. " "Can be timing issue. Trying again..." .format(self.home_dir)) time.sleep(0.1) shutil.rmtree(self.home_dir) def popen(self, *args, **kwds): if 'env' in kwds: raise RuntimeError('Do not use env!') if 'cwd' in kwds: raise RuntimeError('Do not use cwd!') kwds['env'] = self.environ kwds['cwd'] = self.home_dir return subprocess.Popen(*args, **kwds) <|code_end|> , predict the next line using imports from the current file: import os import sys import subprocess import unittest import tempfile import shutil import textwrap import json import time from ..utils.py3compat import PY3 from ..config import ConfigStore from ..tests.utils import BaseTestCase, skipIf from ..record import get_environ and context including class names, function names, and sometimes code from other files: # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # # Path: rash/config.py # class ConfigStore(object): # # """ # Configuration and data file store. # # RASH stores data in the following directory in Linux:: # # * ~/.config/ # $XDG_CONFIG_HOME # `--* rash/ # base_path # |--* daemon.pid # PID of daemon process # |--* daemon.log # Log file for daemon # `--* data/ # data_path # |--* db.sqlite # db_path ("indexed" record) # `--* record/ # record_path ("raw" record) # |--* command/ # command log # `--* init/ # initialization log # # In Mac OS and Windows, :attr:`base_path` may be different but # structure in the directory is the same. # # """ # # def __init__(self, base_path=None): # self.base_path = base_path or get_config_directory('RASH') # """ # Root directory for any RASH related data files (``~/.config/rash``). # """ # # self.config_path = os.path.join(self.base_path, 'config.py') # """ # File to store user configuration (``~/.config/rash/config.py``). # """ # # self.data_path = os.path.join(self.base_path, 'data') # """ # Directory to store data collected by RASH (``~/.config/rash/data``). # """ # # self.record_path = os.path.join(self.data_path, 'record') # """ # Shell history is stored in this directory at the first stage. # """ # # self.db_path = os.path.join(self.data_path, 'db.sqlite') # """ # Shell history is stored in the DB at this path. # """ # # self.daemon_pid_path = os.path.join(self.base_path, 'daemon.pid') # """ # A file to store daemon PID (``~/.config/rash/daemon.pid``). # """ # # self.daemon_log_path = os.path.join(self.base_path, 'daemon.log') # """ # Daemon log file (``~/.config/rash/daemon.log``). # """ # # self.daemon_log_level = 'INFO' # FIXME: make this configurable # """ # Daemon log level. # """ # # mkdirp(self.record_path) # # def get_config(self): # """ # Load user configuration or return default when not found. # # :rtype: :class:`Configuration` # # """ # if not self._config: # namespace = {} # if os.path.exists(self.config_path): # execfile(self.config_path, namespace) # self._config = namespace.get('config') or Configuration() # return self._config # _config = None # # Path: rash/tests/utils.py # class BaseTestCase(unittest.TestCase): # # if not hasattr(unittest.TestCase, 'assertIn'): # def assertIn(self, member, container): # self.assertTrue(member in container) # # if not hasattr(unittest.TestCase, 'assertNotIn'): # def assertNotIn(self, member, container): # self.assertTrue(member not in container) # # if not hasattr(unittest.TestCase, 'assertIsInstance'): # def assertIsInstance(self, obj, cls, msg=None): # self.assertTrue(isinstance(obj, cls), msg) # # if not hasattr(unittest.TestCase, 'assertSetEqual'): # def assertSetEqual(self, set1, set2, msg=None): # self.assertEqual(set1, set2, msg) # # def skipIf(condition, reason): # def decorator(func): # @functools.wraps(func) # def wrapper(*args, **kwds): # if condition: # print("Skipping {0} because:".format(func.__name__)) # print(reason) # else: # return func(*args, **kwds) # return wrapper # return decorator . Output only the next line.
class TestIsolation(FunctionalTestMixIn, BaseTestCase):
Predict the next line for this snippet: <|code_start|> self.assertEqual(len(records['exit']), 1) self.assertEqual(len(records['command']), 1) command_data = [d['data'] for d in records['command']] self.assertEqual(command_data[0]['pipestatus'], [1, 0]) test_pipe_status_script = None """Set this to a shell script for :meth:`test_pipe_status`.""" def test_non_existing_directory(self): main_script = """ _rash-precmd mkdir non_existing_directory _rash-precmd cd non_existing_directory _rash-precmd rmdir ../non_existing_directory _rash-precmd : _rash-precmd cd .. """ script = self.get_script(main_script) (stdout, stderr) = self.run_shell(script) self.assertNotIn('Traceback', stderr) <|code_end|> with the help of current file imports: import os import sys import subprocess import unittest import tempfile import shutil import textwrap import json import time from ..utils.py3compat import PY3 from ..config import ConfigStore from ..tests.utils import BaseTestCase, skipIf from ..record import get_environ and context from other files: # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # # Path: rash/config.py # class ConfigStore(object): # # """ # Configuration and data file store. # # RASH stores data in the following directory in Linux:: # # * ~/.config/ # $XDG_CONFIG_HOME # `--* rash/ # base_path # |--* daemon.pid # PID of daemon process # |--* daemon.log # Log file for daemon # `--* data/ # data_path # |--* db.sqlite # db_path ("indexed" record) # `--* record/ # record_path ("raw" record) # |--* command/ # command log # `--* init/ # initialization log # # In Mac OS and Windows, :attr:`base_path` may be different but # structure in the directory is the same. # # """ # # def __init__(self, base_path=None): # self.base_path = base_path or get_config_directory('RASH') # """ # Root directory for any RASH related data files (``~/.config/rash``). # """ # # self.config_path = os.path.join(self.base_path, 'config.py') # """ # File to store user configuration (``~/.config/rash/config.py``). # """ # # self.data_path = os.path.join(self.base_path, 'data') # """ # Directory to store data collected by RASH (``~/.config/rash/data``). # """ # # self.record_path = os.path.join(self.data_path, 'record') # """ # Shell history is stored in this directory at the first stage. # """ # # self.db_path = os.path.join(self.data_path, 'db.sqlite') # """ # Shell history is stored in the DB at this path. # """ # # self.daemon_pid_path = os.path.join(self.base_path, 'daemon.pid') # """ # A file to store daemon PID (``~/.config/rash/daemon.pid``). # """ # # self.daemon_log_path = os.path.join(self.base_path, 'daemon.log') # """ # Daemon log file (``~/.config/rash/daemon.log``). # """ # # self.daemon_log_level = 'INFO' # FIXME: make this configurable # """ # Daemon log level. # """ # # mkdirp(self.record_path) # # def get_config(self): # """ # Load user configuration or return default when not found. # # :rtype: :class:`Configuration` # # """ # if not self._config: # namespace = {} # if os.path.exists(self.config_path): # execfile(self.config_path, namespace) # self._config = namespace.get('config') or Configuration() # return self._config # _config = None # # Path: rash/tests/utils.py # class BaseTestCase(unittest.TestCase): # # if not hasattr(unittest.TestCase, 'assertIn'): # def assertIn(self, member, container): # self.assertTrue(member in container) # # if not hasattr(unittest.TestCase, 'assertNotIn'): # def assertNotIn(self, member, container): # self.assertTrue(member not in container) # # if not hasattr(unittest.TestCase, 'assertIsInstance'): # def assertIsInstance(self, obj, cls, msg=None): # self.assertTrue(isinstance(obj, cls), msg) # # if not hasattr(unittest.TestCase, 'assertSetEqual'): # def assertSetEqual(self, set1, set2, msg=None): # self.assertEqual(set1, set2, msg) # # def skipIf(condition, reason): # def decorator(func): # @functools.wraps(func) # def wrapper(*args, **kwds): # if condition: # print("Skipping {0} because:".format(func.__name__)) # print(reason) # else: # return func(*args, **kwds) # return wrapper # return decorator , which may contain function names, class names, or code. Output only the next line.
@skipIf(PY3, "watchdog does not support Python 3")
Given the code snippet: <|code_start|> def wrapper(*args, **kwds): if condition: print("Skipping {0} because:".format(func.__name__)) print(reason) else: return func(*args, **kwds) return wrapper return decorator @contextmanager def monkeypatch(obj, name, attr): """ Context manager to replace attribute named `name` in `obj` with `attr`. """ orig = getattr(obj, name) setattr(obj, name, attr) yield setattr(obj, name, orig) def zip_dict(dictionary, fillvalue=None): """ Zip values in `dictionary` and yield dictionaries with same keys. >>> list(zip_dict({'a': [1, 2, 3], 'b': [4, 5]})) [{'a': 1, 'b': 4}, {'a': 2, 'b': 5}, {'a': 3, 'b': None}] """ (keys, lists) = zip(*dictionary.items()) <|code_end|> , generate the next line using the imports in this file: import unittest import functools from contextlib import contextmanager from ..utils.py3compat import zip_longest and context (functions, classes, or occasionally code) from other files: # Path: rash/utils/py3compat.py # PY3 = (sys.version_info[0] >= 3) # def nested(*managers): . Output only the next line.
for values in zip_longest(*lists, fillvalue=fillvalue):
Based on the snippet: <|code_start|># (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_cpu class GenericCpu(Cpu): def __init__(self, cpu_factory, registers): for group, register_list in registers.iteritems(): registers[group] = [Register(x) for x in register_list] super(GenericCpu, self).__init__(cpu_factory, registers) @classmethod def architecture(cls): <|code_end|> , predict the immediate next line with the help of imports: from ...framework.platform import Architecture from ...framework.platform import Cpu from ...framework.platform import Register from ...framework.platform import register_cpu and context (classes, functions, sometimes code) from other files: # Path: voidwalker/framework/platform/cpu.py # class Register(object): # class StaticRegister(type(register), object): # class Cpu(object): # class CpuFactory(object): # class CpuRepository(object): # def __init__(self, name): # def name(self): # def size(self): # def value(self): # def str(self): # def create_static_register(register): # def __init__(self, name): # def size(self): # def value(self): # def __init__(self, cpu_factory, registers): # def architecture(cls): # def register(self, name): # def registers(self): # def stack_pointer(self): # def program_counter(self): # def create_cpu(self, architecture): # def create_register(self, cpu, register): # def __init__(self, cpu_factory): # def get_cpu(self, architecture): # def register_cpu(cls): # # Path: voidwalker/framework/platform/cpu.py # class Cpu(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu_factory, registers): # self._registers = OrderedDict() # for group, register_list in registers.iteritems(): # registers = OrderedDict([(x.name(), # cpu_factory.create_register(self, x)) # for x in register_list]) # # self._registers[group] = registers # # @classmethod # @abc.abstractmethod # def architecture(cls): # raise NotImplementedError # # def register(self, name): # for register_dict in self._registers.itervalues(): # if name in register_dict: # return register_dict[name] # # return None # # def registers(self): # return self._registers.iteritems() # # @abc.abstractmethod # def stack_pointer(self): # raise NotImplementedError # # @abc.abstractmethod # def program_counter(self): # raise NotImplementedError # # Path: voidwalker/framework/platform/cpu.py # class Register(object): # _register_fmt = {16: '0x%032lX', # 10: '0x%020lX', # 8: '0x%016lX', # 4: '0x%08lX', # 2: '0x%04lX', # 1: '0x%02lX'} # # def __init__(self, name): # self._name = name # # def name(self): # return self._name # # def size(self): # raise NotImplementedError # # def value(self): # raise NotImplementedError # # def str(self): # if self.value() is not None: # return self._register_fmt[self.size()] % self.value() # chars_per_byte = 2 # return ''.join(['-' * (self.size() * chars_per_byte)]) # # Path: voidwalker/framework/platform/cpu.py # def register_cpu(cls): # _cpu_map[cls.architecture()] = cls # return cls . Output only the next line.
return Architecture.Generic
Predict the next line for this snippet: <|code_start|># (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_cpu class GenericCpu(Cpu): def __init__(self, cpu_factory, registers): for group, register_list in registers.iteritems(): <|code_end|> with the help of current file imports: from ...framework.platform import Architecture from ...framework.platform import Cpu from ...framework.platform import Register from ...framework.platform import register_cpu and context from other files: # Path: voidwalker/framework/platform/cpu.py # class Register(object): # class StaticRegister(type(register), object): # class Cpu(object): # class CpuFactory(object): # class CpuRepository(object): # def __init__(self, name): # def name(self): # def size(self): # def value(self): # def str(self): # def create_static_register(register): # def __init__(self, name): # def size(self): # def value(self): # def __init__(self, cpu_factory, registers): # def architecture(cls): # def register(self, name): # def registers(self): # def stack_pointer(self): # def program_counter(self): # def create_cpu(self, architecture): # def create_register(self, cpu, register): # def __init__(self, cpu_factory): # def get_cpu(self, architecture): # def register_cpu(cls): # # Path: voidwalker/framework/platform/cpu.py # class Cpu(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu_factory, registers): # self._registers = OrderedDict() # for group, register_list in registers.iteritems(): # registers = OrderedDict([(x.name(), # cpu_factory.create_register(self, x)) # for x in register_list]) # # self._registers[group] = registers # # @classmethod # @abc.abstractmethod # def architecture(cls): # raise NotImplementedError # # def register(self, name): # for register_dict in self._registers.itervalues(): # if name in register_dict: # return register_dict[name] # # return None # # def registers(self): # return self._registers.iteritems() # # @abc.abstractmethod # def stack_pointer(self): # raise NotImplementedError # # @abc.abstractmethod # def program_counter(self): # raise NotImplementedError # # Path: voidwalker/framework/platform/cpu.py # class Register(object): # _register_fmt = {16: '0x%032lX', # 10: '0x%020lX', # 8: '0x%016lX', # 4: '0x%08lX', # 2: '0x%04lX', # 1: '0x%02lX'} # # def __init__(self, name): # self._name = name # # def name(self): # return self._name # # def size(self): # raise NotImplementedError # # def value(self): # raise NotImplementedError # # def str(self): # if self.value() is not None: # return self._register_fmt[self.size()] % self.value() # chars_per_byte = 2 # return ''.join(['-' * (self.size() * chars_per_byte)]) # # Path: voidwalker/framework/platform/cpu.py # def register_cpu(cls): # _cpu_map[cls.architecture()] = cls # return cls , which may contain function names, class names, or code. Output only the next line.
registers[group] = [Register(x) for x in register_list]
Using the snippet: <|code_start|># # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class TestInferior(Inferior): def __init__(self, cpu, inferior_id): super(TestInferior, self).__init__(cpu) self._id = inferior_id def id(self): return self._id def disassemble(self, address, length): return None def read_memory(self, address, length): return None def write_memory(self, buf, address): return None <|code_end|> , determine the next line of code. You have imports: from ...framework.target import Inferior from ...framework.target import InferiorFactory from ...framework.target import Thread from ...framework.target import ThreadFactory from .platform import TestCpu from .platform import TestCpuFactory and context (class names, function names, or code) available: # Path: voidwalker/framework/target/inferior.py # class Inferior(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu): # self._cpu = cpu # self._threads = {} # # @abc.abstractmethod # def id(self): # raise NotImplementedError # # def cpu(self): # return self._cpu # # def has_thread(self, thread_id): # return thread_id in self._threads # # def add_thread(self, thread): # self._threads[thread.id()] = thread # # def thread(self, thread_id): # assert self.has_thread(thread_id) # return self._threads[thread_id] # # @abc.abstractmethod # def disassemble(self, address, length): # raise NotImplementedError # # @abc.abstractmethod # def read_memory(self, address, length): # raise NotImplementedError # # @abc.abstractmethod # def write_memory(self, buf, address): # raise NotImplementedError # # Path: voidwalker/framework/target/inferior.py # class InferiorFactory(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu_factory): # self._cpu_factory = cpu_factory # # @abc.abstractmethod # def create_inferior(self, inferior_id): # raise NotImplementedError # # Path: voidwalker/framework/target/thread.py # class Thread(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, inferior): # self._inferior = inferior # self._contexts = deque() # # def get_inferior(self): # return self._inferior # # def contexts(self): # return self._contexts # # @abc.abstractmethod # def name(self): # raise NotImplementedError # # @abc.abstractmethod # def id(self): # raise NotImplementedError # # @abc.abstractmethod # def is_valid(self): # raise NotImplementedError # # Path: voidwalker/framework/target/thread.py # class ThreadFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create_thread(self, inferior, thread_id): # raise NotImplementedError # # Path: voidwalker/backends/test/platform.py # class TestCpu(Cpu): # register_dict = OrderedDict([('gp', ('r0 r1').split()), # ('sp', ('pc sp flags').split())]) # # def __init__(self, cpu_factory): # registers = OrderedDict() # for group, register_list in self.register_dict.items(): # registers[group] = [Register(x) for x in register_list] # super(TestCpu, self).__init__(cpu_factory, registers) # # @classmethod # def architecture(cls): # return Architecture.Test # # def stack_pointer(self): # return self.register('sp') # # def program_counter(self): # return self.register('pc') # # Path: voidwalker/backends/test/platform.py # class TestCpuFactory(CpuFactory): # def __init__(self): # self._registers = None # # def create_cpu(self, architecture): # return TestCpu(self) # # def create_register(self, cpu, register): # class TestRegister(type(register), object): # def __init__(self, name): # super(TestRegister, self).__init__(name) # self._size = 8 # self._value = 0 # # def size(self): # return self._size # # def value(self): # return self._value # # return TestRegister(register.name()) . Output only the next line.
class TestInferiorFactory(InferiorFactory):
Next line prediction: <|code_start|> def __init__(self, cpu, inferior_id): super(TestInferior, self).__init__(cpu) self._id = inferior_id def id(self): return self._id def disassemble(self, address, length): return None def read_memory(self, address, length): return None def write_memory(self, buf, address): return None class TestInferiorFactory(InferiorFactory): def __init__(self): super(TestInferiorFactory, self).__init__(TestCpuFactory()) def create_inferior(self, cpu, inferior_id): return TestInferior(cpu, inferior_id) def create_thread(self, inferior, thread_id): thread = TestThread(inferior.id(), thread_id) inferior.add_thread(thread) return thread <|code_end|> . Use current file imports: (from ...framework.target import Inferior from ...framework.target import InferiorFactory from ...framework.target import Thread from ...framework.target import ThreadFactory from .platform import TestCpu from .platform import TestCpuFactory) and context including class names, function names, or small code snippets from other files: # Path: voidwalker/framework/target/inferior.py # class Inferior(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu): # self._cpu = cpu # self._threads = {} # # @abc.abstractmethod # def id(self): # raise NotImplementedError # # def cpu(self): # return self._cpu # # def has_thread(self, thread_id): # return thread_id in self._threads # # def add_thread(self, thread): # self._threads[thread.id()] = thread # # def thread(self, thread_id): # assert self.has_thread(thread_id) # return self._threads[thread_id] # # @abc.abstractmethod # def disassemble(self, address, length): # raise NotImplementedError # # @abc.abstractmethod # def read_memory(self, address, length): # raise NotImplementedError # # @abc.abstractmethod # def write_memory(self, buf, address): # raise NotImplementedError # # Path: voidwalker/framework/target/inferior.py # class InferiorFactory(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu_factory): # self._cpu_factory = cpu_factory # # @abc.abstractmethod # def create_inferior(self, inferior_id): # raise NotImplementedError # # Path: voidwalker/framework/target/thread.py # class Thread(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, inferior): # self._inferior = inferior # self._contexts = deque() # # def get_inferior(self): # return self._inferior # # def contexts(self): # return self._contexts # # @abc.abstractmethod # def name(self): # raise NotImplementedError # # @abc.abstractmethod # def id(self): # raise NotImplementedError # # @abc.abstractmethod # def is_valid(self): # raise NotImplementedError # # Path: voidwalker/framework/target/thread.py # class ThreadFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create_thread(self, inferior, thread_id): # raise NotImplementedError # # Path: voidwalker/backends/test/platform.py # class TestCpu(Cpu): # register_dict = OrderedDict([('gp', ('r0 r1').split()), # ('sp', ('pc sp flags').split())]) # # def __init__(self, cpu_factory): # registers = OrderedDict() # for group, register_list in self.register_dict.items(): # registers[group] = [Register(x) for x in register_list] # super(TestCpu, self).__init__(cpu_factory, registers) # # @classmethod # def architecture(cls): # return Architecture.Test # # def stack_pointer(self): # return self.register('sp') # # def program_counter(self): # return self.register('pc') # # Path: voidwalker/backends/test/platform.py # class TestCpuFactory(CpuFactory): # def __init__(self): # self._registers = None # # def create_cpu(self, architecture): # return TestCpu(self) # # def create_register(self, cpu, register): # class TestRegister(type(register), object): # def __init__(self, name): # super(TestRegister, self).__init__(name) # self._size = 8 # self._value = 0 # # def size(self): # return self._size # # def value(self): # return self._value # # return TestRegister(register.name()) . Output only the next line.
class TestThread(Thread):
Here is a snippet: <|code_start|> class TestInferiorFactory(InferiorFactory): def __init__(self): super(TestInferiorFactory, self).__init__(TestCpuFactory()) def create_inferior(self, cpu, inferior_id): return TestInferior(cpu, inferior_id) def create_thread(self, inferior, thread_id): thread = TestThread(inferior.id(), thread_id) inferior.add_thread(thread) return thread class TestThread(Thread): def __init__(self, inferior, thread_id): super(TestThread, self).__init__(inferior) self._thread_id = thread_id def name(self): return ('thread %d' % self._thread_id) def id(self): return self._thread_id def is_valid(self): return True <|code_end|> . Write the next line using the current file imports: from ...framework.target import Inferior from ...framework.target import InferiorFactory from ...framework.target import Thread from ...framework.target import ThreadFactory from .platform import TestCpu from .platform import TestCpuFactory and context from other files: # Path: voidwalker/framework/target/inferior.py # class Inferior(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu): # self._cpu = cpu # self._threads = {} # # @abc.abstractmethod # def id(self): # raise NotImplementedError # # def cpu(self): # return self._cpu # # def has_thread(self, thread_id): # return thread_id in self._threads # # def add_thread(self, thread): # self._threads[thread.id()] = thread # # def thread(self, thread_id): # assert self.has_thread(thread_id) # return self._threads[thread_id] # # @abc.abstractmethod # def disassemble(self, address, length): # raise NotImplementedError # # @abc.abstractmethod # def read_memory(self, address, length): # raise NotImplementedError # # @abc.abstractmethod # def write_memory(self, buf, address): # raise NotImplementedError # # Path: voidwalker/framework/target/inferior.py # class InferiorFactory(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu_factory): # self._cpu_factory = cpu_factory # # @abc.abstractmethod # def create_inferior(self, inferior_id): # raise NotImplementedError # # Path: voidwalker/framework/target/thread.py # class Thread(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, inferior): # self._inferior = inferior # self._contexts = deque() # # def get_inferior(self): # return self._inferior # # def contexts(self): # return self._contexts # # @abc.abstractmethod # def name(self): # raise NotImplementedError # # @abc.abstractmethod # def id(self): # raise NotImplementedError # # @abc.abstractmethod # def is_valid(self): # raise NotImplementedError # # Path: voidwalker/framework/target/thread.py # class ThreadFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create_thread(self, inferior, thread_id): # raise NotImplementedError # # Path: voidwalker/backends/test/platform.py # class TestCpu(Cpu): # register_dict = OrderedDict([('gp', ('r0 r1').split()), # ('sp', ('pc sp flags').split())]) # # def __init__(self, cpu_factory): # registers = OrderedDict() # for group, register_list in self.register_dict.items(): # registers[group] = [Register(x) for x in register_list] # super(TestCpu, self).__init__(cpu_factory, registers) # # @classmethod # def architecture(cls): # return Architecture.Test # # def stack_pointer(self): # return self.register('sp') # # def program_counter(self): # return self.register('pc') # # Path: voidwalker/backends/test/platform.py # class TestCpuFactory(CpuFactory): # def __init__(self): # self._registers = None # # def create_cpu(self, architecture): # return TestCpu(self) # # def create_register(self, cpu, register): # class TestRegister(type(register), object): # def __init__(self, name): # super(TestRegister, self).__init__(name) # self._size = 8 # self._value = 0 # # def size(self): # return self._size # # def value(self): # return self._value # # return TestRegister(register.name()) , which may include functions, classes, or code. Output only the next line.
class TestThreadFactory(ThreadFactory):
Using the snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class TestInferior(Inferior): def __init__(self, cpu, inferior_id): super(TestInferior, self).__init__(cpu) self._id = inferior_id def id(self): return self._id def disassemble(self, address, length): return None def read_memory(self, address, length): return None def write_memory(self, buf, address): return None class TestInferiorFactory(InferiorFactory): def __init__(self): <|code_end|> , determine the next line of code. You have imports: from ...framework.target import Inferior from ...framework.target import InferiorFactory from ...framework.target import Thread from ...framework.target import ThreadFactory from .platform import TestCpu from .platform import TestCpuFactory and context (class names, function names, or code) available: # Path: voidwalker/framework/target/inferior.py # class Inferior(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu): # self._cpu = cpu # self._threads = {} # # @abc.abstractmethod # def id(self): # raise NotImplementedError # # def cpu(self): # return self._cpu # # def has_thread(self, thread_id): # return thread_id in self._threads # # def add_thread(self, thread): # self._threads[thread.id()] = thread # # def thread(self, thread_id): # assert self.has_thread(thread_id) # return self._threads[thread_id] # # @abc.abstractmethod # def disassemble(self, address, length): # raise NotImplementedError # # @abc.abstractmethod # def read_memory(self, address, length): # raise NotImplementedError # # @abc.abstractmethod # def write_memory(self, buf, address): # raise NotImplementedError # # Path: voidwalker/framework/target/inferior.py # class InferiorFactory(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, cpu_factory): # self._cpu_factory = cpu_factory # # @abc.abstractmethod # def create_inferior(self, inferior_id): # raise NotImplementedError # # Path: voidwalker/framework/target/thread.py # class Thread(object): # __metaclass__ = abc.ABCMeta # # def __init__(self, inferior): # self._inferior = inferior # self._contexts = deque() # # def get_inferior(self): # return self._inferior # # def contexts(self): # return self._contexts # # @abc.abstractmethod # def name(self): # raise NotImplementedError # # @abc.abstractmethod # def id(self): # raise NotImplementedError # # @abc.abstractmethod # def is_valid(self): # raise NotImplementedError # # Path: voidwalker/framework/target/thread.py # class ThreadFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create_thread(self, inferior, thread_id): # raise NotImplementedError # # Path: voidwalker/backends/test/platform.py # class TestCpu(Cpu): # register_dict = OrderedDict([('gp', ('r0 r1').split()), # ('sp', ('pc sp flags').split())]) # # def __init__(self, cpu_factory): # registers = OrderedDict() # for group, register_list in self.register_dict.items(): # registers[group] = [Register(x) for x in register_list] # super(TestCpu, self).__init__(cpu_factory, registers) # # @classmethod # def architecture(cls): # return Architecture.Test # # def stack_pointer(self): # return self.register('sp') # # def program_counter(self): # return self.register('pc') # # Path: voidwalker/backends/test/platform.py # class TestCpuFactory(CpuFactory): # def __init__(self): # self._registers = None # # def create_cpu(self, architecture): # return TestCpu(self) # # def create_register(self, cpu, register): # class TestRegister(type(register), object): # def __init__(self, name): # super(TestRegister, self).__init__(name) # self._size = 8 # self._value = 0 # # def size(self): # return self._size # # def value(self): # return self._value # # return TestRegister(register.name()) . Output only the next line.
super(TestInferiorFactory, self).__init__(TestCpuFactory())
Continue the code snippet: <|code_start|> return TestDataCommand() if issubclass(command_type, Command): class TestCommand(command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) def invoke(self, argument, _): command_type.execute(self, terminal, argument) return TestCommand() else: raise TypeError('Command type %s unknown!' % str(command_type)) class TestParameterFactory(ParameterFactory, object): def create(self, parameter_type): if issubclass(parameter_type, EnumParameter): class TestParameterEnum(parameter_type): def __init__(self): parameter_type.__init__(self) self.value = parameter_type.default_value(self) return TestParameterEnum() <|code_end|> . Use current file imports: from ...framework.interface import BooleanParameter from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import EnumParameter from ...framework.interface import Parameter from ...framework.interface import ParameterFactory from .target import TestInferior from .target import TestThread and context (classes, functions, or code) from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class ParameterFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, parameter_type): # raise NotImplementedError # # Path: voidwalker/backends/test/target.py # class TestInferior(Inferior): # def __init__(self, cpu, inferior_id): # super(TestInferior, self).__init__(cpu) # self._id = inferior_id # # def id(self): # return self._id # # def disassemble(self, address, length): # return None # # def read_memory(self, address, length): # return None # # def write_memory(self, buf, address): # return None # # Path: voidwalker/backends/test/target.py # class TestThread(Thread): # def __init__(self, inferior, thread_id): # super(TestThread, self).__init__(inferior) # self._thread_id = thread_id # # def name(self): # return ('thread %d' % self._thread_id) # # def id(self): # return self._thread_id # # def is_valid(self): # return True . Output only the next line.
elif issubclass(parameter_type, BooleanParameter):
Continue the code snippet: <|code_start|># (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class TestCommandFactory(CommandFactory, object): def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): if issubclass(command_type, DataCommand): class TestDataCommand(command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) def invoke(self, argument, _): inferior = TestInferior() thread = TestThread(inferior.id(), 0) command_type.execute(self, terminal, thread, argument) return TestDataCommand() <|code_end|> . Use current file imports: from ...framework.interface import BooleanParameter from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import EnumParameter from ...framework.interface import Parameter from ...framework.interface import ParameterFactory from .target import TestInferior from .target import TestThread and context (classes, functions, or code) from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class ParameterFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, parameter_type): # raise NotImplementedError # # Path: voidwalker/backends/test/target.py # class TestInferior(Inferior): # def __init__(self, cpu, inferior_id): # super(TestInferior, self).__init__(cpu) # self._id = inferior_id # # def id(self): # return self._id # # def disassemble(self, address, length): # return None # # def read_memory(self, address, length): # return None # # def write_memory(self, buf, address): # return None # # Path: voidwalker/backends/test/target.py # class TestThread(Thread): # def __init__(self, inferior, thread_id): # super(TestThread, self).__init__(inferior) # self._thread_id = thread_id # # def name(self): # return ('thread %d' % self._thread_id) # # def id(self): # return self._thread_id # # def is_valid(self): # return True . Output only the next line.
if issubclass(command_type, Command):
Predict the next line for this snippet: <|code_start|># (void)walker unit test backend # Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class TestCommandFactory(CommandFactory, object): def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): <|code_end|> with the help of current file imports: from ...framework.interface import BooleanParameter from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import EnumParameter from ...framework.interface import Parameter from ...framework.interface import ParameterFactory from .target import TestInferior from .target import TestThread and context from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class ParameterFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, parameter_type): # raise NotImplementedError # # Path: voidwalker/backends/test/target.py # class TestInferior(Inferior): # def __init__(self, cpu, inferior_id): # super(TestInferior, self).__init__(cpu) # self._id = inferior_id # # def id(self): # return self._id # # def disassemble(self, address, length): # return None # # def read_memory(self, address, length): # return None # # def write_memory(self, buf, address): # return None # # Path: voidwalker/backends/test/target.py # class TestThread(Thread): # def __init__(self, inferior, thread_id): # super(TestThread, self).__init__(inferior) # self._thread_id = thread_id # # def name(self): # return ('thread %d' % self._thread_id) # # def id(self): # return self._thread_id # # def is_valid(self): # return True , which may contain function names, class names, or code. Output only the next line.
if issubclass(command_type, DataCommand):
Continue the code snippet: <|code_start|> def __init__(self): command_type.__init__(self) def invoke(self, argument, _): inferior = TestInferior() thread = TestThread(inferior.id(), 0) command_type.execute(self, terminal, thread, argument) return TestDataCommand() if issubclass(command_type, Command): class TestCommand(command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) def invoke(self, argument, _): command_type.execute(self, terminal, argument) return TestCommand() else: raise TypeError('Command type %s unknown!' % str(command_type)) class TestParameterFactory(ParameterFactory, object): def create(self, parameter_type): <|code_end|> . Use current file imports: from ...framework.interface import BooleanParameter from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import EnumParameter from ...framework.interface import Parameter from ...framework.interface import ParameterFactory from .target import TestInferior from .target import TestThread and context (classes, functions, or code) from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class ParameterFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, parameter_type): # raise NotImplementedError # # Path: voidwalker/backends/test/target.py # class TestInferior(Inferior): # def __init__(self, cpu, inferior_id): # super(TestInferior, self).__init__(cpu) # self._id = inferior_id # # def id(self): # return self._id # # def disassemble(self, address, length): # return None # # def read_memory(self, address, length): # return None # # def write_memory(self, buf, address): # return None # # Path: voidwalker/backends/test/target.py # class TestThread(Thread): # def __init__(self, inferior, thread_id): # super(TestThread, self).__init__(inferior) # self._thread_id = thread_id # # def name(self): # return ('thread %d' % self._thread_id) # # def id(self): # return self._thread_id # # def is_valid(self): # return True . Output only the next line.
if issubclass(parameter_type, EnumParameter):
Given the following code snippet before the placeholder: <|code_start|> command_type.__init__(self) def invoke(self, argument, _): command_type.execute(self, terminal, argument) return TestCommand() else: raise TypeError('Command type %s unknown!' % str(command_type)) class TestParameterFactory(ParameterFactory, object): def create(self, parameter_type): if issubclass(parameter_type, EnumParameter): class TestParameterEnum(parameter_type): def __init__(self): parameter_type.__init__(self) self.value = parameter_type.default_value(self) return TestParameterEnum() elif issubclass(parameter_type, BooleanParameter): class TestParameterBoolean(parameter_type): def __init__(self): parameter_type.__init__(self) self.value = parameter_type.default_value(self) return TestParameterBoolean() <|code_end|> , predict the next line using imports from the current file: from ...framework.interface import BooleanParameter from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import EnumParameter from ...framework.interface import Parameter from ...framework.interface import ParameterFactory from .target import TestInferior from .target import TestThread and context including class names, function names, and sometimes code from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class ParameterFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, parameter_type): # raise NotImplementedError # # Path: voidwalker/backends/test/target.py # class TestInferior(Inferior): # def __init__(self, cpu, inferior_id): # super(TestInferior, self).__init__(cpu) # self._id = inferior_id # # def id(self): # return self._id # # def disassemble(self, address, length): # return None # # def read_memory(self, address, length): # return None # # def write_memory(self, buf, address): # return None # # Path: voidwalker/backends/test/target.py # class TestThread(Thread): # def __init__(self, inferior, thread_id): # super(TestThread, self).__init__(inferior) # self._thread_id = thread_id # # def name(self): # return ('thread %d' % self._thread_id) # # def id(self): # return self._thread_id # # def is_valid(self): # return True . Output only the next line.
elif issubclass(parameter_type, Parameter):
Given the code snippet: <|code_start|> class TestDataCommand(command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) def invoke(self, argument, _): inferior = TestInferior() thread = TestThread(inferior.id(), 0) command_type.execute(self, terminal, thread, argument) return TestDataCommand() if issubclass(command_type, Command): class TestCommand(command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) def invoke(self, argument, _): command_type.execute(self, terminal, argument) return TestCommand() else: raise TypeError('Command type %s unknown!' % str(command_type)) <|code_end|> , generate the next line using the imports in this file: from ...framework.interface import BooleanParameter from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import EnumParameter from ...framework.interface import Parameter from ...framework.interface import ParameterFactory from .target import TestInferior from .target import TestThread and context (functions, classes, or occasionally code) from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class ParameterFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, parameter_type): # raise NotImplementedError # # Path: voidwalker/backends/test/target.py # class TestInferior(Inferior): # def __init__(self, cpu, inferior_id): # super(TestInferior, self).__init__(cpu) # self._id = inferior_id # # def id(self): # return self._id # # def disassemble(self, address, length): # return None # # def read_memory(self, address, length): # return None # # def write_memory(self, buf, address): # return None # # Path: voidwalker/backends/test/target.py # class TestThread(Thread): # def __init__(self, inferior, thread_id): # super(TestThread, self).__init__(inferior) # self._thread_id = thread_id # # def name(self): # return ('thread %d' % self._thread_id) # # def id(self): # return self._thread_id # # def is_valid(self): # return True . Output only the next line.
class TestParameterFactory(ParameterFactory, object):
Next line prediction: <|code_start|># (void)walker unit test backend # Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class TestCommandFactory(CommandFactory, object): def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): if issubclass(command_type, DataCommand): class TestDataCommand(command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) def invoke(self, argument, _): <|code_end|> . Use current file imports: (from ...framework.interface import BooleanParameter from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import EnumParameter from ...framework.interface import Parameter from ...framework.interface import ParameterFactory from .target import TestInferior from .target import TestThread) and context including class names, function names, or small code snippets from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class ParameterFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, parameter_type): # raise NotImplementedError # # Path: voidwalker/backends/test/target.py # class TestInferior(Inferior): # def __init__(self, cpu, inferior_id): # super(TestInferior, self).__init__(cpu) # self._id = inferior_id # # def id(self): # return self._id # # def disassemble(self, address, length): # return None # # def read_memory(self, address, length): # return None # # def write_memory(self, buf, address): # return None # # Path: voidwalker/backends/test/target.py # class TestThread(Thread): # def __init__(self, inferior, thread_id): # super(TestThread, self).__init__(inferior) # self._thread_id = thread_id # # def name(self): # return ('thread %d' % self._thread_id) # # def id(self): # return self._thread_id # # def is_valid(self): # return True . Output only the next line.
inferior = TestInferior()
Here is a snippet: <|code_start|># Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class TestCommandFactory(CommandFactory, object): def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): if issubclass(command_type, DataCommand): class TestDataCommand(command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) def invoke(self, argument, _): inferior = TestInferior() <|code_end|> . Write the next line using the current file imports: from ...framework.interface import BooleanParameter from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import EnumParameter from ...framework.interface import Parameter from ...framework.interface import ParameterFactory from .target import TestInferior from .target import TestThread and context from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class ParameterFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, parameter_type): # raise NotImplementedError # # Path: voidwalker/backends/test/target.py # class TestInferior(Inferior): # def __init__(self, cpu, inferior_id): # super(TestInferior, self).__init__(cpu) # self._id = inferior_id # # def id(self): # return self._id # # def disassemble(self, address, length): # return None # # def read_memory(self, address, length): # return None # # def write_memory(self, buf, address): # return None # # Path: voidwalker/backends/test/target.py # class TestThread(Thread): # def __init__(self, inferior, thread_id): # super(TestThread, self).__init__(inferior) # self._thread_id = thread_id # # def name(self): # return ('thread %d' % self._thread_id) # # def id(self): # return self._thread_id # # def is_valid(self): # return True , which may include functions, classes, or code. Output only the next line.
thread = TestThread(inferior.id(), 0)
Next line prediction: <|code_start|> def __init__(self): super(HookParameter, self).__init__() def default_value(self): return None @staticmethod def name(): return '%s %s' % (VoidwalkerParameter.name(), 'hook') @register_parameter class ContextHookParameter(BooleanParameter): '''Dump context when relevant hooks are called''' DEFAULT_VALUE = True def __init__(self): super(ContextHookParameter, self).__init__() @staticmethod def name(): return '%s %s' % (HookParameter.name(), 'context') def default_value(self): return self.DEFAULT_VALUE @register_command <|code_end|> . Use current file imports: (import gdb from ...framework.interface.command import StackCommand from ...framework.interface.command import register_command from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import register_parameter from ...application.commands.context import ContextCommand from ...application.commands.voidwalker import VoidwalkerCommand from ...application.parameters.voidwalker import VoidwalkerParameter) and context including class names, function names, or small code snippets from other files: # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/commands/context.py # class ContextCommand(StackCommand): # '''Show the current context. # # If the current thread of the inferior is valid the context will be recorded and # dumped. The contents of the context can be controlled using the (void)walker # parameters''' # # @staticmethod # def name(): # return '%s %s' % (VoidwalkerCommand.name(), 'context') # # def __init__(self): # super(ContextCommand, self).__init__() # # def execute(self, config, terminal, thread, platform_factory, argument): # if not thread.is_valid(): # return # # context = platform_factory.create_context(config, thread) # previous_context = context # if len(thread.contexts()): # previous_context = thread.contexts()[-1] # # context_widget = ContextWidget(previous_context, context) # context_widget.draw(terminal, terminal.width()) # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
class VoidwalkerHookStop(StackCommand):
Given the following code snippet before the placeholder: <|code_start|> '''(void)walker hook parameters''' def __init__(self): super(HookParameter, self).__init__() def default_value(self): return None @staticmethod def name(): return '%s %s' % (VoidwalkerParameter.name(), 'hook') @register_parameter class ContextHookParameter(BooleanParameter): '''Dump context when relevant hooks are called''' DEFAULT_VALUE = True def __init__(self): super(ContextHookParameter, self).__init__() @staticmethod def name(): return '%s %s' % (HookParameter.name(), 'context') def default_value(self): return self.DEFAULT_VALUE <|code_end|> , predict the next line using imports from the current file: import gdb from ...framework.interface.command import StackCommand from ...framework.interface.command import register_command from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import register_parameter from ...application.commands.context import ContextCommand from ...application.commands.voidwalker import VoidwalkerCommand from ...application.parameters.voidwalker import VoidwalkerParameter and context including class names, function names, and sometimes code from other files: # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/commands/context.py # class ContextCommand(StackCommand): # '''Show the current context. # # If the current thread of the inferior is valid the context will be recorded and # dumped. The contents of the context can be controlled using the (void)walker # parameters''' # # @staticmethod # def name(): # return '%s %s' % (VoidwalkerCommand.name(), 'context') # # def __init__(self): # super(ContextCommand, self).__init__() # # def execute(self, config, terminal, thread, platform_factory, argument): # if not thread.is_valid(): # return # # context = platform_factory.create_context(config, thread) # previous_context = context # if len(thread.contexts()): # previous_context = thread.contexts()[-1] # # context_widget = ContextWidget(previous_context, context) # context_widget.draw(terminal, terminal.width()) # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
@register_command
Based on the snippet: <|code_start|># (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_parameter class HookParameter(PrefixParameter): '''(void)walker hook parameters''' def __init__(self): super(HookParameter, self).__init__() def default_value(self): return None @staticmethod def name(): return '%s %s' % (VoidwalkerParameter.name(), 'hook') @register_parameter <|code_end|> , predict the immediate next line with the help of imports: import gdb from ...framework.interface.command import StackCommand from ...framework.interface.command import register_command from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import register_parameter from ...application.commands.context import ContextCommand from ...application.commands.voidwalker import VoidwalkerCommand from ...application.parameters.voidwalker import VoidwalkerParameter and context (classes, functions, sometimes code) from other files: # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/commands/context.py # class ContextCommand(StackCommand): # '''Show the current context. # # If the current thread of the inferior is valid the context will be recorded and # dumped. The contents of the context can be controlled using the (void)walker # parameters''' # # @staticmethod # def name(): # return '%s %s' % (VoidwalkerCommand.name(), 'context') # # def __init__(self): # super(ContextCommand, self).__init__() # # def execute(self, config, terminal, thread, platform_factory, argument): # if not thread.is_valid(): # return # # context = platform_factory.create_context(config, thread) # previous_context = context # if len(thread.contexts()): # previous_context = thread.contexts()[-1] # # context_widget = ContextWidget(previous_context, context) # context_widget.draw(terminal, terminal.width()) # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
class ContextHookParameter(BooleanParameter):
Predict the next line after this snippet: <|code_start|> def name(): return '%s %s' % (HookParameter.name(), 'context') def default_value(self): return self.DEFAULT_VALUE @register_command class VoidwalkerHookStop(StackCommand): '''This command should be called from GDB hook-stop. To support all features of (void)walker this command must be called from GDB's hook-stop command. If you haven't defined hook-stop simply add the following to your ~/.gdbinit: define hook-stop voidwalker hook-stop end''' def __init__(self): super(VoidwalkerHookStop, self).__init__() self._terminal = None @staticmethod def name(): return '%s %s' % (VoidwalkerCommand.name(), 'hook-stop') def execute(self, config, *_): context_hook_name = ContextHookParameter.name() if config.parameter(context_hook_name).value(): <|code_end|> using the current file's imports: import gdb from ...framework.interface.command import StackCommand from ...framework.interface.command import register_command from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import register_parameter from ...application.commands.context import ContextCommand from ...application.commands.voidwalker import VoidwalkerCommand from ...application.parameters.voidwalker import VoidwalkerParameter and any relevant context from other files: # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/commands/context.py # class ContextCommand(StackCommand): # '''Show the current context. # # If the current thread of the inferior is valid the context will be recorded and # dumped. The contents of the context can be controlled using the (void)walker # parameters''' # # @staticmethod # def name(): # return '%s %s' % (VoidwalkerCommand.name(), 'context') # # def __init__(self): # super(ContextCommand, self).__init__() # # def execute(self, config, terminal, thread, platform_factory, argument): # if not thread.is_valid(): # return # # context = platform_factory.create_context(config, thread) # previous_context = context # if len(thread.contexts()): # previous_context = thread.contexts()[-1] # # context_widget = ContextWidget(previous_context, context) # context_widget.draw(terminal, terminal.width()) # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
gdb.execute(ContextCommand.name())
Continue the code snippet: <|code_start|> def __init__(self): super(ContextHookParameter, self).__init__() @staticmethod def name(): return '%s %s' % (HookParameter.name(), 'context') def default_value(self): return self.DEFAULT_VALUE @register_command class VoidwalkerHookStop(StackCommand): '''This command should be called from GDB hook-stop. To support all features of (void)walker this command must be called from GDB's hook-stop command. If you haven't defined hook-stop simply add the following to your ~/.gdbinit: define hook-stop voidwalker hook-stop end''' def __init__(self): super(VoidwalkerHookStop, self).__init__() self._terminal = None @staticmethod def name(): <|code_end|> . Use current file imports: import gdb from ...framework.interface.command import StackCommand from ...framework.interface.command import register_command from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import register_parameter from ...application.commands.context import ContextCommand from ...application.commands.voidwalker import VoidwalkerCommand from ...application.parameters.voidwalker import VoidwalkerParameter and context (classes, functions, or code) from other files: # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/commands/context.py # class ContextCommand(StackCommand): # '''Show the current context. # # If the current thread of the inferior is valid the context will be recorded and # dumped. The contents of the context can be controlled using the (void)walker # parameters''' # # @staticmethod # def name(): # return '%s %s' % (VoidwalkerCommand.name(), 'context') # # def __init__(self): # super(ContextCommand, self).__init__() # # def execute(self, config, terminal, thread, platform_factory, argument): # if not thread.is_valid(): # return # # context = platform_factory.create_context(config, thread) # previous_context = context # if len(thread.contexts()): # previous_context = thread.contexts()[-1] # # context_widget = ContextWidget(previous_context, context) # context_widget.draw(terminal, terminal.width()) # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
return '%s %s' % (VoidwalkerCommand.name(), 'hook-stop')
Given the code snippet: <|code_start|> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_parameter class HookParameter(PrefixParameter): '''(void)walker hook parameters''' def __init__(self): super(HookParameter, self).__init__() def default_value(self): return None @staticmethod def name(): <|code_end|> , generate the next line using the imports in this file: import gdb from ...framework.interface.command import StackCommand from ...framework.interface.command import register_command from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import register_parameter from ...application.commands.context import ContextCommand from ...application.commands.voidwalker import VoidwalkerCommand from ...application.parameters.voidwalker import VoidwalkerParameter and context (functions, classes, or occasionally code) from other files: # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/commands/context.py # class ContextCommand(StackCommand): # '''Show the current context. # # If the current thread of the inferior is valid the context will be recorded and # dumped. The contents of the context can be controlled using the (void)walker # parameters''' # # @staticmethod # def name(): # return '%s %s' % (VoidwalkerCommand.name(), 'context') # # def __init__(self): # super(ContextCommand, self).__init__() # # def execute(self, config, terminal, thread, platform_factory, argument): # if not thread.is_valid(): # return # # context = platform_factory.create_context(config, thread) # previous_context = context # if len(thread.contexts()): # previous_context = thread.contexts()[-1] # # context_widget = ContextWidget(previous_context, context) # context_widget.draw(terminal, terminal.width()) # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
return '%s %s' % (VoidwalkerParameter.name(), 'hook')
Using the snippet: <|code_start|> super(SnippetCommand, self).__init__() class SnippetCommandBuilder(object): def __init__(self, snippet_repository): @register_command class ListSnippetsCommand(SupportCommand): '''List all the available snippets''' @staticmethod def name(): return '%s %s' % (SnippetCommand.name(), 'list') def __init__(self): super(ListSnippetsCommand, self).__init__() def execute(self, terminal, *_): table = Table() for name, snippet in snippet_repository.snippets(): row = Row() row.add_cell(Cell('%s%s' % ('%(face-identifier)s', name))) row.add_cell(Cell('%s%s' % ('%(face-comment)s', snippet.description()))) table.add_row(row) section = Section('snippets') section.add_component(table) section.draw(terminal, terminal.width()) @register_command <|code_end|> , determine the next line of code. You have imports: from flowui.widgets import Section from flowui.widgets.table import Cell from flowui.widgets.table import Row from flowui.widgets.table import Table from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand from ...framework.interface import register_command from ...framework.platform import Architecture from ..commands.voidwalker import VoidwalkerCommand and context (class names, function names, or code) available: # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/platform/cpu.py # class Register(object): # class StaticRegister(type(register), object): # class Cpu(object): # class CpuFactory(object): # class CpuRepository(object): # def __init__(self, name): # def name(self): # def size(self): # def value(self): # def str(self): # def create_static_register(register): # def __init__(self, name): # def size(self): # def value(self): # def __init__(self, cpu_factory, registers): # def architecture(cls): # def register(self, name): # def registers(self): # def stack_pointer(self): # def program_counter(self): # def create_cpu(self, architecture): # def create_register(self, cpu, register): # def __init__(self, cpu_factory): # def get_cpu(self, architecture): # def register_cpu(cls): # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() . Output only the next line.
class ApplySnippetCommand(StackCommand):
Given the code snippet: <|code_start|> @register_command class PatchCommand(PrefixCommand): '''Commands for patching code''' @staticmethod def name(): return '%s %s' % (VoidwalkerCommand.name(), 'patch') def __init__(self): super(PatchCommand, self).__init__() @register_command class SnippetCommand(PrefixCommand): '''Predefined snippets for patching''' @staticmethod def name(): return '%s %s' % (PatchCommand.name(), 'snippet') def __init__(self): super(SnippetCommand, self).__init__() class SnippetCommandBuilder(object): def __init__(self, snippet_repository): @register_command <|code_end|> , generate the next line using the imports in this file: from flowui.widgets import Section from flowui.widgets.table import Cell from flowui.widgets.table import Row from flowui.widgets.table import Table from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand from ...framework.interface import register_command from ...framework.platform import Architecture from ..commands.voidwalker import VoidwalkerCommand and context (functions, classes, or occasionally code) from other files: # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/platform/cpu.py # class Register(object): # class StaticRegister(type(register), object): # class Cpu(object): # class CpuFactory(object): # class CpuRepository(object): # def __init__(self, name): # def name(self): # def size(self): # def value(self): # def str(self): # def create_static_register(register): # def __init__(self, name): # def size(self): # def value(self): # def __init__(self, cpu_factory, registers): # def architecture(cls): # def register(self, name): # def registers(self): # def stack_pointer(self): # def program_counter(self): # def create_cpu(self, architecture): # def create_register(self, cpu, register): # def __init__(self, cpu_factory): # def get_cpu(self, architecture): # def register_cpu(cls): # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() . Output only the next line.
class ListSnippetsCommand(SupportCommand):
Given the code snippet: <|code_start|> '''Apply a snippet: <name> <address> Apply the specified snippet at the specified address. This operation will overwrite whatever is at that location in memory. The original binary is never touched by this command.''' @staticmethod def name(): return '%s %s' % (SnippetCommand.name(), 'apply') def __init__(self): super(ApplySnippetCommand, self).__init__() def execute(self, config, terminal, thread, platform_factory, argument): if len(argument) < 2: terminal.write('%(face-error)s' 'Wrong number of arguments!\n') return inferior = thread.get_inferior() snippet = snippet_repository.snippet(argument[0]) if snippet is None: terminal.write(' '.join(['%(face-error)sSnippet', argument[0], '%s does not exist!\n'])) return architecture = inferior.cpu().architecture() implementation = None <|code_end|> , generate the next line using the imports in this file: from flowui.widgets import Section from flowui.widgets.table import Cell from flowui.widgets.table import Row from flowui.widgets.table import Table from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand from ...framework.interface import register_command from ...framework.platform import Architecture from ..commands.voidwalker import VoidwalkerCommand and context (functions, classes, or occasionally code) from other files: # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/platform/cpu.py # class Register(object): # class StaticRegister(type(register), object): # class Cpu(object): # class CpuFactory(object): # class CpuRepository(object): # def __init__(self, name): # def name(self): # def size(self): # def value(self): # def str(self): # def create_static_register(register): # def __init__(self, name): # def size(self): # def value(self): # def __init__(self, cpu_factory, registers): # def architecture(cls): # def register(self, name): # def registers(self): # def stack_pointer(self): # def program_counter(self): # def create_cpu(self, architecture): # def create_register(self, cpu, register): # def __init__(self, cpu_factory): # def get_cpu(self, architecture): # def register_cpu(cls): # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() . Output only the next line.
if ((architecture == Architecture.X8664 and
Predict the next line for this snippet: <|code_start|># (void)walker code patching interface # Copyright (C) 2012-2013 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_command class PatchCommand(PrefixCommand): '''Commands for patching code''' @staticmethod def name(): <|code_end|> with the help of current file imports: from flowui.widgets import Section from flowui.widgets.table import Cell from flowui.widgets.table import Row from flowui.widgets.table import Table from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand from ...framework.interface import register_command from ...framework.platform import Architecture from ..commands.voidwalker import VoidwalkerCommand and context from other files: # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/framework/platform/cpu.py # class Register(object): # class StaticRegister(type(register), object): # class Cpu(object): # class CpuFactory(object): # class CpuRepository(object): # def __init__(self, name): # def name(self): # def size(self): # def value(self): # def str(self): # def create_static_register(register): # def __init__(self, name): # def size(self): # def value(self): # def __init__(self, cpu_factory, registers): # def architecture(cls): # def register(self, name): # def registers(self): # def stack_pointer(self): # def program_counter(self): # def create_cpu(self, architecture): # def create_register(self, cpu, register): # def __init__(self, cpu_factory): # def get_cpu(self, architecture): # def register_cpu(cls): # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() , which may contain function names, class names, or code. Output only the next line.
return '%s %s' % (VoidwalkerCommand.name(), 'patch')
Next line prediction: <|code_start|># (void)walker nop snippets # Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_snippet class NopSnippet(Snippet): _code = {Architecture.X86: CodeBlock(x86.nop()), <|code_end|> . Use current file imports: (from ...framework.patching.composer import CodeBlock from ...framework.patching.snippet import Snippet from ...framework.patching.snippet import register_snippet from ...framework.platform.cpu import Architecture from ..cpus import mips_instructions as mips from ..cpus import x86_instructions as x86) and context including class names, function names, or small code snippets from other files: # Path: voidwalker/framework/patching/composer.py # class CodeBlock(object): # def __init__(self, *instructions): # self._instructions = list(instructions) # # def __len__(self): # return len(self._instructions) # # def hex(self): # stream = ByteStream() # (x.assemble(stream) for x in self._instructions).next() # return ' '.join('%02x' % ord(x) # for x in stream.buffer()) # # def assemble(self): # stream = ByteStream() # (x.assemble(stream) for x in self._instructions).next() # return stream.buffer() # # Path: voidwalker/framework/patching/snippet.py # class Snippet(object): # def architectures(self): # raise NotImplementedError # # def implementation(self, architecture): # raise NotImplementedError # # @staticmethod # def description(): # raise NotImplementedError # # @staticmethod # def name(): # raise NotImplementedError # # Path: voidwalker/framework/patching/snippet.py # def register_snippet(cls): # _snippet_map[cls.name()] = cls() # return cls # # Path: voidwalker/framework/platform/cpu.py # class Register(object): # class StaticRegister(type(register), object): # class Cpu(object): # class CpuFactory(object): # class CpuRepository(object): # def __init__(self, name): # def name(self): # def size(self): # def value(self): # def str(self): # def create_static_register(register): # def __init__(self, name): # def size(self): # def value(self): # def __init__(self, cpu_factory, registers): # def architecture(cls): # def register(self, name): # def registers(self): # def stack_pointer(self): # def program_counter(self): # def create_cpu(self, architecture): # def create_register(self, cpu, register): # def __init__(self, cpu_factory): # def get_cpu(self, architecture): # def register_cpu(cls): # # Path: voidwalker/application/cpus/mips_instructions.py # def nop(instruction): # # Path: voidwalker/application/cpus/x86_instructions.py # def nop(instruction): . Output only the next line.
Architecture.Mips: CodeBlock(mips.nop())}
Using the snippet: <|code_start|> def create_generic_command(self, command_type): class GdbCommand(gdb.Command, command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) gdb.Command.__init__(self, command_type.name(), gdb.COMMAND_USER, gdb.COMPLETE_COMMAND) return GdbCommand() def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): create_method = [(DataCommand, partial(self.create_data_command, command_type, terminal, inferior_repository, inferior_factory, thread_factory)), (StackCommand, partial(self.create_stack_command, command_type, config, terminal, inferior_repository, platform_factory, inferior_factory, thread_factory)), (PrefixCommand, partial(self.create_prefix_command, command_type, terminal)), (SupportCommand, partial(self.create_support_command, command_type, terminal)), <|code_end|> , determine the next line of code. You have imports: import gdb from functools import partial from ...framework.interface import BreakpointCommand from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand and context (class names, function names, or code) available: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError . Output only the next line.
(BreakpointCommand, partial(self.create_brkp_command,
Using the snippet: <|code_start|>def get_current_thread(inferior_repository, inferior_factory, thread_factory): if gdb.selected_thread() is not None: thread_num = gdb.selected_thread().num inferior = get_current_inferior(inferior_repository, inferior_factory) if not inferior.has_thread(thread_num): thread_factory.create_thread(inferior, thread_num) if inferior.has_thread(thread_num): return inferior.thread(thread_num) return None def parse_argument_list(argument): args = [] for obj in gdb.string_to_argv(argument): try: obj = gdb.parse_and_eval('%s' % obj) except gdb.error: pass args.append(obj) return args class GdbCommandFactory(CommandFactory, object): def create_data_command(self, command_type, terminal, inferior_repo, inferior_factory, thread_factory): <|code_end|> , determine the next line of code. You have imports: import gdb from functools import partial from ...framework.interface import BreakpointCommand from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand and context (class names, function names, or code) available: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError . Output only the next line.
class GdbDataCommand(gdb.Command, command_type):
Here is a snippet: <|code_start|> return inferior_repository.get_inferior(inferior_num) def get_current_thread(inferior_repository, inferior_factory, thread_factory): if gdb.selected_thread() is not None: thread_num = gdb.selected_thread().num inferior = get_current_inferior(inferior_repository, inferior_factory) if not inferior.has_thread(thread_num): thread_factory.create_thread(inferior, thread_num) if inferior.has_thread(thread_num): return inferior.thread(thread_num) return None def parse_argument_list(argument): args = [] for obj in gdb.string_to_argv(argument): try: obj = gdb.parse_and_eval('%s' % obj) except gdb.error: pass args.append(obj) return args <|code_end|> . Write the next line using the current file imports: import gdb from functools import partial from ...framework.interface import BreakpointCommand from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand and context from other files: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError , which may include functions, classes, or code. Output only the next line.
class GdbCommandFactory(CommandFactory, object):
Given the code snippet: <|code_start|> def create_brkp_command(self, command_type, terminal, inferior_repo): class GdbBreakpointCommand(gdb.Command, command_type): def __init__(self): command_type.__init__(self) gdb.Command.__init__(self, command_type.name(), gdb.COMMAND_BREAKPOINTS, gdb.COMPLETE_NONE) def invoke(self, argument, _): inferior = get_current_inferior(inferior_repo) if inferior is not None: args = parse_argument_list(argument) command_type.execute(self, terminal, inferior, args) return GdbBreakpointCommand() def create_generic_command(self, command_type): class GdbCommand(gdb.Command, command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) gdb.Command.__init__(self, command_type.name(), gdb.COMMAND_USER, gdb.COMPLETE_COMMAND) return GdbCommand() def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): <|code_end|> , generate the next line using the imports in this file: import gdb from functools import partial from ...framework.interface import BreakpointCommand from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand and context (functions, classes, or occasionally code) from other files: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError . Output only the next line.
create_method = [(DataCommand, partial(self.create_data_command,
Given snippet: <|code_start|> args = parse_argument_list(argument) command_type.execute(self, terminal, inferior, args) return GdbBreakpointCommand() def create_generic_command(self, command_type): class GdbCommand(gdb.Command, command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) gdb.Command.__init__(self, command_type.name(), gdb.COMMAND_USER, gdb.COMPLETE_COMMAND) return GdbCommand() def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): create_method = [(DataCommand, partial(self.create_data_command, command_type, terminal, inferior_repository, inferior_factory, thread_factory)), (StackCommand, partial(self.create_stack_command, command_type, config, terminal, inferior_repository, platform_factory, inferior_factory, thread_factory)), <|code_end|> , continue by predicting the next line. Consider current file imports: import gdb from functools import partial from ...framework.interface import BreakpointCommand from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand and context: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError which might include code, classes, or functions. Output only the next line.
(PrefixCommand, partial(self.create_prefix_command,
Using the snippet: <|code_start|> gdb.COMMAND_BREAKPOINTS, gdb.COMPLETE_NONE) def invoke(self, argument, _): inferior = get_current_inferior(inferior_repo) if inferior is not None: args = parse_argument_list(argument) command_type.execute(self, terminal, inferior, args) return GdbBreakpointCommand() def create_generic_command(self, command_type): class GdbCommand(gdb.Command, command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) gdb.Command.__init__(self, command_type.name(), gdb.COMMAND_USER, gdb.COMPLETE_COMMAND) return GdbCommand() def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): create_method = [(DataCommand, partial(self.create_data_command, command_type, terminal, inferior_repository, inferior_factory, thread_factory)), <|code_end|> , determine the next line of code. You have imports: import gdb from functools import partial from ...framework.interface import BreakpointCommand from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand and context (class names, function names, or code) available: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError . Output only the next line.
(StackCommand, partial(self.create_stack_command,
Using the snippet: <|code_start|> return GdbBreakpointCommand() def create_generic_command(self, command_type): class GdbCommand(gdb.Command, command_type): __doc__ = command_type.__doc__ def __init__(self): command_type.__init__(self) gdb.Command.__init__(self, command_type.name(), gdb.COMMAND_USER, gdb.COMPLETE_COMMAND) return GdbCommand() def create(self, command_type, inferior_repository, platform_factory, inferior_factory, thread_factory, config, terminal): create_method = [(DataCommand, partial(self.create_data_command, command_type, terminal, inferior_repository, inferior_factory, thread_factory)), (StackCommand, partial(self.create_stack_command, command_type, config, terminal, inferior_repository, platform_factory, inferior_factory, thread_factory)), (PrefixCommand, partial(self.create_prefix_command, command_type, terminal)), <|code_end|> , determine the next line of code. You have imports: import gdb from functools import partial from ...framework.interface import BreakpointCommand from ...framework.interface import Command from ...framework.interface import CommandFactory from ...framework.interface import DataCommand from ...framework.interface import PrefixCommand from ...framework.interface import StackCommand from ...framework.interface import SupportCommand and context (class names, function names, or code) available: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class Command(object): # pass # # Path: voidwalker/framework/interface/command.py # class CommandFactory(object): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def create(self, command_type, inferior_repository, platform_factory, # inferior_factory, thread_factory, config, terminal): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class DataCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, thread, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # class StackCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, config, terminal, thread, platform_factory, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class SupportCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, argument): # raise NotImplementedError . Output only the next line.
(SupportCommand, partial(self.create_support_command,
Continue the code snippet: <|code_start|> self._address = address self._buffer = data_buffer def __len__(self): return len(self._buffer) def address(self): return self._address def buffer(self): return self._buffer class DataWidget(Widget): _ascii_filter = ''.join([['.', chr(x)] [chr(x) in string.printable[:-5]] for x in xrange(256)]) def __init__(self, data_chunk): super(DataWidget, self).__init__() self._data_chunk = data_chunk def draw(self, terminal, width): table = Table() line_len = 16 if width < 100: line_len = 8 address = self._data_chunk.address() <|code_end|> . Use current file imports: import string from flowui import Widget from flowui.widgets.table import Cell from flowui.widgets.table import Row from flowui.widgets.table import Table from ..utils.recipes import grouper and context (classes, functions, or code) from other files: # Path: voidwalker/framework/utils/recipes.py # def grouper(n, iterable, fillvalue=None): # args = [iter(iterable)] * n # return izip_longest(*args, fillvalue=fillvalue) . Output only the next line.
for line in grouper(line_len, self._data_chunk.buffer()):
Based on the snippet: <|code_start|># the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_parameter class ContextParameter(PrefixParameter): '''(void)walker context command parameters''' def __init__(self): super(ContextParameter, self).__init__() def default_value(self): return None @staticmethod def name(): return '%s %s' % (VoidwalkerParameter.name(), 'context') @register_parameter <|code_end|> , predict the immediate next line with the help of imports: from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import IntegerParameter from ...framework.interface.parameter import register_parameter from .voidwalker import VoidwalkerParameter and context (classes, functions, sometimes code) from other files: # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class IntegerParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
class ContextStackParameter(IntegerParameter):
Given the code snippet: <|code_start|># Copyright (C) 2012-2013 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_parameter class ContextParameter(PrefixParameter): '''(void)walker context command parameters''' def __init__(self): super(ContextParameter, self).__init__() def default_value(self): return None @staticmethod def name(): <|code_end|> , generate the next line using the imports in this file: from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import IntegerParameter from ...framework.interface.parameter import register_parameter from .voidwalker import VoidwalkerParameter and context (functions, classes, or occasionally code) from other files: # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class IntegerParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
return '%s %s' % (VoidwalkerParameter.name(), 'context')
Continue the code snippet: <|code_start|># (void)walker GDB-specific interface # Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_command class GdbCommand(PrefixCommand): '''Commands for interacting with GDB''' @staticmethod def name(): <|code_end|> . Use current file imports: from ....framework.interface.command import PrefixCommand from ....framework.interface.command import register_command from ....application.commands.voidwalker import VoidwalkerCommand and context (classes, functions, or code) from other files: # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/application/commands/voidwalker.py # class VoidwalkerCommand(PrefixCommand): # '''(void)walker is a GDB toolbox for low-level software debugging. # # https://github.com/dholm/voidwalker''' # # @staticmethod # def name(): # return 'voidwalker' # # def __init__(self): # super(VoidwalkerCommand, self).__init__() . Output only the next line.
return '%s %s' % (VoidwalkerCommand.name(), 'gdb')
Given snippet: <|code_start|> return GdbParameterInteger() def create_boolean_parameter(self, parameter_type): class GdbParameterBoolean(GdbBaseParameter, parameter_type): __doc__ = parameter_type.__doc__ show_doc = __doc__ set_doc = __doc__ def __init__(self): parameter_type.__init__(self) gdb_name = parameter_type.name().replace(' ', '-') GdbBaseParameter.__init__(self, gdb_name, gdb.COMMAND_SUPPORT, gdb.PARAM_BOOLEAN) self.value = parameter_type.default_value(self) return GdbParameterBoolean() def create_generic_parameter(self, parameter_type): class GdbParameter(parameter_type): __doc__ = parameter_type.__doc__ def __init__(self): parameter_type.__init__(self) return GdbParameter() def create(self, parameter_type): create_method = [(EnumParameter, self.create_enum_parameter), (IntegerParameter, self.create_integer_parameter), <|code_end|> , continue by predicting the next line. Consider current file imports: import gdb from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import EnumParameter from ...framework.interface.parameter import IntegerParameter from ...framework.interface.parameter import Parameter from ...framework.interface.parameter import PrefixParameter and context: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class IntegerParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError which might include code, classes, or functions. Output only the next line.
(BooleanParameter, self.create_boolean_parameter),
Continue the code snippet: <|code_start|> self.value = parameter_type.default_value(self) return GdbParameterInteger() def create_boolean_parameter(self, parameter_type): class GdbParameterBoolean(GdbBaseParameter, parameter_type): __doc__ = parameter_type.__doc__ show_doc = __doc__ set_doc = __doc__ def __init__(self): parameter_type.__init__(self) gdb_name = parameter_type.name().replace(' ', '-') GdbBaseParameter.__init__(self, gdb_name, gdb.COMMAND_SUPPORT, gdb.PARAM_BOOLEAN) self.value = parameter_type.default_value(self) return GdbParameterBoolean() def create_generic_parameter(self, parameter_type): class GdbParameter(parameter_type): __doc__ = parameter_type.__doc__ def __init__(self): parameter_type.__init__(self) return GdbParameter() def create(self, parameter_type): <|code_end|> . Use current file imports: import gdb from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import EnumParameter from ...framework.interface.parameter import IntegerParameter from ...framework.interface.parameter import Parameter from ...framework.interface.parameter import PrefixParameter and context (classes, functions, or code) from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class IntegerParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError . Output only the next line.
create_method = [(EnumParameter, self.create_enum_parameter),
Using the snippet: <|code_start|> return GdbParameterInteger() def create_boolean_parameter(self, parameter_type): class GdbParameterBoolean(GdbBaseParameter, parameter_type): __doc__ = parameter_type.__doc__ show_doc = __doc__ set_doc = __doc__ def __init__(self): parameter_type.__init__(self) gdb_name = parameter_type.name().replace(' ', '-') GdbBaseParameter.__init__(self, gdb_name, gdb.COMMAND_SUPPORT, gdb.PARAM_BOOLEAN) self.value = parameter_type.default_value(self) return GdbParameterBoolean() def create_generic_parameter(self, parameter_type): class GdbParameter(parameter_type): __doc__ = parameter_type.__doc__ def __init__(self): parameter_type.__init__(self) return GdbParameter() def create(self, parameter_type): create_method = [(EnumParameter, self.create_enum_parameter), <|code_end|> , determine the next line of code. You have imports: import gdb from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import EnumParameter from ...framework.interface.parameter import IntegerParameter from ...framework.interface.parameter import Parameter from ...framework.interface.parameter import PrefixParameter and context (class names, function names, or code) available: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class IntegerParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError . Output only the next line.
(IntegerParameter, self.create_integer_parameter),
Next line prediction: <|code_start|> def create_boolean_parameter(self, parameter_type): class GdbParameterBoolean(GdbBaseParameter, parameter_type): __doc__ = parameter_type.__doc__ show_doc = __doc__ set_doc = __doc__ def __init__(self): parameter_type.__init__(self) gdb_name = parameter_type.name().replace(' ', '-') GdbBaseParameter.__init__(self, gdb_name, gdb.COMMAND_SUPPORT, gdb.PARAM_BOOLEAN) self.value = parameter_type.default_value(self) return GdbParameterBoolean() def create_generic_parameter(self, parameter_type): class GdbParameter(parameter_type): __doc__ = parameter_type.__doc__ def __init__(self): parameter_type.__init__(self) return GdbParameter() def create(self, parameter_type): create_method = [(EnumParameter, self.create_enum_parameter), (IntegerParameter, self.create_integer_parameter), (BooleanParameter, self.create_boolean_parameter), <|code_end|> . Use current file imports: (import gdb from ...framework.interface.parameter import BooleanParameter from ...framework.interface.parameter import EnumParameter from ...framework.interface.parameter import IntegerParameter from ...framework.interface.parameter import Parameter from ...framework.interface.parameter import PrefixParameter) and context including class names, function names, or small code snippets from other files: # Path: voidwalker/framework/interface/parameter.py # class BooleanParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class EnumParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def sequence(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class IntegerParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class Parameter(object): # __metaclass__ = abc.ABCMeta # # def init(self): # pass # # @staticmethod # def name(): # raise NotImplementedError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError . Output only the next line.
(PrefixParameter, self.create_generic_parameter),
Based on the snippet: <|code_start|># Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_parameter class ShowParameter(PrefixParameter): '''(void)walker show parameters''' def __init__(self): super(ShowParameter, self).__init__() def default_value(self): return None @staticmethod def name(): <|code_end|> , predict the immediate next line with the help of imports: from ...framework.interface.parameter import PrefixParameter from ...framework.interface.parameter import register_parameter from .voidwalker import VoidwalkerParameter and context (classes, functions, sometimes code) from other files: # Path: voidwalker/framework/interface/parameter.py # class PrefixParameter(Parameter): # __metaclass__ = abc.ABCMeta # # @classmethod # def get_value(cls): # raise TypeError # # @abc.abstractmethod # def default_value(self): # raise NotImplementedError # # Path: voidwalker/framework/interface/parameter.py # def register_parameter(cls): # _parameter_list.append(cls) # return cls # # Path: voidwalker/application/parameters/voidwalker.py # class VoidwalkerParameter(PrefixParameter): # '''(void)walker parameters''' # # def __init__(self): # super(VoidwalkerParameter, self).__init__() # # def init(self): # pass # # def default_value(self): # return None # # @staticmethod # def name(): # return 'voidwalker' . Output only the next line.
return '%s %s' % (VoidwalkerParameter.name(), 'show')
Next line prediction: <|code_start|># This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_command class BreakCommand(PrefixCommand): '''Commands for GDB breakpoints''' @staticmethod def name(): return '%s %s' % (GdbCommand.name(), 'break') def __init__(self): super(BreakCommand, self).__init__() @register_command <|code_end|> . Use current file imports: (import gdb import re from ....framework.interface.command import BreakpointCommand from ....framework.interface.command import PrefixCommand from ....framework.interface.command import register_command from .interface import GdbCommand) and context including class names, function names, or small code snippets from other files: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/backends/gdb/tools/interface.py # class GdbCommand(PrefixCommand): # '''Commands for interacting with GDB''' # # @staticmethod # def name(): # return '%s %s' % (VoidwalkerCommand.name(), 'gdb') # # def __init__(self): # super(GdbCommand, self).__init__() . Output only the next line.
class BreakTextCommand(BreakpointCommand):
Predict the next line for this snippet: <|code_start|># (void)walker GDB breakpoint control # Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @register_command class BreakCommand(PrefixCommand): '''Commands for GDB breakpoints''' @staticmethod def name(): <|code_end|> with the help of current file imports: import gdb import re from ....framework.interface.command import BreakpointCommand from ....framework.interface.command import PrefixCommand from ....framework.interface.command import register_command from .interface import GdbCommand and context from other files: # Path: voidwalker/framework/interface/command.py # class BreakpointCommand(Command): # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def execute(self, terminal, inferior, argument): # raise NotImplementedError # # Path: voidwalker/framework/interface/command.py # class PrefixCommand(Command): # def execute(self, terminal): # terminal.write('%(face-error)sAttempting to invoke an ' # 'incomplete command!\n') # # Path: voidwalker/framework/interface/command.py # def register_command(cls): # _command_list.append(cls) # return cls # # Path: voidwalker/backends/gdb/tools/interface.py # class GdbCommand(PrefixCommand): # '''Commands for interacting with GDB''' # # @staticmethod # def name(): # return '%s %s' % (VoidwalkerCommand.name(), 'gdb') # # def __init__(self): # super(GdbCommand, self).__init__() , which may contain function names, class names, or code. Output only the next line.
return '%s %s' % (GdbCommand.name(), 'break')
Based on the snippet: <|code_start|># (void)walker unit tests # Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class InferiorTest(TestCase): def setUp(self): cpu_factory = TestCpuFactory() self._cpu = cpu_factory.create_cpu(None) def test_inferior_repository(self): <|code_end|> , predict the immediate next line with the help of imports: from unittest import TestCase from voidwalker.framework.platform import CpuFactory from voidwalker.framework.target import InferiorRepository from voidwalker.backends.test import TestPlatformFactory from voidwalker.backends.test import TestThreadFactory from voidwalker.backends.test import TestInferiorFactory from voidwalker.backends.test.platform import TestCpuFactory from voidwalker.backends.test.target import TestInferiorFactory from voidwalker.backends.test.target import TestThreadFactory and context (classes, functions, sometimes code) from other files: # Path: voidwalker/framework/platform/cpu.py # class CpuFactory(object): # __metaclass__ = abc.ABCMeta # # def create_cpu(self, architecture): # assert architecture in _cpu_map # return _cpu_map.get(architecture, # None)(self) # # @abc.abstractmethod # def create_register(self, cpu, register): # raise NotImplementedError # # Path: voidwalker/framework/target/inferior.py # class InferiorRepository(object): # def __init__(self): # self._inferiors = {} # # def add_inferior(self, inferior): # self._inferiors[inferior.id()] = inferior # # def has_inferior(self, inferior_id): # return inferior_id in self._inferiors # # def get_inferior(self, inferior_id): # assert self.has_inferior(inferior_id), ('inferior %r not found' % # inferior_id) # return self._inferiors[inferior_id] # # Path: voidwalker/backends/test/platform.py # class TestPlatformFactory(PlatformFactory, object): # def __init__(self): # self._registers = None # self.reset() # # def reset(self): # self._registers = {} # # def create_context(self, config, inferior, thread): # class TestContext(Context): # def __init__(self): # sp = inferior.cpu().stack_pointer() # super(TestContext, self).__init__(sp) # # for group, register_dict in inferior.cpu().registers(): # register_dict = dict((x.name(), create_static_register(x)) # for x in register_dict.itervalues()) # self._registers[group] = register_dict # # return TestContext() # # Path: voidwalker/backends/test/target.py # class TestThreadFactory(ThreadFactory): # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior, thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/target.py # class TestInferiorFactory(InferiorFactory): # def __init__(self): # super(TestInferiorFactory, self).__init__(TestCpuFactory()) # # def create_inferior(self, cpu, inferior_id): # return TestInferior(cpu, inferior_id) # # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior.id(), thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/platform.py # class TestCpuFactory(CpuFactory): # def __init__(self): # self._registers = None # # def create_cpu(self, architecture): # return TestCpu(self) # # def create_register(self, cpu, register): # class TestRegister(type(register), object): # def __init__(self, name): # super(TestRegister, self).__init__(name) # self._size = 8 # self._value = 0 # # def size(self): # return self._size # # def value(self): # return self._value # # return TestRegister(register.name()) # # Path: voidwalker/backends/test/target.py # class TestInferiorFactory(InferiorFactory): # def __init__(self): # super(TestInferiorFactory, self).__init__(TestCpuFactory()) # # def create_inferior(self, cpu, inferior_id): # return TestInferior(cpu, inferior_id) # # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior.id(), thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/target.py # class TestThreadFactory(ThreadFactory): # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior, thread_id) # inferior.add_thread(thread) # return thread . Output only the next line.
inferior_repository = InferiorRepository()
Continue the code snippet: <|code_start|># GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class InferiorTest(TestCase): def setUp(self): cpu_factory = TestCpuFactory() self._cpu = cpu_factory.create_cpu(None) def test_inferior_repository(self): inferior_repository = InferiorRepository() self.assertFalse(inferior_repository.has_inferior(0)) def test_inferior(self): inferior_factory = TestInferiorFactory() inferior = inferior_factory.create_inferior(self._cpu, 0) self.assertEqual(0, inferior.id()) self.assertEqual(inferior.cpu().architecture(), self._cpu.architecture()) def test_thread(self): inferior_factory = TestInferiorFactory() inferior = inferior_factory.create_inferior(self._cpu, 0) <|code_end|> . Use current file imports: from unittest import TestCase from voidwalker.framework.platform import CpuFactory from voidwalker.framework.target import InferiorRepository from voidwalker.backends.test import TestPlatformFactory from voidwalker.backends.test import TestThreadFactory from voidwalker.backends.test import TestInferiorFactory from voidwalker.backends.test.platform import TestCpuFactory from voidwalker.backends.test.target import TestInferiorFactory from voidwalker.backends.test.target import TestThreadFactory and context (classes, functions, or code) from other files: # Path: voidwalker/framework/platform/cpu.py # class CpuFactory(object): # __metaclass__ = abc.ABCMeta # # def create_cpu(self, architecture): # assert architecture in _cpu_map # return _cpu_map.get(architecture, # None)(self) # # @abc.abstractmethod # def create_register(self, cpu, register): # raise NotImplementedError # # Path: voidwalker/framework/target/inferior.py # class InferiorRepository(object): # def __init__(self): # self._inferiors = {} # # def add_inferior(self, inferior): # self._inferiors[inferior.id()] = inferior # # def has_inferior(self, inferior_id): # return inferior_id in self._inferiors # # def get_inferior(self, inferior_id): # assert self.has_inferior(inferior_id), ('inferior %r not found' % # inferior_id) # return self._inferiors[inferior_id] # # Path: voidwalker/backends/test/platform.py # class TestPlatformFactory(PlatformFactory, object): # def __init__(self): # self._registers = None # self.reset() # # def reset(self): # self._registers = {} # # def create_context(self, config, inferior, thread): # class TestContext(Context): # def __init__(self): # sp = inferior.cpu().stack_pointer() # super(TestContext, self).__init__(sp) # # for group, register_dict in inferior.cpu().registers(): # register_dict = dict((x.name(), create_static_register(x)) # for x in register_dict.itervalues()) # self._registers[group] = register_dict # # return TestContext() # # Path: voidwalker/backends/test/target.py # class TestThreadFactory(ThreadFactory): # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior, thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/target.py # class TestInferiorFactory(InferiorFactory): # def __init__(self): # super(TestInferiorFactory, self).__init__(TestCpuFactory()) # # def create_inferior(self, cpu, inferior_id): # return TestInferior(cpu, inferior_id) # # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior.id(), thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/platform.py # class TestCpuFactory(CpuFactory): # def __init__(self): # self._registers = None # # def create_cpu(self, architecture): # return TestCpu(self) # # def create_register(self, cpu, register): # class TestRegister(type(register), object): # def __init__(self, name): # super(TestRegister, self).__init__(name) # self._size = 8 # self._value = 0 # # def size(self): # return self._size # # def value(self): # return self._value # # return TestRegister(register.name()) # # Path: voidwalker/backends/test/target.py # class TestInferiorFactory(InferiorFactory): # def __init__(self): # super(TestInferiorFactory, self).__init__(TestCpuFactory()) # # def create_inferior(self, cpu, inferior_id): # return TestInferior(cpu, inferior_id) # # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior.id(), thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/target.py # class TestThreadFactory(ThreadFactory): # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior, thread_id) # inferior.add_thread(thread) # return thread . Output only the next line.
thread_factory = TestThreadFactory()
Given the following code snippet before the placeholder: <|code_start|># Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class InferiorTest(TestCase): def setUp(self): cpu_factory = TestCpuFactory() self._cpu = cpu_factory.create_cpu(None) def test_inferior_repository(self): inferior_repository = InferiorRepository() self.assertFalse(inferior_repository.has_inferior(0)) def test_inferior(self): <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase from voidwalker.framework.platform import CpuFactory from voidwalker.framework.target import InferiorRepository from voidwalker.backends.test import TestPlatformFactory from voidwalker.backends.test import TestThreadFactory from voidwalker.backends.test import TestInferiorFactory from voidwalker.backends.test.platform import TestCpuFactory from voidwalker.backends.test.target import TestInferiorFactory from voidwalker.backends.test.target import TestThreadFactory and context including class names, function names, and sometimes code from other files: # Path: voidwalker/framework/platform/cpu.py # class CpuFactory(object): # __metaclass__ = abc.ABCMeta # # def create_cpu(self, architecture): # assert architecture in _cpu_map # return _cpu_map.get(architecture, # None)(self) # # @abc.abstractmethod # def create_register(self, cpu, register): # raise NotImplementedError # # Path: voidwalker/framework/target/inferior.py # class InferiorRepository(object): # def __init__(self): # self._inferiors = {} # # def add_inferior(self, inferior): # self._inferiors[inferior.id()] = inferior # # def has_inferior(self, inferior_id): # return inferior_id in self._inferiors # # def get_inferior(self, inferior_id): # assert self.has_inferior(inferior_id), ('inferior %r not found' % # inferior_id) # return self._inferiors[inferior_id] # # Path: voidwalker/backends/test/platform.py # class TestPlatformFactory(PlatformFactory, object): # def __init__(self): # self._registers = None # self.reset() # # def reset(self): # self._registers = {} # # def create_context(self, config, inferior, thread): # class TestContext(Context): # def __init__(self): # sp = inferior.cpu().stack_pointer() # super(TestContext, self).__init__(sp) # # for group, register_dict in inferior.cpu().registers(): # register_dict = dict((x.name(), create_static_register(x)) # for x in register_dict.itervalues()) # self._registers[group] = register_dict # # return TestContext() # # Path: voidwalker/backends/test/target.py # class TestThreadFactory(ThreadFactory): # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior, thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/target.py # class TestInferiorFactory(InferiorFactory): # def __init__(self): # super(TestInferiorFactory, self).__init__(TestCpuFactory()) # # def create_inferior(self, cpu, inferior_id): # return TestInferior(cpu, inferior_id) # # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior.id(), thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/platform.py # class TestCpuFactory(CpuFactory): # def __init__(self): # self._registers = None # # def create_cpu(self, architecture): # return TestCpu(self) # # def create_register(self, cpu, register): # class TestRegister(type(register), object): # def __init__(self, name): # super(TestRegister, self).__init__(name) # self._size = 8 # self._value = 0 # # def size(self): # return self._size # # def value(self): # return self._value # # return TestRegister(register.name()) # # Path: voidwalker/backends/test/target.py # class TestInferiorFactory(InferiorFactory): # def __init__(self): # super(TestInferiorFactory, self).__init__(TestCpuFactory()) # # def create_inferior(self, cpu, inferior_id): # return TestInferior(cpu, inferior_id) # # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior.id(), thread_id) # inferior.add_thread(thread) # return thread # # Path: voidwalker/backends/test/target.py # class TestThreadFactory(ThreadFactory): # def create_thread(self, inferior, thread_id): # thread = TestThread(inferior, thread_id) # inferior.add_thread(thread) # return thread . Output only the next line.
inferior_factory = TestInferiorFactory()
Predict the next line after this snippet: <|code_start|># (void)walker assembler composer # Based on Pyasm by Florian Boesch, https://bitbucket.org/pyalot/pyasm/ # Copyright (C) 2012 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class CodeBlock(object): def __init__(self, *instructions): self._instructions = list(instructions) def __len__(self): return len(self._instructions) def hex(self): <|code_end|> using the current file's imports: from .types import ByteStream and any relevant context from other files: # Path: voidwalker/framework/patching/types.py # class ByteStream(object): # def __init__(self): # self._buffer = bytes() # # def buffer(self): # return self._buffer # # def byte(self, value): # self._buffer += struct.pack('B', value) # # def halfword(self, value): # self._buffer += struct.pack('H', value) # # def word(self, value): # self._buffer += struct.pack('I', value) # # def doubleword(self, value): # self._buffer += struct.pack('Q', value) . Output only the next line.
stream = ByteStream()
Based on the snippet: <|code_start|> return self._process(unions) def _prepare_clipper(self, poly): """Prepare 2D polygons for clipping operations. :param poly: The clip polygon. :returns: A Pyclipper object. """ s1 = pc.scale_to_clipper(self.vertices_list) s2 = pc.scale_to_clipper(poly.vertices_list) clipper = pc.Pyclipper() clipper.AddPath(s1, poly_type=pc.PT_SUBJECT, closed=True) clipper.AddPath(s2, poly_type=pc.PT_CLIP, closed=True) return clipper def _process(self, results): """Process and return the results of a clipping operation. :param results: A list of lists of coordinates . :returns: A list of Polygon2D results of the clipping operation. """ if not results: return [] scaled = [pc.scale_from_clipper(r) for r in results] polys = [self.as_2d(r) for r in scaled] processed = [] for poly in polys: <|code_end|> , predict the immediate next line with the help of imports: from typing import List # noqa from .polygons import Polygon # noqa from ..utilities import almostequal import pyclipper as pc and context (classes, functions, sometimes code) from other files: # Path: geomeppy/utilities.py # def almostequal(first, second, places=7): # # type: (Any, Any, int) -> bool # """Tests a range of types for near equality.""" # try: # # try converting to float first # first = float(first) # second = float(second) # # test floats for near-equality # if round(abs(second - first), places) != 0: # return False # else: # return True # except ValueError: # # handle non-float types # return str(first) == str(second) # except TypeError: # # handle iterables # return all([almostequal(a, b, places) for a, b in zip(first, second)]) . Output only the next line.
if almostequal(poly.normal_vector, self.normal_vector):
Predict the next line after this snippet: <|code_start|> def test_copy_geometry(extracts_idf): idf = copy_geometry(extracts_idf) assert idf.getobject("ZONE", "z1 Thermal Zone") assert not idf.getobject("MATERIAL", "Spam") def test_copy_constructions(extracts_idf): <|code_end|> using the current file's imports: from geomeppy.extractor import copy_constructions, copy_geometry and any relevant context from other files: # Path: geomeppy/extractor.py # def copy_constructions(source_idf, target_idf=None, fname="new.idf"): # # type: (IDF, Optional[IDF], str) -> IDF # """Extract construction objects from a source IDF and add them to a target IDF or a new IDF. # # :param source_idf: An IDF to source objects from. # :param target_idf: An optional IDF to add objects to. If none is passed, a new IDF is returned. # :param fname: A name for the new IDF created if no target IDF is passed in. Default: "new.idf". # :returns: Either the target IDF or a new IDF containing the construction objects. # """ # group = "Surface Construction Elements" # target_idf = target_idf or new_idf(fname) # idf = copy_group(source_idf, target_idf, group) # return idf # # def copy_geometry(source_idf, target_idf=None, fname="new.idf"): # # type: (IDF, Optional[IDF], str) -> IDF # """Extract geometry objects from a source IDF and add them to a target IDF or a new IDF.. # # :param source_idf: An IDF to source objects from. # :param target_idf: An optional IDF to add objects to. If none is passed, a new IDF is returned. # :param fname: A name for the new IDF created if no target IDF is passed in. Default: "new.idf". # :returns: Either the target IDF or a new IDF containing the geometry objects. # """ # group = "Thermal Zones and Surfaces" # target_idf = target_idf or new_idf(fname) # idf = copy_group(source_idf, target_idf, group) # return idf . Output only the next line.
idf = copy_constructions(extracts_idf)
Based on the snippet: <|code_start|>"""Tests for fetching surfaces.""" class TestSurfaces: def test_surfaces(self, wwr_idf): # type: () -> None idf = wwr_idf surfaces = idf.getsurfaces() assert surfaces <|code_end|> , predict the immediate next line with the help of imports: from geomeppy.idf import EpBunch and context (classes, functions, sometimes code) from other files: # Path: geomeppy/idf.py # def new_idf(fname): # def intersect_match(self): # def intersect(self): # def match(self): # def translate_to_origin(self): # def translate(self, vector): # def rotate(self, angle, anchor=None): # def scale(self, factor, anchor=None, axes="xy"): # def set_default_constructions(self): # def bounding_box(self): # def centroid(self): # def getsurfaces(self, surface_type=""): # def getsubsurfaces(self, surface_type=""): # def getshadingsurfaces(self, surface_type=""): # def set_wwr( # self, wwr=0.2, construction=None, force=False, wwr_map={}, orientation=None # ): # def view_model(self, test=False): # def to_obj(self, fname=None, mtllib=None): # def add_block(self, *args, **kwargs): # def add_shading_block(self, *args, **kwargs): # def add_zone(self, zone): # class IDF(PatchedIDF): . Output only the next line.
assert all(isinstance(s, EpBunch) for s in surfaces)
Given the code snippet: <|code_start|> def __repr__(self): # type: () -> str class_name = type(self).__name__ return "{}({}, {})".format(class_name, self.p1, self.p2) def __neg__(self): # type: () -> Segment return Segment(self.p2, self.p1) def __iter__(self): # type: () -> Iterator return (i for i in self.vertices) def __eq__(self, other): # type: (Any) -> bool return self.__dict__ == other.__dict__ def _is_collinear(self, other): # type: (Segment) -> bool """Test if a segment is collinear with another segment :param other: The other segment. :return: True if the segments are collinear else False. """ if almostequal(other, self) or almostequal(other, -self): return True a = self.p1 - other.p1 b = self.p1 - other.p2 angle_between = a.cross(b) <|code_end|> , generate the next line using the imports in this file: from typing import Any, Iterator # noqa from .vectors import Vector3D from ..utilities import almostequal from .polygons import Polygon3D # noqa and context (functions, classes, or occasionally code) from other files: # Path: geomeppy/geom/vectors.py # class Vector3D(Vector2D): # """Three dimensional point.""" # # def __init__( # self, # x, # type: Union[float, np.float64] # y, # type: Union[float, np.float64] # z=0, # type: Union[float, np.float64] # ): # # type: (...) -> None # super(Vector3D, self).__init__(x, y, z) # self.z = float(z) # self.args = [self.x, self.y, self.z] # # def __repr__(self): # # type: () -> str # class_name = type(self).__name__ # return "{}({!r}, {!r}, {!r})".format(class_name, *self.args) # # def __hash__(self): # # type: () -> int # return hash(self.x) ^ hash(self.y) ^ hash(self.z) # # Path: geomeppy/utilities.py # def almostequal(first, second, places=7): # # type: (Any, Any, int) -> bool # """Tests a range of types for near equality.""" # try: # # try converting to float first # first = float(first) # second = float(second) # # test floats for near-equality # if round(abs(second - first), places) != 0: # return False # else: # return True # except ValueError: # # handle non-float types # return str(first) == str(second) # except TypeError: # # handle iterables # return all([almostequal(a, b, places) for a, b in zip(first, second)]) . Output only the next line.
if almostequal(angle_between, Vector3D(0, 0, 0)):
Next line prediction: <|code_start|> def __init__(self, *vertices): # type: (*Vector3D) -> None self.vertices = vertices self.p1 = vertices[0] self.p2 = vertices[1] def __repr__(self): # type: () -> str class_name = type(self).__name__ return "{}({}, {})".format(class_name, self.p1, self.p2) def __neg__(self): # type: () -> Segment return Segment(self.p2, self.p1) def __iter__(self): # type: () -> Iterator return (i for i in self.vertices) def __eq__(self, other): # type: (Any) -> bool return self.__dict__ == other.__dict__ def _is_collinear(self, other): # type: (Segment) -> bool """Test if a segment is collinear with another segment :param other: The other segment. :return: True if the segments are collinear else False. """ <|code_end|> . Use current file imports: (from typing import Any, Iterator # noqa from .vectors import Vector3D from ..utilities import almostequal from .polygons import Polygon3D # noqa) and context including class names, function names, or small code snippets from other files: # Path: geomeppy/geom/vectors.py # class Vector3D(Vector2D): # """Three dimensional point.""" # # def __init__( # self, # x, # type: Union[float, np.float64] # y, # type: Union[float, np.float64] # z=0, # type: Union[float, np.float64] # ): # # type: (...) -> None # super(Vector3D, self).__init__(x, y, z) # self.z = float(z) # self.args = [self.x, self.y, self.z] # # def __repr__(self): # # type: () -> str # class_name = type(self).__name__ # return "{}({!r}, {!r}, {!r})".format(class_name, *self.args) # # def __hash__(self): # # type: () -> int # return hash(self.x) ^ hash(self.y) ^ hash(self.z) # # Path: geomeppy/utilities.py # def almostequal(first, second, places=7): # # type: (Any, Any, int) -> bool # """Tests a range of types for near equality.""" # try: # # try converting to float first # first = float(first) # second = float(second) # # test floats for near-equality # if round(abs(second - first), places) != 0: # return False # else: # return True # except ValueError: # # handle non-float types # return str(first) == str(second) # except TypeError: # # handle iterables # return all([almostequal(a, b, places) for a, b in zip(first, second)]) . Output only the next line.
if almostequal(other, self) or almostequal(other, -self):
Given the following code snippet before the placeholder: <|code_start|> }, { "name": "PN1001_Bld1003 Zone4", "coordinates": [ (-83616.24896021019, -100960.96199999936), (-83619.72295787116, -100976.95590000041), (-83636.55229433342, -100976.95590000041), (-83636.50970000029, -100976.35019999929), (-83635.42752116646, -100960.96199999936), (-83616.24896021019, -100960.96199999936), ], "height": 3.0, "num_stories": 1, }, ] return {"zones": zones, "shadows": shadow_blocks} def _test_adjacencies(new_idf, shadow_intersecting): """Test in a single plane, but angled.""" try: ggr = new_idf.idfobjects["GLOBALGEOMETRYRULES"][0] except IndexError: ggr = None for block in shadow_intersecting["shadows"]: new_idf.add_shading_block(**block) for block in shadow_intersecting["zones"]: new_idf.add_block(**block) new_idf.translate_to_origin() # new_idf.view_model() <|code_end|> , predict the next line using imports from the current file: import pytest from geomeppy.geom.surfaces import get_adjacencies from geomeppy.geom.surfaces import set_coords and context including class names, function names, and sometimes code from other files: # Path: geomeppy/geom/surfaces.py # def get_adjacencies(surfaces): # # type: (Idf_MSequence) -> defaultdict # """Create a dictionary mapping surfaces to their adjacent surfaces. # # :param surfaces: A mutable list of surfaces. # :returns: Mapping of surfaces to adjacent surfaces. # """ # adjacencies = defaultdict(list) # type: defaultdict # # find all adjacent surfaces # for s1, s2 in combinations(surfaces, 2): # adjacencies = populate_adjacencies(adjacencies, s1, s2) # for adjacency, polys in adjacencies.items(): # adjacencies[adjacency] = minimal_set(polys) # return adjacencies # # Path: geomeppy/geom/surfaces.py # def set_coords( # surface, # type: EpBunch # coords, # # type: Union[List[Vector3D], List[Tuple[float, float, float]], Polygon3D] # ggr, # type: Union[List, None, Idf_MSequence] # ): # # type: (...) -> None # """Update the coordinates of a surface. # # :param surface: The surface to modify. # :param coords: The new coordinates as lists of [x,y,z] lists. # :param ggr: Global geometry rules. # """ # coords = list(coords) # deduped = [c for i, c in enumerate(coords) if c != coords[(i + 1) % len(coords)]] # poly = Polygon3D(deduped) # poly = poly.normalize_coords(ggr) # coords = [i for vertex in poly for i in vertex] # if len(coords) > 120: # warnings.warn( # "To create surfaces with >120 vertices, ensure you have customised your IDD before running EnergyPlus. " # "https://unmethours.com/question/9343/energy-idf-parsing-error/?answer=9344#post-id-9344" # ) # # find the vertex fields # n_vertices_index = surface.objls.index("Number_of_Vertices") # first_x = n_vertices_index + 1 # X of first coordinate # surface.obj = surface.obj[:first_x] # # set the vertex field values # surface.fieldvalues.extend(coords) . Output only the next line.
adjacencies = get_adjacencies(new_idf.getsurfaces() + new_idf.getshadingsurfaces())
Given snippet: <|code_start|> "num_stories": 1, }, ] return {"zones": zones, "shadows": shadow_blocks} def _test_adjacencies(new_idf, shadow_intersecting): """Test in a single plane, but angled.""" try: ggr = new_idf.idfobjects["GLOBALGEOMETRYRULES"][0] except IndexError: ggr = None for block in shadow_intersecting["shadows"]: new_idf.add_shading_block(**block) for block in shadow_intersecting["zones"]: new_idf.add_block(**block) new_idf.translate_to_origin() # new_idf.view_model() adjacencies = get_adjacencies(new_idf.getsurfaces() + new_idf.getshadingsurfaces()) done = [] for surface in adjacencies: key, name = surface new_surfaces = adjacencies[surface] old_obj = new_idf.getobject(key.upper(), name) for i, new_coords in enumerate(new_surfaces, 1): if (key, name, new_coords) in done: continue done.append((key, name, new_coords)) new = new_idf.copyidfobject(old_obj) new.Name = "%s_%i" % (name, i) <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from geomeppy.geom.surfaces import get_adjacencies from geomeppy.geom.surfaces import set_coords and context: # Path: geomeppy/geom/surfaces.py # def get_adjacencies(surfaces): # # type: (Idf_MSequence) -> defaultdict # """Create a dictionary mapping surfaces to their adjacent surfaces. # # :param surfaces: A mutable list of surfaces. # :returns: Mapping of surfaces to adjacent surfaces. # """ # adjacencies = defaultdict(list) # type: defaultdict # # find all adjacent surfaces # for s1, s2 in combinations(surfaces, 2): # adjacencies = populate_adjacencies(adjacencies, s1, s2) # for adjacency, polys in adjacencies.items(): # adjacencies[adjacency] = minimal_set(polys) # return adjacencies # # Path: geomeppy/geom/surfaces.py # def set_coords( # surface, # type: EpBunch # coords, # # type: Union[List[Vector3D], List[Tuple[float, float, float]], Polygon3D] # ggr, # type: Union[List, None, Idf_MSequence] # ): # # type: (...) -> None # """Update the coordinates of a surface. # # :param surface: The surface to modify. # :param coords: The new coordinates as lists of [x,y,z] lists. # :param ggr: Global geometry rules. # """ # coords = list(coords) # deduped = [c for i, c in enumerate(coords) if c != coords[(i + 1) % len(coords)]] # poly = Polygon3D(deduped) # poly = poly.normalize_coords(ggr) # coords = [i for vertex in poly for i in vertex] # if len(coords) > 120: # warnings.warn( # "To create surfaces with >120 vertices, ensure you have customised your IDD before running EnergyPlus. " # "https://unmethours.com/question/9343/energy-idf-parsing-error/?answer=9344#post-id-9344" # ) # # find the vertex fields # n_vertices_index = surface.objls.index("Number_of_Vertices") # first_x = n_vertices_index + 1 # X of first coordinate # surface.obj = surface.obj[:first_x] # # set the vertex field values # surface.fieldvalues.extend(coords) which might include code, classes, or functions. Output only the next line.
set_coords(new, new_coords, ggr)
Next line prediction: <|code_start|>"""Module for extracting the geometry from an existing IDF. There is the option to copy: - thermal zone description and geometry - surface construction elements """ def copy_constructions(source_idf, target_idf=None, fname="new.idf"): # type: (IDF, Optional[IDF], str) -> IDF """Extract construction objects from a source IDF and add them to a target IDF or a new IDF. :param source_idf: An IDF to source objects from. :param target_idf: An optional IDF to add objects to. If none is passed, a new IDF is returned. :param fname: A name for the new IDF created if no target IDF is passed in. Default: "new.idf". :returns: Either the target IDF or a new IDF containing the construction objects. """ group = "Surface Construction Elements" <|code_end|> . Use current file imports: (import itertools from typing import Optional # noqa from .idf import EpBunch, Idf_MSequence, IDF, new_idf # noqa) and context including class names, function names, or small code snippets from other files: # Path: geomeppy/idf.py # def new_idf(fname): # def intersect_match(self): # def intersect(self): # def match(self): # def translate_to_origin(self): # def translate(self, vector): # def rotate(self, angle, anchor=None): # def scale(self, factor, anchor=None, axes="xy"): # def set_default_constructions(self): # def bounding_box(self): # def centroid(self): # def getsurfaces(self, surface_type=""): # def getsubsurfaces(self, surface_type=""): # def getshadingsurfaces(self, surface_type=""): # def set_wwr( # self, wwr=0.2, construction=None, force=False, wwr_map={}, orientation=None # ): # def view_model(self, test=False): # def to_obj(self, fname=None, mtllib=None): # def add_block(self, *args, **kwargs): # def add_shading_block(self, *args, **kwargs): # def add_zone(self, zone): # class IDF(PatchedIDF): . Output only the next line.
target_idf = target_idf or new_idf(fname)
Predict the next line after this snippet: <|code_start|>"""Tests for polygons.""" def test_polygon_repr(): # type: () -> None s2D = Polygon2D([(0, 0), (2, 0), (2, 0), (0, 0)]) # vertical assert eval(repr(s2D)) == s2D <|code_end|> using the current file's imports: from geomeppy.geom.polygons import ( break_polygons, Polygon2D, Polygon3D, Vector2D, Vector3D, ) from geomeppy.geom.segments import Segment from geomeppy.utilities import almostequal and any relevant context from other files: # Path: geomeppy/geom/polygons.py # class Polygon(Clipper2D, MutableSequence): # class Polygon2D(Polygon): # class Polygon3D(Clipper3D, Polygon): # def n_dims(self): # def vector_class(self): # def normal_vector(self): # def __init__(self, vertices): # def __repr__(self): # def __len__(self): # def __delitem__(self, key): # def __getitem__(self, key): # def __setitem__(self, key, value): # def __add__(self, other): # type: (Polygon) -> Union[None, Polygon] # def __sub__(self, other): # def insert(self, key, value): # def area(self): # def bounding_box(self): # def buffer(self, distance=None, join_style=2): # def centroid(self): # def edges(self): # def invert_orientation(self): # def is_convex(self): # def points_matrix(self): # def vertices_list(self): # def xs(self): # def ys(self): # def zs(self): # def __eq__(self, other): # def normal_vector(self): # def project_to_3D(self, example3d): # def zs(self): # def __eq__(self, other): # def zs(self): # def normal_vector(self): # def distance(self): # def projection_axis(self): # def is_horizontal(self): # def is_clockwise(self, viewpoint): # def is_coplanar(self, other): # def outside_point(self, entry_direction="counterclockwise"): # def order_points(self, starting_position): # def project_to_2D(self): # def normalize_coords(self, ggr): # def from_wkt(self, wkt_poly): # def break_polygons(poly, hole): # def section(first, last, coords): # def project(pt, proj_axis): # def project_inv( # pt, proj_axis, a, v # ): # type: (np.ndarray, int, np.float64, Vector3D) -> Any # def project_to_2D(vertices, proj_axis): # def project_to_3D( # vertices, proj_axis, a, v # ): # type: (np.ndarray, int, np.float64, Vector3D) -> List[Tuple[np.float64, np.float64, np.float64]] # def normalize_coords( # poly, outside_pt, ggr=None # ): # type: (Polygon3D, Vector3D, Union[List, None, Idf_MSequence]) -> Polygon3D # def set_entry_direction(poly, outside_pt, ggr=None): # def set_starting_position(poly, ggr=None): # def intersect(poly1, poly2): # def is_hole(surface, possible_hole): # def bounding_box(polygons): # def is_convex_polygon(polygon): # noqa # # Path: geomeppy/geom/segments.py # class Segment(object): # """Line segment in 3D.""" # # def __init__(self, *vertices): # # type: (*Vector3D) -> None # self.vertices = vertices # self.p1 = vertices[0] # self.p2 = vertices[1] # # def __repr__(self): # # type: () -> str # class_name = type(self).__name__ # return "{}({}, {})".format(class_name, self.p1, self.p2) # # def __neg__(self): # # type: () -> Segment # return Segment(self.p2, self.p1) # # def __iter__(self): # # type: () -> Iterator # return (i for i in self.vertices) # # def __eq__(self, other): # # type: (Any) -> bool # return self.__dict__ == other.__dict__ # # def _is_collinear(self, other): # # type: (Segment) -> bool # """Test if a segment is collinear with another segment # # :param other: The other segment. # :return: True if the segments are collinear else False. # """ # if almostequal(other, self) or almostequal(other, -self): # return True # a = self.p1 - other.p1 # b = self.p1 - other.p2 # angle_between = a.cross(b) # if almostequal(angle_between, Vector3D(0, 0, 0)): # return True # a = self.p2 - other.p1 # b = self.p2 - other.p2 # angle_between = a.cross(b) # if almostequal(angle_between, Vector3D(0, 0, 0)): # return True # return False # # def _on_poly_edge(self, poly): # # type: (Polygon3D) -> bool # """Test if segment lies on any edge of a polygon # # :param poly: The polygon to test against. # :returns: True if segment lies on any edge of the polygon, else False. # """ # for edge in poly.edges: # if self._is_collinear(edge): # return True # return False # # Path: geomeppy/utilities.py # def almostequal(first, second, places=7): # # type: (Any, Any, int) -> bool # """Tests a range of types for near equality.""" # try: # # try converting to float first # first = float(first) # second = float(second) # # test floats for near-equality # if round(abs(second - first), places) != 0: # return False # else: # return True # except ValueError: # # handle non-float types # return str(first) == str(second) # except TypeError: # # handle iterables # return all([almostequal(a, b, places) for a, b in zip(first, second)]) . Output only the next line.
s3D = Polygon3D([(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0)]) # vertical
Predict the next line after this snippet: <|code_start|> """ childpid = os.fork() root = kwargs.get("root", "/mnt/sysimage") if not childpid: if not root in ["","/"]: os.chroot(root) os.chdir("/") del(os.environ["LIBUSER_CONF"]) self.admin = libuser.admin() if self.admin.lookupUserByName(user_name): log.error("User %s already exists, not creating.", user_name) os._exit(1) userEnt = self.admin.initUser(user_name) groupEnt = self.admin.initGroup(user_name) if kwargs.get("gid", -1) >= 0: groupEnt.set(libuser.GIDNUMBER, kwargs["gid"]) grpLst = filter(lambda grp: grp, map(self.admin.lookupGroupByName, kwargs.get("groups", []))) userEnt.set(libuser.GIDNUMBER, [groupEnt.get(libuser.GIDNUMBER)[0]] + map(lambda grp: grp.get(libuser.GIDNUMBER)[0], grpLst)) if kwargs.get("homedir", False): userEnt.set(libuser.HOMEDIRECTORY, kwargs["homedir"]) else: <|code_end|> using the current file's imports: import libuser import string import crypt import random import tempfile import os import os.path import pwquality import logging from pyanaconda import iutil from pyanaconda.iutil import strip_accents from pyanaconda.i18n import _ from pyanaconda.constants import PASSWORD_MIN_LEN and any relevant context from other files: # Path: pyanaconda/iutil.py # def augmentEnv(): # def _run_program(argv, root='/', stdin=None, stdout=None, env_prune=None): # def chroot(): # def execWithRedirect(command, argv, stdin=None, stdout=None, # root='/', env_prune=None): # def execWithCapture(command, argv, stdin=None, root='/'): # def execReadlines(command, argv, stdin=None, root='/', env_prune=None): # def queue_lines(out, queue): # def chroot(): # def execConsole(): # def getDirSize(directory): # def getSubdirSize(directory): # def mkdirChain(directory): # def get_active_console(dev="console"): # def isConsoleOnVirtualTerminal(dev="console"): # def strip_markup(text): # def reIPL(ipldev): # def resetRpmDb(): # def parseNfsUrl(nfsurl): # def add_po_path(module, directory): # def setup_translations(module): # def fork_orphan(): # def _run_systemctl(command, service): # def start_service(service): # def stop_service(service): # def restart_service(service): # def service_running(service): # def dracut_eject(device): # def vtActivate(num): # def __init__(self, url=None, protocol="http://", host=None, port="3128", # username=None, password=None): # def parse_url(self): # def parse_components(self): # def dict(self): # def __str__(self): # def getdeepattr(obj, name): # def setdeepattr(obj, name, value): # def strip_accents(s): # def cmp_obj_attrs(obj1, obj2, attr_list): # def dir_tree_map(root, func, files=True, dirs=True): # def chown_dir_tree(root, uid, gid, from_uid_only=None, from_gid_only=None): # def conditional_chown(path, uid, gid, from_uid=None, from_gid=None): # def is_unsupported_hw(): # def _toASCII(s): # def upperASCII(s): # def lowerASCII(s): # def upcase_first_letter(text): # class ProxyStringError(Exception): # class ProxyString(object): # # Path: pyanaconda/iutil.py # def strip_accents(s): # """This function takes arbitrary unicode string # and returns it with all the diacritics removed. # # :param s: arbitrary string # :type s: unicode # # :return: s with diacritics removed # :rtype: unicode # # """ # return ''.join((c for c in unicodedata.normalize('NFD', s) # if unicodedata.category(c) != 'Mn')) # # Path: pyanaconda/constants.py # PASSWORD_MIN_LEN = 6 . Output only the next line.
iutil.mkdirChain(root+'/home')
Here is a snippet: <|code_start|> message = _("Requested password contains " "non-ASCII characters, which are " "not allowed.") valid = False break if valid: try: strength = settings.check(pw, None, user) except pwquality.PWQError as e: # Leave valid alone here: the password is weak but can still # be accepted. # PWQError values are built as a tuple of (int, str) message = e[1] return (valid, strength, message) def guess_username(fullname): fullname = fullname.split() # use last name word (at the end in most of the western countries..) if len(fullname) > 0: username = fullname[-1].decode("utf-8").lower() else: username = u"" # and prefix it with the first name inital if len(fullname) > 1: username = fullname[0].decode("utf-8")[0].lower() + username <|code_end|> . Write the next line using the current file imports: import libuser import string import crypt import random import tempfile import os import os.path import pwquality import logging from pyanaconda import iutil from pyanaconda.iutil import strip_accents from pyanaconda.i18n import _ from pyanaconda.constants import PASSWORD_MIN_LEN and context from other files: # Path: pyanaconda/iutil.py # def augmentEnv(): # def _run_program(argv, root='/', stdin=None, stdout=None, env_prune=None): # def chroot(): # def execWithRedirect(command, argv, stdin=None, stdout=None, # root='/', env_prune=None): # def execWithCapture(command, argv, stdin=None, root='/'): # def execReadlines(command, argv, stdin=None, root='/', env_prune=None): # def queue_lines(out, queue): # def chroot(): # def execConsole(): # def getDirSize(directory): # def getSubdirSize(directory): # def mkdirChain(directory): # def get_active_console(dev="console"): # def isConsoleOnVirtualTerminal(dev="console"): # def strip_markup(text): # def reIPL(ipldev): # def resetRpmDb(): # def parseNfsUrl(nfsurl): # def add_po_path(module, directory): # def setup_translations(module): # def fork_orphan(): # def _run_systemctl(command, service): # def start_service(service): # def stop_service(service): # def restart_service(service): # def service_running(service): # def dracut_eject(device): # def vtActivate(num): # def __init__(self, url=None, protocol="http://", host=None, port="3128", # username=None, password=None): # def parse_url(self): # def parse_components(self): # def dict(self): # def __str__(self): # def getdeepattr(obj, name): # def setdeepattr(obj, name, value): # def strip_accents(s): # def cmp_obj_attrs(obj1, obj2, attr_list): # def dir_tree_map(root, func, files=True, dirs=True): # def chown_dir_tree(root, uid, gid, from_uid_only=None, from_gid_only=None): # def conditional_chown(path, uid, gid, from_uid=None, from_gid=None): # def is_unsupported_hw(): # def _toASCII(s): # def upperASCII(s): # def lowerASCII(s): # def upcase_first_letter(text): # class ProxyStringError(Exception): # class ProxyString(object): # # Path: pyanaconda/iutil.py # def strip_accents(s): # """This function takes arbitrary unicode string # and returns it with all the diacritics removed. # # :param s: arbitrary string # :type s: unicode # # :return: s with diacritics removed # :rtype: unicode # # """ # return ''.join((c for c in unicodedata.normalize('NFD', s) # if unicodedata.category(c) != 'Mn')) # # Path: pyanaconda/constants.py # PASSWORD_MIN_LEN = 6 , which may include functions, classes, or code. Output only the next line.
username = strip_accents(username).encode("utf-8")
Here is a snippet: <|code_start|> pwquality will raise a PWQError on a weak password, which, honestly, is kind of dumb behavior. A weak password isn't exceptional, it's what we're asking about! Anyway, this function does not raise PWQError. If the password fails the PWQSettings conditions, the first member of the return tuple will be False and the second member of the tuple will be 0. :param pw: the password to check :type pw: string :param user: the username for which the password is being set. If no username is provided, "root" will be used. Use user=None to disable the username check. :type user: string :param settings: an optional PWQSettings object :type settings: pwquality.PWQSettings :returns: A tuple containing (bool(valid), int(score), str(message)) :rtype: tuple """ valid = True message = None strength = 0 if settings is None: # Generate a default PWQSettings once and save it as a member of this function if not hasattr(validatePassword, "pwqsettings"): validatePassword.pwqsettings = pwquality.PWQSettings() validatePassword.pwqsettings.read_config() <|code_end|> . Write the next line using the current file imports: import libuser import string import crypt import random import tempfile import os import os.path import pwquality import logging from pyanaconda import iutil from pyanaconda.iutil import strip_accents from pyanaconda.i18n import _ from pyanaconda.constants import PASSWORD_MIN_LEN and context from other files: # Path: pyanaconda/iutil.py # def augmentEnv(): # def _run_program(argv, root='/', stdin=None, stdout=None, env_prune=None): # def chroot(): # def execWithRedirect(command, argv, stdin=None, stdout=None, # root='/', env_prune=None): # def execWithCapture(command, argv, stdin=None, root='/'): # def execReadlines(command, argv, stdin=None, root='/', env_prune=None): # def queue_lines(out, queue): # def chroot(): # def execConsole(): # def getDirSize(directory): # def getSubdirSize(directory): # def mkdirChain(directory): # def get_active_console(dev="console"): # def isConsoleOnVirtualTerminal(dev="console"): # def strip_markup(text): # def reIPL(ipldev): # def resetRpmDb(): # def parseNfsUrl(nfsurl): # def add_po_path(module, directory): # def setup_translations(module): # def fork_orphan(): # def _run_systemctl(command, service): # def start_service(service): # def stop_service(service): # def restart_service(service): # def service_running(service): # def dracut_eject(device): # def vtActivate(num): # def __init__(self, url=None, protocol="http://", host=None, port="3128", # username=None, password=None): # def parse_url(self): # def parse_components(self): # def dict(self): # def __str__(self): # def getdeepattr(obj, name): # def setdeepattr(obj, name, value): # def strip_accents(s): # def cmp_obj_attrs(obj1, obj2, attr_list): # def dir_tree_map(root, func, files=True, dirs=True): # def chown_dir_tree(root, uid, gid, from_uid_only=None, from_gid_only=None): # def conditional_chown(path, uid, gid, from_uid=None, from_gid=None): # def is_unsupported_hw(): # def _toASCII(s): # def upperASCII(s): # def lowerASCII(s): # def upcase_first_letter(text): # class ProxyStringError(Exception): # class ProxyString(object): # # Path: pyanaconda/iutil.py # def strip_accents(s): # """This function takes arbitrary unicode string # and returns it with all the diacritics removed. # # :param s: arbitrary string # :type s: unicode # # :return: s with diacritics removed # :rtype: unicode # # """ # return ''.join((c for c in unicodedata.normalize('NFD', s) # if unicodedata.category(c) != 'Mn')) # # Path: pyanaconda/constants.py # PASSWORD_MIN_LEN = 6 , which may include functions, classes, or code. Output only the next line.
validatePassword.pwqsettings.minlen = PASSWORD_MIN_LEN
Given snippet: <|code_start|># Chris Lumens <clumens@redhat.com> # __all__ = ["FakeDiskLabel", "FakeDisk", "getDisks", "isLocalDisk", "size_str"] class FakeDiskLabel(object): def __init__(self, free=0): self.free = free class FakeDisk(object): def __init__(self, name, size=0, free=0, partitioned=True, vendor=None, model=None, serial=None, removable=False): self.name = name self.size = size self.format = FakeDiskLabel(free=free) self.partitioned = partitioned self.vendor = vendor self.model = model self.serial = serial self.removable = removable @property def description(self): return "%s %s" % (self.vendor, self.model) def getDisks(devicetree, fake=False): if not fake: devices = devicetree.devices <|code_end|> , continue by predicting the next line. Consider current file imports: from blivet.devices import MultipathDevice, iScsiDiskDevice from blivet.size import Size from pyanaconda.flags import flags and context: # Path: pyanaconda/flags.py # class Flags(object): # class BootArgs(OrderedDict): # def __setattr__(self, attr, val): # def get(self, attr, val=None): # def set_cmdline_bool(self, flag): # def __init__(self, read_cmdline=True): # def read_cmdline(self): # def __init__(self, cmdline=None, files=None): # def read(self, filenames): # def readstr(self, cmdline): # def getbool(self, arg, default=False): # def can_touch_runtime_system(msg, touch_live=False): which might include code, classes, or functions. Output only the next line.
if not flags.imageInstall:
Given the following code snippet before the placeholder: <|code_start|> :rtype: None """ if lang: lang.lang = locale os.environ["LANG"] = locale def get_english_name(locale): """ Function returning english name for the given locale. :param locale: locale to return english name for :type locale: str :return: english name for the locale or empty string if unknown :rtype: st :raise InvalidLocaleSpec: if an invalid locale is given (see LANGCODE_RE) """ parts = parse_langcode(locale) if "language" not in parts: raise InvalidLocaleSpec("'%s' is not a valid locale" % locale) name = langtable.language_name(languageId=parts["language"], territoryId=parts.get("territory", ""), scriptId=parts.get("script", ""), languageIdQuery="en") <|code_end|> , predict the next line using imports from the current file: import gettext import os import re import langtable import glob import logging from pyanaconda.iutil import upcase_first_letter and context including class names, function names, and sometimes code from other files: # Path: pyanaconda/iutil.py # def upcase_first_letter(text): # """ # Helper function that upcases the first letter of the string. Python's # standard string.capitalize() not only upcases the first letter but also # lowercases all the others. string.title() capitalizes all words in the # string. # # :type text: either a str or unicode object # :return: the given text with the first letter upcased # :rtype: str or unicode (depends on the input) # # """ # # if not text: # # cannot change anything # return text # elif len(text) == 1: # return text.upper() # else: # return text[0].upper() + text[1:] . Output only the next line.
return upcase_first_letter(name)
Given the following code snippet before the placeholder: <|code_start|> self._queue.put(('post', None)) def do_transaction(base, queue): try: display = PayloadRPMDisplay(queue) base.do_transaction(display=display) except BaseException as e: log.error('The transaction process has ended abruptly') log.info(e) queue.put(('quit', str(e))) class DNFPayload(packaging.PackagePayload): def __init__(self, data): packaging.PackagePayload.__init__(self, data) if rpm is None or dnf is None: raise packaging.PayloadError("unsupported payload type") self._base = None self._required_groups = [] self._required_pkgs = [] self._configure() def _add_repo(self, ksrepo): repo = self._base.build_repo(ksrepo.name) url = ksrepo.baseurl mirrorlist = ksrepo.mirrorlist if url: repo.baseurl = [url] if mirrorlist: repo.mirrorlist = mirrorlist <|code_end|> , predict the next line using imports from the current file: from blivet.size import Size from pyanaconda.flags import flags from pyanaconda.i18n import _ from pyanaconda.progress import progressQ import itertools import logging import multiprocessing import pyanaconda.constants as constants import pyanaconda.errors as errors import pyanaconda.packaging as packaging import sys import time import dnf import dnf.exceptions import dnf.output import rpm and context including class names, function names, and sometimes code from other files: # Path: pyanaconda/flags.py # class Flags(object): # class BootArgs(OrderedDict): # def __setattr__(self, attr, val): # def get(self, attr, val=None): # def set_cmdline_bool(self, flag): # def __init__(self, read_cmdline=True): # def read_cmdline(self): # def __init__(self, cmdline=None, files=None): # def read(self, filenames): # def readstr(self, cmdline): # def getbool(self, arg, default=False): # def can_touch_runtime_system(msg, touch_live=False): . Output only the next line.
repo.sslverify = not (ksrepo.noverifyssl or flags.noverifyssl)
Given the code snippet: <|code_start|> if fileName[-3:] != ".py" and fileName[-4:-1] != ".py": continue mainName = fileName.split(".")[0] if done.has_key(mainName): continue done[mainName] = 1 try: found = imputil.imp.find_module(mainName) except ImportError as err: log.warning ("module import of %s failed: %s, %s", mainName, sys.exc_type, err) continue try: loaded = imputil.imp.load_module(mainName, found[0], found[1], found[2]) obj = loaded.InstallClass if obj.__dict__.has_key('sortPriority'): sortOrder = obj.sortPriority else: sortOrder = 0 if obj.hidden == 0 or showHidden == 1: lst.append(((obj.name, obj), sortOrder)) except (ImportError, AttributeError) as err: log.warning ("module import of %s failed: %s, %s", mainName, sys.exc_type, err) <|code_end|> , generate the next line using the imports in this file: from distutils.sysconfig import get_python_lib from blivet.partspec import PartSpec from blivet.devicelibs import swap from blivet.platform import platform from pyanaconda.flags import flags from pyanaconda.kickstart import getAvailableDiskSpace import os, sys import imputil import logging and context (functions, classes, or occasionally code) from other files: # Path: pyanaconda/flags.py # class Flags(object): # class BootArgs(OrderedDict): # def __setattr__(self, attr, val): # def get(self, attr, val=None): # def set_cmdline_bool(self, flag): # def __init__(self, read_cmdline=True): # def read_cmdline(self): # def __init__(self, cmdline=None, files=None): # def read(self, filenames): # def readstr(self, cmdline): # def getbool(self, arg, default=False): # def can_touch_runtime_system(msg, touch_live=False): # # Path: pyanaconda/kickstart.py # def getAvailableDiskSpace(storage): # """ # Get overall disk space available on disks we may use (not free space on the # disks, but overall space on the disks). # # :param storage: blivet.Blivet instance # :return: overall disk space available in MB # :rtype: int # # """ # # disk_space = 0 # for disk in storage.disks: # if not storage.config.clearPartDisks or \ # disk.name in storage.config.clearPartDisks: # disk_space += disk.size # # return disk_space . Output only the next line.
if flags.debug: raise
Predict the next line for this snippet: <|code_start|> @property def l10n_domain(self): if self._l10n_domain is None: raise RuntimeError("Localization domain for '%s' not set." % self.name) return self._l10n_domain def setPackageSelection(self, anaconda): pass def getBackend(self): # The default is to return None here, which means anaconda should # use live or yum (whichever can be detected). This method is # provided as a way for other products to specify their own. return None def setDefaultPartitioning(self, storage): autorequests = [PartSpec(mountpoint="/", fstype=storage.defaultFSType, size=1024, maxSize=50*1024, grow=True, btr=True, lv=True, thin=True, encrypted=True), PartSpec(mountpoint="/home", fstype=storage.defaultFSType, size=500, grow=True, requiredSpace=50*1024, btr=True, lv=True, thin=True, encrypted=True)] bootreqs = platform.setDefaultPartitioning() if bootreqs: autorequests.extend(bootreqs) <|code_end|> with the help of current file imports: from distutils.sysconfig import get_python_lib from blivet.partspec import PartSpec from blivet.devicelibs import swap from blivet.platform import platform from pyanaconda.flags import flags from pyanaconda.kickstart import getAvailableDiskSpace import os, sys import imputil import logging and context from other files: # Path: pyanaconda/flags.py # class Flags(object): # class BootArgs(OrderedDict): # def __setattr__(self, attr, val): # def get(self, attr, val=None): # def set_cmdline_bool(self, flag): # def __init__(self, read_cmdline=True): # def read_cmdline(self): # def __init__(self, cmdline=None, files=None): # def read(self, filenames): # def readstr(self, cmdline): # def getbool(self, arg, default=False): # def can_touch_runtime_system(msg, touch_live=False): # # Path: pyanaconda/kickstart.py # def getAvailableDiskSpace(storage): # """ # Get overall disk space available on disks we may use (not free space on the # disks, but overall space on the disks). # # :param storage: blivet.Blivet instance # :return: overall disk space available in MB # :rtype: int # # """ # # disk_space = 0 # for disk in storage.disks: # if not storage.config.clearPartDisks or \ # disk.name in storage.config.clearPartDisks: # disk_space += disk.size # # return disk_space , which may contain function names, class names, or code. Output only the next line.
disk_space = getAvailableDiskSpace(storage)
Given the code snippet: <|code_start|> if not keyboard.vc_keymap: populate_missing_items(keyboard) args = set() args.add("vconsole.keymap=%s" % keyboard.vc_keymap) args.add("vconsole.font=%s" % DEFAULT_VC_FONT) return args def _try_to_load_keymap(keymap): """ Method that tries to load keymap and returns boolean indicating if it was successfull or not. It can be used to test if given string is VConsole keymap or not, but in case it is given valid keymap, IT REALLY LOADS IT!. :type keymap: string :raise KeyboardConfigError: if loadkeys command is not available :return: True if given string was a valid keymap and thus was loaded, False otherwise """ # BUG: systemd-localed should be able to tell us if we are trying to # activate invalid keymap. Then we will be able to get rid of this # fuction ret = 0 try: <|code_end|> , generate the next line using the imports in this file: import types import os import re import shutil import ctypes import gettext import threading import logging from collections import namedtuple from pyanaconda import iutil from pyanaconda import flags from pyanaconda.safe_dbus import dbus_call_safe_sync, dbus_get_property_safe_sync from pyanaconda.safe_dbus import DBUS_SYSTEM_BUS_ADDR, DBusPropertyError from pyanaconda.constants import DEFAULT_VC_FONT, DEFAULT_KEYBOARD, THREAD_XKL_WRAPPER_INIT from pyanaconda.threads import threadMgr, AnacondaThread from gi.repository import Xkl, Gio, GLib from gi.repository import GdkX11 and context (functions, classes, or occasionally code) from other files: # Path: pyanaconda/iutil.py # def augmentEnv(): # def _run_program(argv, root='/', stdin=None, stdout=None, env_prune=None): # def chroot(): # def execWithRedirect(command, argv, stdin=None, stdout=None, # root='/', env_prune=None): # def execWithCapture(command, argv, stdin=None, root='/'): # def execReadlines(command, argv, stdin=None, root='/', env_prune=None): # def queue_lines(out, queue): # def chroot(): # def execConsole(): # def getDirSize(directory): # def getSubdirSize(directory): # def mkdirChain(directory): # def get_active_console(dev="console"): # def isConsoleOnVirtualTerminal(dev="console"): # def strip_markup(text): # def reIPL(ipldev): # def resetRpmDb(): # def parseNfsUrl(nfsurl): # def add_po_path(module, directory): # def setup_translations(module): # def fork_orphan(): # def _run_systemctl(command, service): # def start_service(service): # def stop_service(service): # def restart_service(service): # def service_running(service): # def dracut_eject(device): # def vtActivate(num): # def __init__(self, url=None, protocol="http://", host=None, port="3128", # username=None, password=None): # def parse_url(self): # def parse_components(self): # def dict(self): # def __str__(self): # def getdeepattr(obj, name): # def setdeepattr(obj, name, value): # def strip_accents(s): # def cmp_obj_attrs(obj1, obj2, attr_list): # def dir_tree_map(root, func, files=True, dirs=True): # def chown_dir_tree(root, uid, gid, from_uid_only=None, from_gid_only=None): # def conditional_chown(path, uid, gid, from_uid=None, from_gid=None): # def is_unsupported_hw(): # def _toASCII(s): # def upperASCII(s): # def lowerASCII(s): # def upcase_first_letter(text): # class ProxyStringError(Exception): # class ProxyString(object): # # Path: pyanaconda/flags.py # class Flags(object): # class BootArgs(OrderedDict): # def __setattr__(self, attr, val): # def get(self, attr, val=None): # def set_cmdline_bool(self, flag): # def __init__(self, read_cmdline=True): # def read_cmdline(self): # def __init__(self, cmdline=None, files=None): # def read(self, filenames): # def readstr(self, cmdline): # def getbool(self, arg, default=False): # def can_touch_runtime_system(msg, touch_live=False): # # Path: pyanaconda/constants.py # DEFAULT_VC_FONT = "latarcyrheb-sun16" # # DEFAULT_KEYBOARD = "us" # # THREAD_XKL_WRAPPER_INIT = "AnaXklWrapperInitThread" # # Path: pyanaconda/threads.py # class ThreadManager(object): # class AnacondaThread(threading.Thread): # def __init__(self): # def __call__(self): # def add(self, obj): # def remove(self, name): # def exists(self, name): # def get(self, name): # def wait(self, name): # def wait_all(self): # def set_error(self, name, *exc_info): # def get_error(self, name): # def any_errors(self): # def raise_error(self, name): # def in_main_thread(self): # def running(self): # def names(self): # def __init__(self, *args, **kwargs): # def run(self, *args, **kwargs): # def initThreading(): . Output only the next line.
ret = iutil.execWithRedirect("loadkeys", [keymap])