Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|># the Free Software Foundation; either version 2 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # dummy redirect urlpatterns = patterns('', url(r'^admin_tools/', include('admin_tools.urls')), ) statistics_modules = get_statistics_modules() for mod in statistics_modules: admin_stats = mod() urlpatterns += patterns('', url(r'^statistics/%s/' % admin_stats.prefix, include(admin_stats.get_urls())), ) use_export_chart = hasattr(settings, 'JAMES_CHART_EXPORT_JS_URL') if len(statistics_modules) > 0 and use_export_chart: urlpatterns += patterns('djangojames.statistics.views', <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls.defaults import patterns, include, url from djangojames.admin_dashboard import get_statistics_modules from django.conf import settings and context (classes, functions, sometimes code) from other files: # Path: djangojames/admin_dashboard.py # def get_statistics_modules(): # mod_clss = getattr( # settings, # 'JAMES_ADMIN_STATISTICS_MODULES', # None # ) # mods = [] # if mod_clss: # for mod_cls in mod_clss: # mod, inst = mod_cls.rsplit('.', 1) # mod = import_module(mod) # mods.append(getattr(mod, inst)) # # return mods . Output only the next line.
url(r'^statistics/export/$', 'export_highchart_svg', name='export-highchart'),
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # # Atizo - The Open Innovation Platform # http://www.atizo.com/ # # Copyright (c) 2008-2010 Atizo AG. All rights reserved. # # 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 2 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # def admin_export_as_csv(modeladmin, request, queryset): return queryset_to_csv_response(slugify(modeladmin.__class__.__name__), queryset) admin_export_as_csv.short_description = "Auswahl als CSV Exportieren" <|code_end|> , predict the next line using imports from the current file: from django.template.defaultfilters import slugify from django.contrib import admin from djangojames.models.export import queryset_to_csv_response and context including class names, function names, and sometimes code from other files: # Path: djangojames/models/export.py # def queryset_to_csv_response(filename, queryset): # if len(queryset) > 0: # response = HttpResponse(mimetype='text/csv') # file_name = slugify(filename) # response['Content-Disposition'] = 'attachment; filename=%s-export.csv' % file_name # writer = csv.writer(response) # # i = 0 # for inst in queryset: # i += 1 # dict = humanized_content_dict_for_model_instance(inst) # if i == 1: # writer.writerow([smart_str(k) for k in dict.keys()]) # writer.writerow([smart_str(c) for c in dict.values()]) # # return response # else: # return None . Output only the next line.
admin.site.add_action(admin_export_as_csv)
Here is a 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # SELECTION_NAME = _(u'- Bitte wählen -') NO_SELECTION = _(u'- Keine Auswahl -') def sort_choice(choice, head_tuple=None): c = list(copy(choice)) m = unaccented_map() c.sort(key=lambda x: unicode(x[1]).translate(m)) if head_tuple: l = [] l.extend(c) head = list(head_tuple) head.reverse() for k in head: l.insert(0,k) return l return c def get_display(choice, key): for c in choice: if c[0] == key: return unicode(c[1]) <|code_end|> . Write the next line using the current file imports: from djangojames.string import unaccented_map from copy import copy from django.utils.translation import ugettext_lazy as _ and context from other files: # Path: djangojames/string.py # class unaccented_map(dict): # """ # Translation dictionary. Translation entries are added to this dictionary as needed # """ # # def mapchar(self, key): # """ # Maps a unicode character code (the key) to a replacement code (either a character code or a unicode string). # """ # ch = self.get(key) # if ch is not None: # return ch # de = unicodedata.decomposition(unichr(key)) # if de: # try: # ch = int(de.split(None, 1)[0], 16) # except (IndexError, ValueError): # ch = key # else: # ch = CHAR_REPLACEMENT.get(key, key) # self[key] = ch # return ch # # if sys.version >= "2.5": # # use __missing__ where available # __missing__ = mapchar # else: # # otherwise, use standard __getitem__ hook (this is slower, # # since it's called for each character) # __getitem__ = mapchar , which may include functions, classes, or code. Output only the next line.
return ''
Based on the snippet: <|code_start|> ('auth', {'secret': b'secret'}, b'AUTH\n' + struct.pack('>l', 6) + b'secret'), ('subscribe', {'topic_name': 'test_topic', 'channel_name': 'test_channel'}, b'SUB test_topic test_channel\n'), ('finish', {'message_id': 'test'}, b'FIN test\n'), ('finish', {'message_id': u'\u2020est \xfcn\xee\xe7\xf8\u2202\xe9'}, b'FIN \xe2\x80\xa0est \xc3\xbcn\xc3\xae\xc3\xa7\xc3\xb8\xe2\x88\x82\xc3\xa9\n'), ('requeue', {'message_id': 'test'}, b'REQ test 0\n'), ('requeue', {'message_id': 'test', 'timeout': 60}, b'REQ test 60\n'), ('touch', {'message_id': 'test'}, b'TOUCH test\n'), ('ready', {'count': 100}, b'RDY 100\n'), ('nop', {}, b'NOP\n'), ('publish', {'topic_name': 'test', 'data': MSGS[0]}, b'PUB test\n' + struct.pack('>l', len(MSGS[0])) + MSGS[0]), <|code_end|> , predict the immediate next line with the help of imports: import json import struct import pytest import six from gnsq import protocol as nsq and context (classes, functions, sometimes code) from other files: # Path: gnsq/protocol.py # MAGIC_V2 = b' V2' # NEWLINE = b'\n' # SPACE = b' ' # EMPTY = b'' # HEARTBEAT = b'_heartbeat_' # OK = b'OK' # IDENTIFY = b'IDENTIFY' # AUTH = b'AUTH' # SUB = b'SUB' # PUB = b'PUB' # MPUB = b'MPUB' # DPUB = b'DPUB' # RDY = b'RDY' # FIN = b'FIN' # REQ = b'REQ' # TOUCH = b'TOUCH' # CLS = b'CLS' # NOP = b'NOP' # FRAME_TYPE_RESPONSE = 0 # FRAME_TYPE_ERROR = 1 # FRAME_TYPE_MESSAGE = 2 # VALID_NAME_RE = re.compile(r'^[\.a-zA-Z0-9_-]+(#ephemeral)?$') # def _valid_name(name): # def valid_topic_name(topic): # def valid_channel_name(channel): # def assert_valid_topic_name(topic): # def assert_valid_channel_name(channel): # def unpack_size(data): # def unpack_response(data): # def unpack_message(data): # def _packsize(data): # def _packbody(body): # def _encode_param(data): # def _command(cmd, body, *params): # def identify(data): # def auth(secret): # def subscribe(topic_name, channel_name): # def publish(topic_name, data): # def multipublish_body(messages): # def multipublish(topic_name, messages): # def deferpublish(topic_name, data, delay_ms): # def ready(count): # def finish(message_id): # def requeue(message_id, timeout=0): # def touch(message_id): # def close(): # def nop(): . Output only the next line.
('multipublish',
Given snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import class CompressionSocket(object): def __init__(self, socket): self._socket = socket self._bootstrapped = None def __getattr__(self, name): return getattr(self._socket, name) <|code_end|> , continue by predicting the next line. Consider current file imports: from errno import EWOULDBLOCK from gnsq.errors import NSQSocketError and context: # Path: gnsq/errors.py # class NSQSocketError(socket.error, NSQException): # pass which might include code, classes, or functions. Output only the next line.
def bootstrap(self, data):
Predict the next line after this snippet: <|code_start|> try: self.socket = socket.create_connection( address=(self.address, self.port), timeout=self.timeout, ) except socket.error as error: six.raise_from(NSQSocketError(*error.args), error) def read(self, size): while len(self.buffer) < size: self.ensure_connection() try: packet = self.socket.recv(self.buffer_size) except socket.error as error: if error.errno in (EDEADLK, EAGAIN, EWOULDBLOCK): gevent.sleep() continue six.raise_from(NSQSocketError(*error.args), error) if not packet: self.close() self.buffer += packet data = self.buffer[:size] self.buffer = self.buffer[size:] <|code_end|> using the current file's imports: from mmap import PAGESIZE from errno import ENOTCONN, EDEADLK, EAGAIN, EWOULDBLOCK from gevent import socket from gevent.lock import Semaphore from gevent.ssl import SSLSocket, PROTOCOL_TLSv1_2, CERT_NONE from gnsq.errors import NSQSocketError from .snappy import SnappySocket from .defalte import DefalteSocket import six import gevent and any relevant context from other files: # Path: gnsq/errors.py # class NSQSocketError(socket.error, NSQException): # pass # # Path: gnsq/stream/defalte.py # class DefalteSocket(CompressionSocket): # def __init__(self, socket, level): # wbits = -zlib.MAX_WBITS # self._decompressor = zlib.decompressobj(wbits) # self._compressor = zlib.compressobj(level, zlib.DEFLATED, wbits) # super(DefalteSocket, self).__init__(socket) # # def compress(self, data): # data = self._compressor.compress(data) # return data + self._compressor.flush(zlib.Z_SYNC_FLUSH) # # def decompress(self, data): # return self._decompressor.decompress(data) # # def close(self): # self._socket.sendall(self._compressor.flush(zlib.Z_FINISH)) # self._socket.close() . Output only the next line.
return data
Using the snippet: <|code_start|> if not packet: self.close() self.buffer += packet data = self.buffer[:size] self.buffer = self.buffer[size:] return data def send(self, data): self.ensure_connection() with self.lock: try: return self.socket.sendall(data) except socket.error as error: six.raise_from(NSQSocketError(*error.args), error) def consume_buffer(self): data = self.buffer self.buffer = b'' return data def close(self): if not self.is_connected: return socket = self.socket self.socket = None <|code_end|> , determine the next line of code. You have imports: from mmap import PAGESIZE from errno import ENOTCONN, EDEADLK, EAGAIN, EWOULDBLOCK from gevent import socket from gevent.lock import Semaphore from gevent.ssl import SSLSocket, PROTOCOL_TLSv1_2, CERT_NONE from gnsq.errors import NSQSocketError from .snappy import SnappySocket from .defalte import DefalteSocket import six import gevent and context (class names, function names, or code) available: # Path: gnsq/errors.py # class NSQSocketError(socket.error, NSQException): # pass # # Path: gnsq/stream/defalte.py # class DefalteSocket(CompressionSocket): # def __init__(self, socket, level): # wbits = -zlib.MAX_WBITS # self._decompressor = zlib.decompressobj(wbits) # self._compressor = zlib.compressobj(level, zlib.DEFLATED, wbits) # super(DefalteSocket, self).__init__(socket) # # def compress(self, data): # data = self._compressor.compress(data) # return data + self._compressor.flush(zlib.Z_SYNC_FLUSH) # # def decompress(self, data): # return self._decompressor.decompress(data) # # def close(self): # self._socket.sendall(self._compressor.flush(zlib.Z_FINISH)) # self._socket.close() . Output only the next line.
self.buffer = b''
Based on the snippet: <|code_start|># html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} html_use_index = False # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. <|code_end|> , predict the immediate next line with the help of imports: import os import sys from gnsq import __version__ and context (classes, functions, sometimes code) from other files: # Path: gnsq/version.py . Output only the next line.
htmlhelp_basename = 'gnsqdoc'
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import USERAGENT = 'gnsq/{}'.format(__version__) def _encode(value): if isinstance(value, bytes): return value return value.encode('utf-8') def _encode_dict(value): if value is None: <|code_end|> , generate the next line using the imports in this file: import json import urllib3 from .errors import NSQHttpError from .version import __version__ and context (functions, classes, or occasionally code) from other files: # Path: gnsq/errors.py # class NSQHttpError(NSQException): # pass # # Path: gnsq/version.py . Output only the next line.
return None
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import USERAGENT = 'gnsq/{}'.format(__version__) def _encode(value): if isinstance(value, bytes): return value return value.encode('utf-8') def _encode_dict(value): if value is None: <|code_end|> , generate the next line using the imports in this file: import json import urllib3 from .errors import NSQHttpError from .version import __version__ and context (functions, classes, or occasionally code) from other files: # Path: gnsq/errors.py # class NSQHttpError(NSQException): # pass # # Path: gnsq/version.py . Output only the next line.
return None
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import class SnappySocket(CompressionSocket): def __init__(self, socket): self._decompressor = snappy.StreamDecompressor() <|code_end|> . Write the next line using the current file imports: import snappy from .compression import CompressionSocket and context from other files: # Path: gnsq/stream/compression.py # class CompressionSocket(object): # def __init__(self, socket): # self._socket = socket # self._bootstrapped = None # # def __getattr__(self, name): # return getattr(self._socket, name) # # def bootstrap(self, data): # if not data: # return # self._bootstrapped = self.decompress(data) # # def recv(self, size): # if self._bootstrapped: # data = self._bootstrapped # self._bootstrapped = None # return data # # chunk = self._socket.recv(size) # if not chunk: # return chunk # # uncompressed = self.decompress(chunk) # if not uncompressed: # raise NSQSocketError(EWOULDBLOCK, 'Operation would block') # # return uncompressed # # def sendall(self, data): # self._socket.sendall(self.compress(data)) , which may include functions, classes, or code. Output only the next line.
self._compressor = snappy.StreamCompressor()
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import class DefalteSocket(CompressionSocket): def __init__(self, socket, level): wbits = -zlib.MAX_WBITS self._decompressor = zlib.decompressobj(wbits) self._compressor = zlib.compressobj(level, zlib.DEFLATED, wbits) <|code_end|> , predict the immediate next line with the help of imports: import zlib from .compression import CompressionSocket and context (classes, functions, sometimes code) from other files: # Path: gnsq/stream/compression.py # class CompressionSocket(object): # def __init__(self, socket): # self._socket = socket # self._bootstrapped = None # # def __getattr__(self, name): # return getattr(self._socket, name) # # def bootstrap(self, data): # if not data: # return # self._bootstrapped = self.decompress(data) # # def recv(self, size): # if self._bootstrapped: # data = self._bootstrapped # self._bootstrapped = None # return data # # chunk = self._socket.recv(size) # if not chunk: # return chunk # # uncompressed = self.decompress(chunk) # if not uncompressed: # raise NSQSocketError(EWOULDBLOCK, 'Operation would block') # # return uncompressed # # def sendall(self, data): # self._socket.sendall(self.compress(data)) . Output only the next line.
super(DefalteSocket, self).__init__(socket)
Continue the code snippet: <|code_start|> @pytest.mark.parametrize('name,good', [ ('valid_name', True), ('invalid name with space', False), ('invalid_name_due_to_length_this_is_' + (4 * 'really_') + 'long', False), ('test-with_period.', True), ('test#ephemeral', True), ('test:ephemeral', False), ]) def test_topic_names(name, good): assert nsq.valid_topic_name(name) == good @pytest.mark.parametrize('name,good', [ ('test', True), ('test-with_period.', True), ('test#ephemeral', True), ('invalid_name_due_to_length_this_is_' + (4 * 'really_') + 'long', False), ('invalid name with space', False), ]) def test_channel_names(name, good): assert nsq.valid_channel_name(name) == good <|code_end|> . Use current file imports: import pytest from six.moves import range from gnsq import BackoffTimer from gnsq import protocol as nsq and context (classes, functions, or code) from other files: # Path: gnsq/backofftimer.py # class BackoffTimer(object): # def __init__(self, ratio=1, max_interval=None, min_interval=None): # self.c = 0 # self.ratio = ratio # # self.max_interval = max_interval # self.min_interval = min_interval # # def is_reset(self): # return self.c == 0 # # def reset(self): # self.c = 0 # return self # # def success(self): # self.c = max(self.c - 1, 0) # return self # # def failure(self): # self.c += 1 # return self # # def get_interval(self): # k = pow(2, self.c) - 1 # interval = random.random() * k * self.ratio # # if self.max_interval is not None: # interval = min(interval, self.max_interval) # # if self.min_interval is not None: # interval = max(interval, self.min_interval) # # return interval # # Path: gnsq/protocol.py # MAGIC_V2 = b' V2' # NEWLINE = b'\n' # SPACE = b' ' # EMPTY = b'' # HEARTBEAT = b'_heartbeat_' # OK = b'OK' # IDENTIFY = b'IDENTIFY' # AUTH = b'AUTH' # SUB = b'SUB' # PUB = b'PUB' # MPUB = b'MPUB' # DPUB = b'DPUB' # RDY = b'RDY' # FIN = b'FIN' # REQ = b'REQ' # TOUCH = b'TOUCH' # CLS = b'CLS' # NOP = b'NOP' # FRAME_TYPE_RESPONSE = 0 # FRAME_TYPE_ERROR = 1 # FRAME_TYPE_MESSAGE = 2 # VALID_NAME_RE = re.compile(r'^[\.a-zA-Z0-9_-]+(#ephemeral)?$') # def _valid_name(name): # def valid_topic_name(topic): # def valid_channel_name(channel): # def assert_valid_topic_name(topic): # def assert_valid_channel_name(channel): # def unpack_size(data): # def unpack_response(data): # def unpack_message(data): # def _packsize(data): # def _packbody(body): # def _encode_param(data): # def _command(cmd, body, *params): # def identify(data): # def auth(secret): # def subscribe(topic_name, channel_name): # def publish(topic_name, data): # def multipublish_body(messages): # def multipublish(topic_name, messages): # def deferpublish(topic_name, data, delay_ms): # def ready(count): # def finish(message_id): # def requeue(message_id, timeout=0): # def touch(message_id): # def close(): # def nop(): . Output only the next line.
def test_assert_topic():
Continue the code snippet: <|code_start|> nsq.assert_valid_topic_name('invalid name with space') def test_assert_channel(): assert nsq.assert_valid_channel_name('channel') is None with pytest.raises(ValueError): nsq.assert_valid_channel_name('invalid name with space') def test_invalid_commands(): with pytest.raises(TypeError): nsq.requeue('1234', None) with pytest.raises(TypeError): nsq.ready(None) with pytest.raises(ValueError): nsq.ready(-1) def test_backoff_timer(): timer = BackoffTimer(max_interval=1000) assert timer.get_interval() == 0 assert timer.is_reset() timer.success() assert timer.get_interval() == 0 assert timer.is_reset() <|code_end|> . Use current file imports: import pytest from six.moves import range from gnsq import BackoffTimer from gnsq import protocol as nsq and context (classes, functions, or code) from other files: # Path: gnsq/backofftimer.py # class BackoffTimer(object): # def __init__(self, ratio=1, max_interval=None, min_interval=None): # self.c = 0 # self.ratio = ratio # # self.max_interval = max_interval # self.min_interval = min_interval # # def is_reset(self): # return self.c == 0 # # def reset(self): # self.c = 0 # return self # # def success(self): # self.c = max(self.c - 1, 0) # return self # # def failure(self): # self.c += 1 # return self # # def get_interval(self): # k = pow(2, self.c) - 1 # interval = random.random() * k * self.ratio # # if self.max_interval is not None: # interval = min(interval, self.max_interval) # # if self.min_interval is not None: # interval = max(interval, self.min_interval) # # return interval # # Path: gnsq/protocol.py # MAGIC_V2 = b' V2' # NEWLINE = b'\n' # SPACE = b' ' # EMPTY = b'' # HEARTBEAT = b'_heartbeat_' # OK = b'OK' # IDENTIFY = b'IDENTIFY' # AUTH = b'AUTH' # SUB = b'SUB' # PUB = b'PUB' # MPUB = b'MPUB' # DPUB = b'DPUB' # RDY = b'RDY' # FIN = b'FIN' # REQ = b'REQ' # TOUCH = b'TOUCH' # CLS = b'CLS' # NOP = b'NOP' # FRAME_TYPE_RESPONSE = 0 # FRAME_TYPE_ERROR = 1 # FRAME_TYPE_MESSAGE = 2 # VALID_NAME_RE = re.compile(r'^[\.a-zA-Z0-9_-]+(#ephemeral)?$') # def _valid_name(name): # def valid_topic_name(topic): # def valid_channel_name(channel): # def assert_valid_topic_name(topic): # def assert_valid_channel_name(channel): # def unpack_size(data): # def unpack_response(data): # def unpack_message(data): # def _packsize(data): # def _packbody(body): # def _encode_param(data): # def _command(cmd, body, *params): # def identify(data): # def auth(secret): # def subscribe(topic_name, channel_name): # def publish(topic_name, data): # def multipublish_body(messages): # def multipublish(topic_name, messages): # def deferpublish(topic_name, data, delay_ms): # def ready(count): # def finish(message_id): # def requeue(message_id, timeout=0): # def touch(message_id): # def close(): # def nop(): . Output only the next line.
timer.failure()
Based on the snippet: <|code_start|> def time(s): return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S+0000') def post_text(item): return item.get('message', u'') + item.get('description', u'') def list_posts(access_token): latest_created_time = FacebookPost.objects\ <|code_end|> , predict the immediate next line with the help of imports: from datetime import datetime from urllib2 import urlopen, HTTPError from django.db.models import Max from sources.models import FacebookPost import json and context (classes, functions, sometimes code) from other files: # Path: sources/models.py # class FacebookPost(models.Model): # access_token = models.CharField(max_length=100) # data = JSONField() # created_time = models.DateTimeField() . Output only the next line.
.filter(access_token=access_token)\
Predict the next line for this snippet: <|code_start|> config = web.config view = web.config.view class front_page: def GET(self): pref = user_pref.reset() facets = items.get_facets_from_cache('', pref) <|code_end|> with the help of current file imports: import web import fsphinx from cloudmining.app.models import items from cloudmining.app.models import user_pref from cloudmining.lib import paging from cloudmining.app.helpers import templating and context from other files: # Path: cloudmining/app/models/items.py # def get_sphinx_client(query): # def search(query, offset=0, limit=10, sort_by='', user_pref={}): # def compute_facet(query, fname, visu_type=''): # def get_facets_from_cache(query, user_pref={}): # def setup_user_pref(cl, user_pref): # def is_sim_query(query, is_active=False): # def to_sim_query(query): # # Path: cloudmining/app/models/user_pref.py # def get(): # def reset(): # def get_default(as_module=True): # # Path: cloudmining/lib/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, # window_size=15, max_allowed_results=1000): , which may contain function names, class names, or code. Output only the next line.
return view.layout(view.front_page(facets, pref))
Next line prediction: <|code_start|> query = i.query_inactive + ' ' + query # redirect to a pretty url url = fsphinx.QueryToPrettyUrl(query) raise web.redirect('/search/' + url + '?' + i.params) class search_url: def GET(self, path): # get variables including the user preferences i = web.input(s=0, so='', ot='') start = int(i.s) pref = user_pref.get() # transform pretty url path into a query query = fsphinx.PrettyUrlToQuery(path, order=i.ot) # call model to search the items query, hits, facets = items.search(query, start, config.results_per_page, i.so, pref) # handle empty result set if not hits.total_found: facets = items.get_facets_from_cache('', pref) # create a pager to go through the results pager = paging.get_paging(start, hits['total_found'], results_per_page=config.results_per_page, window_size=config.paging_window_size) # call the proper view to display the results return view.layout(view.search(query, hits, facets, pager, pref)) class load_facet: def GET(self, fname, visu_type): i = web.input(q='') facet = items.compute_facet(i.q, fname, visu_type) <|code_end|> . Use current file imports: (import web import fsphinx from cloudmining.app.models import items from cloudmining.app.models import user_pref from cloudmining.lib import paging from cloudmining.app.helpers import templating) and context including class names, function names, or small code snippets from other files: # Path: cloudmining/app/models/items.py # def get_sphinx_client(query): # def search(query, offset=0, limit=10, sort_by='', user_pref={}): # def compute_facet(query, fname, visu_type=''): # def get_facets_from_cache(query, user_pref={}): # def setup_user_pref(cl, user_pref): # def is_sim_query(query, is_active=False): # def to_sim_query(query): # # Path: cloudmining/app/models/user_pref.py # def get(): # def reset(): # def get_default(as_module=True): # # Path: cloudmining/lib/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, # window_size=15, max_allowed_results=1000): . Output only the next line.
return config.visu[visu_type].render(facet, animate=True)
Predict the next line after this snippet: <|code_start|># coding=utf-8 from __future__ import unicode_literals code_apply = 'apply(hello, args, kwargs)' code_basestring = 'basestring' code_buffer = "buffer('hello', 1, 3)" code_callable = "callable('hello')" code_dict = """ d.keys() d.iteritems() d.viewvalues() """ code_except = """ try: import asdf except E, T: pass """ code_exec = 'exec code in ns1, ns2' code_execfile = "execfile('test.py')" code_filter = 'filter(lambda x: x, [1, 2, 3])' code_funcattrs = """ <|code_end|> using the current file's imports: import os import unittest from py3kwarn import main and any relevant context from other files: # Path: py3kwarn/main.py # def main(args=None): # if args is None: # args = sys.argv[1:] # # import optparse # parser = optparse.OptionParser(version='%prog {0}'.format(__version__), # prog='py3kwarn') # parser.add_option('-j', '--jobs', action='store', default=1, # type='int', help='Run in parallel') # options, args = parser.parse_args(args) # # if options.jobs < 1: # try: # import multiprocessing # except ImportError: # parser.error('"--jobs" is not supported on this platform') # options.jobs = multiprocessing.cpu_count() # # return 2 if print_warnings_for_files(args, # num_processes=options.jobs) else 0 . Output only the next line.
def test():
Given the following code snippet before the placeholder: <|code_start|> class FixHasKey(fixer_base.BaseFix): BM_compatible = True PATTERN = """ anchor=power< before=any+ trailer< '.' 'has_key' > trailer< '(' ( not(arglist | argument<any '=' any>) arg=any | arglist<(not argument<any '=' any>) arg=any ','> ) ')' > after=any* > | negation=not_test< 'not' anchor=power< before=any+ trailer< '.' 'has_key' > trailer< '(' ( not(arglist | argument<any '=' any>) arg=any | arglist<(not argument<any '=' any>) arg=any ','> ) ')' <|code_end|> , predict the next line using imports from the current file: from .. import pytree from .. import fixer_base from ..fixer_util import Name, parenthesize and context including class names, function names, and sometimes code from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def parenthesize(node): # return Node(syms.atom, [LParen(), node, RParen()]) . Output only the next line.
>
Given the code snippet: <|code_start|>2) Cases like this will not be converted: m = d.has_key if m(k): ... Only *calls* to has_key() are converted. While it is possible to convert the above to something like m = d.__contains__ if m(k): ... this is currently not done. """ # Local imports class FixHasKey(fixer_base.BaseFix): BM_compatible = True PATTERN = """ anchor=power< before=any+ trailer< '.' 'has_key' > trailer< '(' ( not(arglist | argument<any '=' any>) arg=any | arglist<(not argument<any '=' any>) arg=any ','> <|code_end|> , generate the next line using the imports in this file: from .. import pytree from .. import fixer_base from ..fixer_util import Name, parenthesize and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def parenthesize(node): # return Node(syms.atom, [LParen(), node, RParen()]) . Output only the next line.
)
Next line prediction: <|code_start|>d.viewkeys() -> d.keys() d.viewitems() -> d.items() d.viewvalues() -> d.values() Except in certain very specific contexts: the iter() can be dropped when the context is list(), sorted(), iter() or for...in; the list() can be dropped when the context is list() or sorted() (but not iter() or for...in!). Special contexts that apply to both: list(), sorted(), tuple() set(), any(), all(), sum(). Note: iter(d.keys()) could be written as iter(d) but since the original d.iterkeys() was also redundant we don't fix this. And there are (rare) contexts where it makes a difference (e.g. when passing it as an argument to a function that introspects the argument). """ # Local imports iter_exempt = fixer_util.consuming_calls | set(["iter"]) class FixDict(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< head=any+ trailer< '.' method=('iterkeys'|'iteritems'|'itervalues'| 'viewkeys'|'viewitems'|'viewvalues') > parens=trailer< '(' ')' > <|code_end|> . Use current file imports: (from .. import pytree from .. import patcomp from .. import fixer_base from ..fixer_util import Name from ..fixer_util import Call from ..fixer_util import Dot from .. import fixer_util) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # Path: py3kwarn2to3/fixer_util.py # def Dot(): # """A period (.) leaf""" # return Leaf(token.DOT, u".") . Output only the next line.
tail=any*
Predict the next line after this snippet: <|code_start|> d.viewkeys() -> d.keys() d.viewitems() -> d.items() d.viewvalues() -> d.values() Except in certain very specific contexts: the iter() can be dropped when the context is list(), sorted(), iter() or for...in; the list() can be dropped when the context is list() or sorted() (but not iter() or for...in!). Special contexts that apply to both: list(), sorted(), tuple() set(), any(), all(), sum(). Note: iter(d.keys()) could be written as iter(d) but since the original d.iterkeys() was also redundant we don't fix this. And there are (rare) contexts where it makes a difference (e.g. when passing it as an argument to a function that introspects the argument). """ # Local imports iter_exempt = fixer_util.consuming_calls | set(["iter"]) class FixDict(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< head=any+ trailer< '.' method=('iterkeys'|'iteritems'|'itervalues'| 'viewkeys'|'viewitems'|'viewvalues') > <|code_end|> using the current file's imports: from .. import pytree from .. import patcomp from .. import fixer_base from ..fixer_util import Name from ..fixer_util import Call from ..fixer_util import Dot from .. import fixer_util and any relevant context from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # Path: py3kwarn2to3/fixer_util.py # def Dot(): # """A period (.) leaf""" # return Leaf(token.DOT, u".") . Output only the next line.
parens=trailer< '(' ')' >
Given the code snippet: <|code_start|>d.iterkeys() -> iter(d.keys()) d.iteritems() -> iter(d.items()) d.itervalues() -> iter(d.values()) d.viewkeys() -> d.keys() d.viewitems() -> d.items() d.viewvalues() -> d.values() Except in certain very specific contexts: the iter() can be dropped when the context is list(), sorted(), iter() or for...in; the list() can be dropped when the context is list() or sorted() (but not iter() or for...in!). Special contexts that apply to both: list(), sorted(), tuple() set(), any(), all(), sum(). Note: iter(d.keys()) could be written as iter(d) but since the original d.iterkeys() was also redundant we don't fix this. And there are (rare) contexts where it makes a difference (e.g. when passing it as an argument to a function that introspects the argument). """ # Local imports iter_exempt = fixer_util.consuming_calls | set(["iter"]) class FixDict(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> , generate the next line using the imports in this file: from .. import pytree from .. import patcomp from .. import fixer_base from ..fixer_util import Name from ..fixer_util import Call from ..fixer_util import Dot from .. import fixer_util and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # Path: py3kwarn2to3/fixer_util.py # def Dot(): # """A period (.) leaf""" # return Leaf(token.DOT, u".") . Output only the next line.
power< head=any+
Here is a snippet: <|code_start|># Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer that changes xrange(...) into range(...).""" # Local imports class FixXrange(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< <|code_end|> . Write the next line using the current file imports: from .. import fixer_base from ..fixer_util import Name and context from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) , which may include functions, classes, or code. Output only the next line.
(name='xrange') trailer< '(' args=any ')' >
Given the code snippet: <|code_start|>except NameError: unicode = str def encode_ascii(value): if sys.version_info < (3,): return value.encode("ascii") else: return value def invocation(s): def dec(f): f.invocation = s return f return dec class FixOperator(fixer_base.BaseFix): BM_compatible = True order = "pre" methods = """ method=('isCallable'|'sequenceIncludes' |'isSequenceType'|'isMappingType'|'isNumberType' |'repeat'|'irepeat') """ obj = "'(' obj=any ')'" PATTERN = """ power< module='operator' <|code_end|> , generate the next line using the imports in this file: import collections import sys from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, touch_import and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
trailer< '.' %(methods)s > trailer< %(obj)s > >
Next line prediction: <|code_start|> def encode_ascii(value): if sys.version_info < (3,): return value.encode("ascii") else: return value def invocation(s): def dec(f): f.invocation = s return f return dec class FixOperator(fixer_base.BaseFix): BM_compatible = True order = "pre" methods = """ method=('isCallable'|'sequenceIncludes' |'isSequenceType'|'isMappingType'|'isNumberType' |'repeat'|'irepeat') """ obj = "'(' obj=any ')'" PATTERN = """ power< module='operator' trailer< '.' %(methods)s > trailer< %(obj)s > > | <|code_end|> . Use current file imports: (import collections import sys from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, touch_import) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
power< %(methods)s trailer< %(obj)s > >
Given the code snippet: <|code_start|> def encode_ascii(value): if sys.version_info < (3,): return value.encode("ascii") else: return value def invocation(s): def dec(f): f.invocation = s return f return dec class FixOperator(fixer_base.BaseFix): BM_compatible = True order = "pre" methods = """ method=('isCallable'|'sequenceIncludes' |'isSequenceType'|'isMappingType'|'isNumberType' |'repeat'|'irepeat') """ obj = "'(' obj=any ')'" PATTERN = """ power< module='operator' trailer< '.' %(methods)s > trailer< %(obj)s > > | <|code_end|> , generate the next line using the imports in this file: import collections import sys from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, touch_import and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
power< %(methods)s trailer< %(obj)s > >
Based on the snippet: <|code_start|> try: unicode except NameError: unicode = str def encode_ascii(value): if sys.version_info < (3,): return value.encode("ascii") else: return value def invocation(s): def dec(f): f.invocation = s return f return dec class FixOperator(fixer_base.BaseFix): BM_compatible = True order = "pre" methods = """ method=('isCallable'|'sequenceIncludes' |'isSequenceType'|'isMappingType'|'isNumberType' <|code_end|> , predict the immediate next line with the help of imports: import collections import sys from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, touch_import and context (classes, functions, sometimes code) from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
|'repeat'|'irepeat')
Here is a snippet: <|code_start|> try: unicode except NameError: unicode = str def encode_ascii(value): if sys.version_info < (3,): return value.encode("ascii") else: return value def invocation(s): def dec(f): f.invocation = s return f return dec class FixOperator(fixer_base.BaseFix): BM_compatible = True order = "pre" methods = """ method=('isCallable'|'sequenceIncludes' |'isSequenceType'|'isMappingType'|'isNumberType' <|code_end|> . Write the next line using the current file imports: import collections import sys from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, touch_import and context from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) , which may include functions, classes, or code. Output only the next line.
|'repeat'|'irepeat')
Here is a snippet: <|code_start|> finally: sys.stdin = save expected = ["def parrot(): pass\n\n", "def cheese(): pass\n\n", "<stdin>", False] self.assertEqual(results, expected) def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS, options=None, mock_log_debug=None, actually_write=True): tmpdir = tempfile.mkdtemp(prefix="2to3-test_refactor") self.addCleanup(shutil.rmtree, tmpdir) # make a copy of the tested file that we can write to shutil.copy(test_file, tmpdir) test_file = os.path.join(tmpdir, os.path.basename(test_file)) os.chmod(test_file, 0o644) def read_file(): with open(test_file, "rb") as fp: return fp.read() old_contents = read_file() rt = self.rt(fixers=fixers, options=options) if mock_log_debug: rt.log_debug = mock_log_debug rt.refactor_file(test_file) self.assertEqual(old_contents, read_file()) if not actually_write: <|code_end|> . Write the next line using the current file imports: import sys import os import codecs import tempfile import shutil import unittest2 as unittest import unittest from StringIO import StringIO from io import StringIO from py3kwarn2to3 import refactor, pygram, fixer_base from py3kwarn2to3.pgen2 import token from myfixes.fix_first import FixFirst from myfixes.fix_last import FixLast from myfixes.fix_parrot import FixParrot from myfixes.fix_preorder import FixPreorder from myfixes.fix_explicit import FixExplicit and context from other files: # Path: py3kwarn2to3/refactor.py # def refactor(self, items, write=False, doctests_only=False): # """Refactor a list of files and directories.""" # # for dir_or_file in items: # if os.path.isdir(dir_or_file): # self.refactor_dir(dir_or_file, write, doctests_only) # else: # self.refactor_file(dir_or_file, write, doctests_only) # # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): , which may include functions, classes, or code. Output only the next line.
return
Given the following code snippet before the placeholder: <|code_start|> def test_refactor_dir(self): def check(structure, expected): def mock_refactor_file(self, f, *args): got.append(f) save_func = refactor.RefactoringTool.refactor_file refactor.RefactoringTool.refactor_file = mock_refactor_file rt = self.rt() got = [] dir = tempfile.mkdtemp(prefix="2to3-test_refactor") try: os.mkdir(os.path.join(dir, "a_dir")) for fn in structure: open(os.path.join(dir, fn), "wb").close() rt.refactor_dir(dir) finally: refactor.RefactoringTool.refactor_file = save_func shutil.rmtree(dir) self.assertEqual(got, [os.path.join(dir, path) for path in expected]) check([], []) tree = ["nothing", "hi.py", ".dumb", ".after.py", "notpy.npy", "sappy"] expected = ["hi.py"] check(tree, expected) tree = ["hi.py", <|code_end|> , predict the next line using imports from the current file: import sys import os import codecs import tempfile import shutil import unittest2 as unittest import unittest from StringIO import StringIO from io import StringIO from py3kwarn2to3 import refactor, pygram, fixer_base from py3kwarn2to3.pgen2 import token from myfixes.fix_first import FixFirst from myfixes.fix_last import FixLast from myfixes.fix_parrot import FixParrot from myfixes.fix_preorder import FixPreorder from myfixes.fix_explicit import FixExplicit and context including class names, function names, and sometimes code from other files: # Path: py3kwarn2to3/refactor.py # def refactor(self, items, write=False, doctests_only=False): # """Refactor a list of files and directories.""" # # for dir_or_file in items: # if os.path.isdir(dir_or_file): # self.refactor_dir(dir_or_file, write, doctests_only) # else: # self.refactor_file(dir_or_file, write, doctests_only) # # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): . Output only the next line.
os.path.join("a_dir", "stuff.py")]
Here is a snippet: <|code_start|> self.assertEqual(run(inp), fs(("generators", "print_function"))) invalid = ("from", "from 4", "from x", "from x 5", "from x im", "from x import", "from x import 4", ) for inp in invalid: self.assertEqual(run(inp), empty) inp = "'docstring'\nfrom __future__ import print_function" self.assertEqual(run(inp), fs(("print_function",))) inp = "'docstring'\n'somng'\nfrom __future__ import print_function" self.assertEqual(run(inp), empty) inp = "# comment\nfrom __future__ import print_function" self.assertEqual(run(inp), fs(("print_function",))) inp = "# comment\n'doc'\nfrom __future__ import print_function" self.assertEqual(run(inp), fs(("print_function",))) inp = "class x: pass\nfrom __future__ import print_function" self.assertEqual(run(inp), empty) def test_get_headnode_dict(self): class NoneFix(fixer_base.BaseFix): pass class FileInputFix(fixer_base.BaseFix): PATTERN = "file_input< any * >" class SimpleFix(fixer_base.BaseFix): <|code_end|> . Write the next line using the current file imports: import sys import os import codecs import tempfile import shutil import unittest2 as unittest import unittest from StringIO import StringIO from io import StringIO from py3kwarn2to3 import refactor, pygram, fixer_base from py3kwarn2to3.pgen2 import token from myfixes.fix_first import FixFirst from myfixes.fix_last import FixLast from myfixes.fix_parrot import FixParrot from myfixes.fix_preorder import FixPreorder from myfixes.fix_explicit import FixExplicit and context from other files: # Path: py3kwarn2to3/refactor.py # def refactor(self, items, write=False, doctests_only=False): # """Refactor a list of files and directories.""" # # for dir_or_file in items: # if os.path.isdir(dir_or_file): # self.refactor_dir(dir_or_file, write, doctests_only) # else: # self.refactor_file(dir_or_file, write, doctests_only) # # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): , which may include functions, classes, or code. Output only the next line.
PATTERN = "'name'"
Based on the snippet: <|code_start|># Local imports MAPPING = {"sys": {"maxint" : "maxsize"}, } LOOKUP = {} try: unicode except NameError: unicode = str def alternates(members): return "(" + "|".join(map(repr, members)) + ")" def build_pattern(): #bare = set() for module, replace in MAPPING.items(): for old_attr, new_attr in replace.items(): LOOKUP[(module, old_attr)] = new_attr #bare.add(module) #bare.add(old_attr) #yield """ # import_name< 'import' (module=%r # | dotted_as_names< any* module=%r any* >) > # """ % (module, module) yield """ import_from< 'from' module_name=%r 'import' <|code_end|> , predict the immediate next line with the help of imports: from .. import fixer_base from ..fixer_util import Name, attr_chain and context (classes, functions, sometimes code) from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def attr_chain(obj, attr): # """Follow an attribute chain. # # If you have a chain of objects where a.foo -> b, b.foo-> c, etc, # use this to iterate over all objects in the chain. Iteration is # terminated by getattr(x, attr) is None. # # Args: # obj: the starting object # attr: the name of the chaining attribute # # Yields: # Each successive object in the chain. # """ # next = getattr(obj, attr) # while next: # yield next # next = getattr(next, attr) . Output only the next line.
( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
Next line prediction: <|code_start|># Local imports MAPPING = {"sys": {"maxint" : "maxsize"}, } LOOKUP = {} try: unicode except NameError: unicode = str def alternates(members): return "(" + "|".join(map(repr, members)) + ")" def build_pattern(): #bare = set() for module, replace in MAPPING.items(): for old_attr, new_attr in replace.items(): LOOKUP[(module, old_attr)] = new_attr #bare.add(module) #bare.add(old_attr) #yield """ # import_name< 'import' (module=%r # | dotted_as_names< any* module=%r any* >) > # """ % (module, module) yield """ import_from< 'from' module_name=%r 'import' <|code_end|> . Use current file imports: (from .. import fixer_base from ..fixer_util import Name, attr_chain) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def attr_chain(obj, attr): # """Follow an attribute chain. # # If you have a chain of objects where a.foo -> b, b.foo-> c, etc, # use this to iterate over all objects in the chain. Iteration is # terminated by getattr(x, attr) is None. # # Args: # obj: the starting object # attr: the name of the chaining attribute # # Yields: # Each successive object in the chain. # """ # next = getattr(obj, attr) # while next: # yield next # next = getattr(next, attr) . Output only the next line.
( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
Given snippet: <|code_start|>"""Fix bound method attributes (method.im_? -> method.__?__). """ # Author: Christian Heimes # Local imports try: unicode except NameError: unicode = str MAP = { "im_func" : "__func__", "im_self" : "__self__", "im_class" : "__self__.__class__" } class FixMethodattrs(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> , continue by predicting the next line. Consider current file imports: from .. import fixer_base from ..fixer_util import Name and context: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) which might include code, classes, or functions. Output only the next line.
power< any+ trailer< '.' attr=('im_func' | 'im_self' | 'im_class') > any* >
Using the snippet: <|code_start|> a = "operator .mul(x, n)" self.check(b, a) b = "operator. repeat(x, n)" a = "operator. mul(x, n)" self.check(b, a) def test_operator_irepeat(self): b = "operator.irepeat(x, n)" a = "operator.imul(x, n)" self.check(b, a) b = "operator .irepeat(x, n)" a = "operator .imul(x, n)" self.check(b, a) b = "operator. irepeat(x, n)" a = "operator. imul(x, n)" self.check(b, a) def test_bare_isCallable(self): s = "isCallable(x)" t = "You should use 'hasattr(x, '__call__')' here." self.warns_unchanged(s, t) def test_bare_sequenceIncludes(self): s = "sequenceIncludes(x, y)" t = "You should use 'operator.contains(x, y)' here." self.warns_unchanged(s, t) <|code_end|> , determine the next line of code. You have imports: import os from itertools import chain from operator import itemgetter from py3kwarn2to3 import pygram, fixer_util from py3kwarn2to3.tests import support from ..fixes.fix_imports import MAPPING as modules from ..fixes.fix_imports2 import MAPPING as modules from ..fixes.fix_imports2 import MAPPING as mapping2 from ..fixes.fix_imports import MAPPING as mapping1 from ..fixes.fix_urllib import MAPPING as modules from py3kwarn2to3.fixes import fix_import from py3kwarn2to3.fixes import fix_import and context (class names, function names, or code) available: # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/tests/support.py # def parse_string(string): # def run_all_tests(test_mod=None, tests=None): # def reformat(string): # def get_refactorer(fixer_pkg="py3kwarn2to3", fixers=None, options=None): # def all_project_files(): . Output only the next line.
def test_bare_operator_isSequenceType(self):
Using the snippet: <|code_start|> b = """ try: pass except Exception, a().foo: pass""" a = """ try: pass except Exception as xxx_todo_changeme: a().foo = xxx_todo_changeme pass""" self.check(b, a) def test_bare_except(self): b = """ try: pass except Exception, a: pass except: pass""" a = """ try: pass except Exception as a: pass except: pass""" <|code_end|> , determine the next line of code. You have imports: import os from itertools import chain from operator import itemgetter from py3kwarn2to3 import pygram, fixer_util from py3kwarn2to3.tests import support from ..fixes.fix_imports import MAPPING as modules from ..fixes.fix_imports2 import MAPPING as modules from ..fixes.fix_imports2 import MAPPING as mapping2 from ..fixes.fix_imports import MAPPING as mapping1 from ..fixes.fix_urllib import MAPPING as modules from py3kwarn2to3.fixes import fix_import from py3kwarn2to3.fixes import fix_import and context (class names, function names, or code) available: # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/tests/support.py # def parse_string(string): # def run_all_tests(test_mod=None, tests=None): # def reformat(string): # def get_refactorer(fixer_pkg="py3kwarn2to3", fixers=None, options=None): # def all_project_files(): . Output only the next line.
self.check(b, a)
Given the code snippet: <|code_start|> s = """print()""" self.unchanged(s) s = """print('')""" self.unchanged(s) def test_1(self): b = """print 1, 1+1, 1+1+1""" a = """print(1, 1+1, 1+1+1)""" self.check(b, a) def test_2(self): b = """print 1, 2""" a = """print(1, 2)""" self.check(b, a) def test_3(self): b = """print""" a = """print()""" self.check(b, a) def test_4(self): # from bug 3000 b = """print whatever; print""" a = """print(whatever); print()""" self.check(b, a) def test_5(self): b = """print; print whatever;""" a = """print(); print(whatever);""" <|code_end|> , generate the next line using the imports in this file: import os from itertools import chain from operator import itemgetter from py3kwarn2to3 import pygram, fixer_util from py3kwarn2to3.tests import support from ..fixes.fix_imports import MAPPING as modules from ..fixes.fix_imports2 import MAPPING as modules from ..fixes.fix_imports2 import MAPPING as mapping2 from ..fixes.fix_imports import MAPPING as mapping1 from ..fixes.fix_urllib import MAPPING as modules from py3kwarn2to3.fixes import fix_import from py3kwarn2to3.fixes import fix_import and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/tests/support.py # def parse_string(string): # def run_all_tests(test_mod=None, tests=None): # def reformat(string): # def get_refactorer(fixer_pkg="py3kwarn2to3", fixers=None, options=None): # def all_project_files(): . Output only the next line.
self.check(b, a)
Given snippet: <|code_start|>- "except E, T:" where T is not a name, tuple or list: except E as t: T = t This is done because the target of an "except" clause must be a name. - "except E, T:" where T is a tuple or list literal: except E as t: T = t.args """ # Author: Collin Winter # Local imports def find_excepts(nodes): for i, n in enumerate(nodes): if n.type == syms.except_clause: if n.children[0].value == u'except': yield (n, nodes[i+2]) class FixExcept(fixer_base.BaseFix): BM_compatible = True PATTERN = """ try_stmt< 'try' ':' (simple_stmt | suite) cleanup=(except_clause ':' (simple_stmt | suite))+ tail=(['except' ':' (simple_stmt | suite)] <|code_end|> , continue by predicting the next line. Consider current file imports: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Attr, Name, is_tuple, is_list, syms and context: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): which might include code, classes, or functions. Output only the next line.
['else' ':' (simple_stmt | suite)]
Continue the code snippet: <|code_start|> except E as T: - "except E, T:" where T is not a name, tuple or list: except E as t: T = t This is done because the target of an "except" clause must be a name. - "except E, T:" where T is a tuple or list literal: except E as t: T = t.args """ # Author: Collin Winter # Local imports def find_excepts(nodes): for i, n in enumerate(nodes): if n.type == syms.except_clause: if n.children[0].value == u'except': yield (n, nodes[i+2]) class FixExcept(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> . Use current file imports: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Attr, Name, is_tuple, is_list, syms and context (classes, functions, or code) from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
try_stmt< 'try' ':' (simple_stmt | suite)
Given snippet: <|code_start|> except E as T: - "except E, T:" where T is not a name, tuple or list: except E as t: T = t This is done because the target of an "except" clause must be a name. - "except E, T:" where T is a tuple or list literal: except E as t: T = t.args """ # Author: Collin Winter # Local imports def find_excepts(nodes): for i, n in enumerate(nodes): if n.type == syms.except_clause: if n.children[0].value == u'except': yield (n, nodes[i+2]) class FixExcept(fixer_base.BaseFix): BM_compatible = True PATTERN = """ try_stmt< 'try' ':' (simple_stmt | suite) <|code_end|> , continue by predicting the next line. Consider current file imports: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Attr, Name, is_tuple, is_list, syms and context: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): which might include code, classes, or functions. Output only the next line.
cleanup=(except_clause ':' (simple_stmt | suite))+
Next line prediction: <|code_start|> except E as t: T = t This is done because the target of an "except" clause must be a name. - "except E, T:" where T is a tuple or list literal: except E as t: T = t.args """ # Author: Collin Winter # Local imports def find_excepts(nodes): for i, n in enumerate(nodes): if n.type == syms.except_clause: if n.children[0].value == u'except': yield (n, nodes[i+2]) class FixExcept(fixer_base.BaseFix): BM_compatible = True PATTERN = """ try_stmt< 'try' ':' (simple_stmt | suite) cleanup=(except_clause ':' (simple_stmt | suite))+ tail=(['except' ':' (simple_stmt | suite)] ['else' ':' (simple_stmt | suite)] <|code_end|> . Use current file imports: (from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Attr, Name, is_tuple, is_list, syms) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
['finally' ':' (simple_stmt | suite)]) >
Continue the code snippet: <|code_start|> - "except E, T:" where T is not a name, tuple or list: except E as t: T = t This is done because the target of an "except" clause must be a name. - "except E, T:" where T is a tuple or list literal: except E as t: T = t.args """ # Author: Collin Winter # Local imports def find_excepts(nodes): for i, n in enumerate(nodes): if n.type == syms.except_clause: if n.children[0].value == u'except': yield (n, nodes[i+2]) class FixExcept(fixer_base.BaseFix): BM_compatible = True PATTERN = """ try_stmt< 'try' ':' (simple_stmt | suite) cleanup=(except_clause ':' (simple_stmt | suite))+ <|code_end|> . Use current file imports: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Attr, Name, is_tuple, is_list, syms and context (classes, functions, or code) from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
tail=(['except' ':' (simple_stmt | suite)]
Given the following code snippet before the placeholder: <|code_start|>- "except E, T:" where T is not a name, tuple or list: except E as t: T = t This is done because the target of an "except" clause must be a name. - "except E, T:" where T is a tuple or list literal: except E as t: T = t.args """ # Author: Collin Winter # Local imports def find_excepts(nodes): for i, n in enumerate(nodes): if n.type == syms.except_clause: if n.children[0].value == u'except': yield (n, nodes[i+2]) class FixExcept(fixer_base.BaseFix): BM_compatible = True PATTERN = """ try_stmt< 'try' ':' (simple_stmt | suite) cleanup=(except_clause ':' (simple_stmt | suite))+ tail=(['except' ':' (simple_stmt | suite)] <|code_end|> , predict the next line using imports from the current file: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Attr, Name, is_tuple, is_list, syms and context including class names, function names, and sometimes code from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
['else' ':' (simple_stmt | suite)]
Predict the next line after this snippet: <|code_start|> class TestDriver(support.TestCase): def test_formfeed(self): s = """print 1\n\x0Cprint 2\n""" t = driver.parse_string(s) self.assertEqual(t.children[0].children[0].type, syms.print_stmt) self.assertEqual(t.children[1].children[0].type, syms.print_stmt) class GrammarTest(support.TestCase): def validate(self, code): support.parse_string(code) def invalid_syntax(self, code): try: self.validate(code) except ParseError: pass else: raise AssertionError("Syntax shouldn't have been valid") class TestRaiseChanges(GrammarTest): def test_2x_style_1(self): self.validate("raise") def test_2x_style_2(self): self.validate("raise E, V") <|code_end|> using the current file's imports: from . import support from .support import driver, test_dir from py3kwarn2to3.pgen2 import tokenize from ..pgen2.parse import ParseError from py3kwarn2to3.pygram import python_symbols as syms import os import sys and any relevant context from other files: # Path: py3kwarn2to3/tests/support.py # def parse_string(string): # def run_all_tests(test_mod=None, tests=None): # def reformat(string): # def get_refactorer(fixer_pkg="py3kwarn2to3", fixers=None, options=None): # def all_project_files(): # # Path: py3kwarn2to3/pgen2/tokenize.py # def tokenize(readline, tokeneater=printtoken): # """ # The tokenize() function accepts two parameters: one representing the # input stream, and one providing an output mechanism for tokenize(). # # The first parameter, readline, must be a callable object which provides # the same interface as the readline() method of built-in file objects. # Each call to the function should return one line of input as a string. # # The second parameter, tokeneater, must also be a callable object. It is # called once for each token, with five arguments, corresponding to the # tuples generated by generate_tokens(). # """ # try: # tokenize_loop(readline, tokeneater) # except StopTokenizing: # pass # # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): . Output only the next line.
def test_2x_style_3(self):
Next line prediction: <|code_start|> # Local imports class TestDriver(support.TestCase): def test_formfeed(self): s = """print 1\n\x0Cprint 2\n""" t = driver.parse_string(s) self.assertEqual(t.children[0].children[0].type, syms.print_stmt) self.assertEqual(t.children[1].children[0].type, syms.print_stmt) class GrammarTest(support.TestCase): def validate(self, code): support.parse_string(code) def invalid_syntax(self, code): try: self.validate(code) except ParseError: pass else: raise AssertionError("Syntax shouldn't have been valid") class TestRaiseChanges(GrammarTest): def test_2x_style_1(self): self.validate("raise") <|code_end|> . Use current file imports: (from . import support from .support import driver, test_dir from py3kwarn2to3.pgen2 import tokenize from ..pgen2.parse import ParseError from py3kwarn2to3.pygram import python_symbols as syms import os import sys) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/tests/support.py # def parse_string(string): # def run_all_tests(test_mod=None, tests=None): # def reformat(string): # def get_refactorer(fixer_pkg="py3kwarn2to3", fixers=None, options=None): # def all_project_files(): # # Path: py3kwarn2to3/pgen2/tokenize.py # def tokenize(readline, tokeneater=printtoken): # """ # The tokenize() function accepts two parameters: one representing the # input stream, and one providing an output mechanism for tokenize(). # # The first parameter, readline, must be a callable object which provides # the same interface as the readline() method of built-in file objects. # Each call to the function should return one line of input as a string. # # The second parameter, tokeneater, must also be a callable object. It is # called once for each token, with five arguments, corresponding to the # tuples generated by generate_tokens(). # """ # try: # tokenize_loop(readline, tokeneater) # except StopTokenizing: # pass # # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): . Output only the next line.
def test_2x_style_2(self):
Given snippet: <|code_start|> lambda (x, y): x + y -> lambda t: t[0] + t[1] # The parens are a syntax error in Python 3 lambda (x): x + y -> lambda x: x + y """ # Author: Collin Winter # Local imports try: unicode except NameError: unicode = str def is_docstring(stmt): return isinstance(stmt, pytree.Node) and \ stmt.children[0].type == token.STRING class FixTupleParams(fixer_base.BaseFix): run_order = 4 #use a lower order since lambda is part of other #patterns BM_compatible = True PATTERN = """ funcdef< 'def' any parameters< '(' args=any ')' > ['->' any] ':' suite=any+ > | lambda= <|code_end|> , continue by predicting the next line. Consider current file imports: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms and context: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): which might include code, classes, or functions. Output only the next line.
lambdef< 'lambda' args=vfpdef< '(' inner=any ')' >
Using the snippet: <|code_start|> ... It will also support lambdas: lambda (x, y): x + y -> lambda t: t[0] + t[1] # The parens are a syntax error in Python 3 lambda (x): x + y -> lambda x: x + y """ # Author: Collin Winter # Local imports try: unicode except NameError: unicode = str def is_docstring(stmt): return isinstance(stmt, pytree.Node) and \ stmt.children[0].type == token.STRING class FixTupleParams(fixer_base.BaseFix): run_order = 4 #use a lower order since lambda is part of other #patterns BM_compatible = True PATTERN = """ <|code_end|> , determine the next line of code. You have imports: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms and context (class names, function names, or code) available: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
funcdef< 'def' any parameters< '(' args=any ')' >
Here is a snippet: <|code_start|> # The parens are a syntax error in Python 3 lambda (x): x + y -> lambda x: x + y """ # Author: Collin Winter # Local imports try: unicode except NameError: unicode = str def is_docstring(stmt): return isinstance(stmt, pytree.Node) and \ stmt.children[0].type == token.STRING class FixTupleParams(fixer_base.BaseFix): run_order = 4 #use a lower order since lambda is part of other #patterns BM_compatible = True PATTERN = """ funcdef< 'def' any parameters< '(' args=any ')' > ['->' any] ':' suite=any+ > | lambda= lambdef< 'lambda' args=vfpdef< '(' inner=any ')' > ':' body=any <|code_end|> . Write the next line using the current file imports: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms and context from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): , which may include functions, classes, or code. Output only the next line.
>
Given the code snippet: <|code_start|> # The parens are a syntax error in Python 3 lambda (x): x + y -> lambda x: x + y """ # Author: Collin Winter # Local imports try: unicode except NameError: unicode = str def is_docstring(stmt): return isinstance(stmt, pytree.Node) and \ stmt.children[0].type == token.STRING class FixTupleParams(fixer_base.BaseFix): run_order = 4 #use a lower order since lambda is part of other #patterns BM_compatible = True PATTERN = """ funcdef< 'def' any parameters< '(' args=any ')' > ['->' any] ':' suite=any+ > | lambda= lambdef< 'lambda' args=vfpdef< '(' inner=any ')' > <|code_end|> , generate the next line using the imports in this file: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
':' body=any
Given the code snippet: <|code_start|> # The parens are a syntax error in Python 3 lambda (x): x + y -> lambda x: x + y """ # Author: Collin Winter # Local imports try: unicode except NameError: unicode = str def is_docstring(stmt): return isinstance(stmt, pytree.Node) and \ stmt.children[0].type == token.STRING class FixTupleParams(fixer_base.BaseFix): run_order = 4 #use a lower order since lambda is part of other #patterns BM_compatible = True PATTERN = """ funcdef< 'def' any parameters< '(' args=any ')' > ['->' any] ':' suite=any+ > | lambda= lambdef< 'lambda' args=vfpdef< '(' inner=any ')' > ':' body=any <|code_end|> , generate the next line using the imports in this file: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
>
Continue the code snippet: <|code_start|> # The parens are a syntax error in Python 3 lambda (x): x + y -> lambda x: x + y """ # Author: Collin Winter # Local imports try: unicode except NameError: unicode = str def is_docstring(stmt): return isinstance(stmt, pytree.Node) and \ stmt.children[0].type == token.STRING class FixTupleParams(fixer_base.BaseFix): run_order = 4 #use a lower order since lambda is part of other #patterns BM_compatible = True PATTERN = """ funcdef< 'def' any parameters< '(' args=any ')' > ['->' any] ':' suite=any+ > | lambda= lambdef< 'lambda' args=vfpdef< '(' inner=any ')' > <|code_end|> . Use current file imports: from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms and context (classes, functions, or code) from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
':' body=any
Predict the next line after this snippet: <|code_start|> if remove_prefix: name = name[4:] fix_names.append(name[:-3]) return fix_names class _EveryNode(Exception): pass def _get_head_types(pat): """ Accepts a pytree Pattern Node and returns a set of the pattern types which will match first. """ if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)): # NodePatters must either have no type and no content # or a type and content -- so they don't get any farther # Always return leafs if pat.type is None: raise _EveryNode return set([pat.type]) if isinstance(pat, pytree.NegatedPattern): if pat.content: return _get_head_types(pat.content) raise _EveryNode # Negated Patterns don't have a type if isinstance(pat, pytree.WildcardPattern): # Recurse on each node in content r = set() <|code_end|> using the current file's imports: import os import sys import logging import operator import collections import codecs import multiprocessing from StringIO import StringIO from io import StringIO from itertools import chain from .pgen2 import driver, parse, tokenize, token from .fixer_util import find_root from . import pytree, pygram from . import btm_matcher as bm and any relevant context from other files: # Path: py3kwarn2to3/pgen2/driver.py # class Driver(object): # def __init__(self, grammar, convert=None, logger=None): # def parse_tokens(self, tokens, debug=False): # def parse_stream_raw(self, stream, debug=False): # def parse_stream(self, stream, debug=False): # def parse_file(self, filename, encoding=None, debug=False): # def parse_string(self, text, debug=False): # def load_grammar(gt="Grammar.txt", gp=None, # save=True, force=False, logger=None): # def _newer(a, b): # # Path: py3kwarn2to3/pgen2/tokenize.py # def tokenize(readline, tokeneater=printtoken): # """ # The tokenize() function accepts two parameters: one representing the # input stream, and one providing an output mechanism for tokenize(). # # The first parameter, readline, must be a callable object which provides # the same interface as the readline() method of built-in file objects. # Each call to the function should return one line of input as a string. # # The second parameter, tokeneater, must also be a callable object. It is # called once for each token, with five arguments, corresponding to the # tuples generated by generate_tokens(). # """ # try: # tokenize_loop(readline, tokeneater) # except StopTokenizing: # pass # # Path: py3kwarn2to3/fixer_util.py # def find_root(node): # """Find the top level namespace.""" # # Scamper up to the top level namespace # while node.type != syms.file_input: # assert node.parent, "Tree is insane! root found before "\ # "file_input node was found." # node = node.parent # return node . Output only the next line.
for p in pat.content:
Next line prediction: <|code_start|> if remove_prefix: name = name[4:] fix_names.append(name[:-3]) return fix_names class _EveryNode(Exception): pass def _get_head_types(pat): """ Accepts a pytree Pattern Node and returns a set of the pattern types which will match first. """ if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)): # NodePatters must either have no type and no content # or a type and content -- so they don't get any farther # Always return leafs if pat.type is None: raise _EveryNode return set([pat.type]) if isinstance(pat, pytree.NegatedPattern): if pat.content: return _get_head_types(pat.content) raise _EveryNode # Negated Patterns don't have a type if isinstance(pat, pytree.WildcardPattern): # Recurse on each node in content r = set() <|code_end|> . Use current file imports: (import os import sys import logging import operator import collections import codecs import multiprocessing from StringIO import StringIO from io import StringIO from itertools import chain from .pgen2 import driver, parse, tokenize, token from .fixer_util import find_root from . import pytree, pygram from . import btm_matcher as bm) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/pgen2/driver.py # class Driver(object): # def __init__(self, grammar, convert=None, logger=None): # def parse_tokens(self, tokens, debug=False): # def parse_stream_raw(self, stream, debug=False): # def parse_stream(self, stream, debug=False): # def parse_file(self, filename, encoding=None, debug=False): # def parse_string(self, text, debug=False): # def load_grammar(gt="Grammar.txt", gp=None, # save=True, force=False, logger=None): # def _newer(a, b): # # Path: py3kwarn2to3/pgen2/tokenize.py # def tokenize(readline, tokeneater=printtoken): # """ # The tokenize() function accepts two parameters: one representing the # input stream, and one providing an output mechanism for tokenize(). # # The first parameter, readline, must be a callable object which provides # the same interface as the readline() method of built-in file objects. # Each call to the function should return one line of input as a string. # # The second parameter, tokeneater, must also be a callable object. It is # called once for each token, with five arguments, corresponding to the # tuples generated by generate_tokens(). # """ # try: # tokenize_loop(readline, tokeneater) # except StopTokenizing: # pass # # Path: py3kwarn2to3/fixer_util.py # def find_root(node): # """Find the top level namespace.""" # # Scamper up to the top level namespace # while node.type != syms.file_input: # assert node.parent, "Tree is insane! root found before "\ # "file_input node was found." # node = node.parent # return node . Output only the next line.
for p in pat.content:
Here is a snippet: <|code_start|> of the pattern types which will match first. """ if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)): # NodePatters must either have no type and no content # or a type and content -- so they don't get any farther # Always return leafs if pat.type is None: raise _EveryNode return set([pat.type]) if isinstance(pat, pytree.NegatedPattern): if pat.content: return _get_head_types(pat.content) raise _EveryNode # Negated Patterns don't have a type if isinstance(pat, pytree.WildcardPattern): # Recurse on each node in content r = set() for p in pat.content: for x in p: r.update(_get_head_types(x)) return r raise Exception("Oh no! I don't understand pattern %s" %(pat)) def _get_headnode_dict(fixer_list): """ Accepts a list of fixers and returns a dictionary of head node type --> fixer list. """ head_nodes = collections.defaultdict(list) <|code_end|> . Write the next line using the current file imports: import os import sys import logging import operator import collections import codecs import multiprocessing from StringIO import StringIO from io import StringIO from itertools import chain from .pgen2 import driver, parse, tokenize, token from .fixer_util import find_root from . import pytree, pygram from . import btm_matcher as bm and context from other files: # Path: py3kwarn2to3/pgen2/driver.py # class Driver(object): # def __init__(self, grammar, convert=None, logger=None): # def parse_tokens(self, tokens, debug=False): # def parse_stream_raw(self, stream, debug=False): # def parse_stream(self, stream, debug=False): # def parse_file(self, filename, encoding=None, debug=False): # def parse_string(self, text, debug=False): # def load_grammar(gt="Grammar.txt", gp=None, # save=True, force=False, logger=None): # def _newer(a, b): # # Path: py3kwarn2to3/pgen2/tokenize.py # def tokenize(readline, tokeneater=printtoken): # """ # The tokenize() function accepts two parameters: one representing the # input stream, and one providing an output mechanism for tokenize(). # # The first parameter, readline, must be a callable object which provides # the same interface as the readline() method of built-in file objects. # Each call to the function should return one line of input as a string. # # The second parameter, tokeneater, must also be a callable object. It is # called once for each token, with five arguments, corresponding to the # tuples generated by generate_tokens(). # """ # try: # tokenize_loop(readline, tokeneater) # except StopTokenizing: # pass # # Path: py3kwarn2to3/fixer_util.py # def find_root(node): # """Find the top level namespace.""" # # Scamper up to the top level namespace # while node.type != syms.file_input: # assert node.parent, "Tree is insane! root found before "\ # "file_input node was found." # node = node.parent # return node , which may include functions, classes, or code. Output only the next line.
every = []
Based on the snippet: <|code_start|># coding=utf-8 from __future__ import print_function from __future__ import unicode_literals try: unicode except NameError: unicode = str def to_warn_str(node): lines = [text.strip() for text in unicode(node).split('\n')] for i, line in enumerate(lines): if line: <|code_end|> , predict the immediate next line with the help of imports: from itertools import chain from . import __version__ from py3kwarn2to3 import refactor, pytree from py3kwarn2to3.fixer_util import find_root import sys import optparse import multiprocessing and context (classes, functions, sometimes code) from other files: # Path: py3kwarn2to3/refactor.py # def refactor(self, items, write=False, doctests_only=False): # """Refactor a list of files and directories.""" # # for dir_or_file in items: # if os.path.isdir(dir_or_file): # self.refactor_dir(dir_or_file, write, doctests_only) # else: # self.refactor_file(dir_or_file, write, doctests_only) # # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_util.py # def find_root(node): # """Find the top level namespace.""" # # Scamper up to the top level namespace # while node.type != syms.file_input: # assert node.parent, "Tree is insane! root found before "\ # "file_input node was found." # node = node.parent # return node . Output only the next line.
if line.startswith('#'):
Next line prediction: <|code_start|> del lines[i] elif line[-1] != ':': lines[i] = line + ';' return ''.join(lines).strip() class WarnRefactoringTool(refactor.MultiprocessRefactoringTool): def __init__(self, fixer_names, options=None, explicit=None): super(WarnRefactoringTool, self).__init__( fixer_names, options, explicit) self.warnings = [] def _append_warning(self, warning): self.warnings.append(warning) def add_to_warnings(self, filename, fixer, node, new): fixer_name = fixer.__class__.__name__ from_string = to_warn_str(node) to_string = to_warn_str(new) warning = '{0} -> {1}'.format(from_string, to_string) self._append_warning(( node.get_lineno(), '{filename}:{line}:1: PY3K ({fixer}) {warning}'.format( filename=filename, line=node.get_lineno(), fixer=fixer_name, <|code_end|> . Use current file imports: (from itertools import chain from . import __version__ from py3kwarn2to3 import refactor, pytree from py3kwarn2to3.fixer_util import find_root import sys import optparse import multiprocessing) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/refactor.py # def refactor(self, items, write=False, doctests_only=False): # """Refactor a list of files and directories.""" # # for dir_or_file in items: # if os.path.isdir(dir_or_file): # self.refactor_dir(dir_or_file, write, doctests_only) # else: # self.refactor_file(dir_or_file, write, doctests_only) # # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_util.py # def find_root(node): # """Find the top level namespace.""" # # Scamper up to the top level namespace # while node.type != syms.file_input: # assert node.parent, "Tree is insane! root found before "\ # "file_input node was found." # node = node.parent # return node . Output only the next line.
warning=warning)))
Predict the next line for this snippet: <|code_start|># coding=utf-8 from __future__ import print_function from __future__ import unicode_literals try: unicode except NameError: unicode = str def to_warn_str(node): lines = [text.strip() for text in unicode(node).split('\n')] for i, line in enumerate(lines): <|code_end|> with the help of current file imports: from itertools import chain from . import __version__ from py3kwarn2to3 import refactor, pytree from py3kwarn2to3.fixer_util import find_root import sys import optparse import multiprocessing and context from other files: # Path: py3kwarn2to3/refactor.py # def refactor(self, items, write=False, doctests_only=False): # """Refactor a list of files and directories.""" # # for dir_or_file in items: # if os.path.isdir(dir_or_file): # self.refactor_dir(dir_or_file, write, doctests_only) # else: # self.refactor_file(dir_or_file, write, doctests_only) # # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_util.py # def find_root(node): # """Find the top level namespace.""" # # Scamper up to the top level namespace # while node.type != syms.file_input: # assert node.parent, "Tree is insane! root found before "\ # "file_input node was found." # node = node.parent # return node , which may contain function names, class names, or code. Output only the next line.
if line:
Given snippet: <|code_start|>""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ ( sys_import=import_name<'import' ('sys' | <|code_end|> , continue by predicting the next line. Consider current file imports: from py3kwarn2to3 import pytree, fixer_base from py3kwarn2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms and context: # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): which might include code, classes, or functions. Output only the next line.
dotted_as_names< (any ',')* 'sys' (',' any)* >
Predict the next line after this snippet: <|code_start|>""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ ( sys_import=import_name<'import' ('sys' | dotted_as_names< (any ',')* 'sys' (',' any)* > ) > | expr_stmt< <|code_end|> using the current file's imports: from py3kwarn2to3 import pytree, fixer_base from py3kwarn2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms and any relevant context from other files: # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
power< 'sys' trailer< '.' 'exitfunc' > >
Using the snippet: <|code_start|>""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ <|code_end|> , determine the next line of code. You have imports: from py3kwarn2to3 import pytree, fixer_base from py3kwarn2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms and context (class names, function names, or code) available: # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
(
Predict the next line after this snippet: <|code_start|>""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ ( sys_import=import_name<'import' ('sys' | dotted_as_names< (any ',')* 'sys' (',' any)* > ) > <|code_end|> using the current file's imports: from py3kwarn2to3 import pytree, fixer_base from py3kwarn2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms and any relevant context from other files: # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
|
Based on the snippet: <|code_start|>""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ ( sys_import=import_name<'import' ('sys' | dotted_as_names< (any ',')* 'sys' (',' any)* > ) > | <|code_end|> , predict the immediate next line with the help of imports: from py3kwarn2to3 import pytree, fixer_base from py3kwarn2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms and context (classes, functions, sometimes code) from other files: # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
expr_stmt<
Using the snippet: <|code_start|>""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ ( sys_import=import_name<'import' ('sys' | <|code_end|> , determine the next line of code. You have imports: from py3kwarn2to3 import pytree, fixer_base from py3kwarn2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms and context (class names, function names, or code) available: # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
dotted_as_names< (any ',')* 'sys' (',' any)* >
Next line prediction: <|code_start|>""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ ( sys_import=import_name<'import' ('sys' | dotted_as_names< (any ',')* 'sys' (',' any)* > ) <|code_end|> . Use current file imports: (from py3kwarn2to3 import pytree, fixer_base from py3kwarn2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
>
Given the code snippet: <|code_start|>""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ ( sys_import=import_name<'import' <|code_end|> , generate the next line using the imports in this file: from py3kwarn2to3 import pytree, fixer_base from py3kwarn2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/pytree.py # HUGE = 0x7FFFFFFF # maximum repeat count, default max # def type_repr(type_num): # def __new__(cls, *args, **kwds): # def __eq__(self, other): # def __ne__(self, other): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def set_prefix(self, prefix): # def get_prefix(self): # def replace(self, new): # def get_lineno(self): # def changed(self): # def remove(self): # def next_sibling(self): # def prev_sibling(self): # def leaves(self): # def depth(self): # def get_suffix(self): # def __str__(self): # def __init__(self,type, children, # context=None, # prefix=None, # fixers_applied=None): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def set_child(self, i, child): # def insert_child(self, i, child): # def append_child(self, child): # def __init__(self, type, value, # context=None, # prefix=None, # fixers_applied=[]): # def __repr__(self): # def __unicode__(self): # def _eq(self, other): # def clone(self): # def leaves(self): # def post_order(self): # def pre_order(self): # def _prefix_getter(self): # def _prefix_setter(self, prefix): # def convert(gr, raw_node): # def __new__(cls, *args, **kwds): # def __repr__(self): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def __init__(self, type=None, content=None, name=None): # def match(self, node, results=None): # def _submatch(self, node, results=None): # def __init__(self, type=None, content=None, name=None): # def _submatch(self, node, results=None): # def __init__(self, content=None, min=0, max=HUGE, name=None): # def optimize(self): # def match(self, node, results=None): # def match_seq(self, nodes, results=None): # def generate_matches(self, nodes): # def _iterative_matches(self, nodes): # def _bare_name_matches(self, nodes): # def _recursive_matches(self, nodes, count): # def __init__(self, content=None): # def match(self, node): # def match_seq(self, nodes): # def generate_matches(self, nodes): # def generate_matches(patterns, nodes): # class Base(object): # class Node(Base): # class Leaf(Base): # class BasePattern(object): # class LeafPattern(BasePattern): # class NodePattern(BasePattern): # class WildcardPattern(BasePattern): # class NegatedPattern(BasePattern): # # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
('sys'
Next line prediction: <|code_start|># Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for exec. This converts usages of the exec statement into calls to a built-in exec() function. exec code in ns1, ns2 -> exec(code, ns1, ns2) """ # Local imports class FixExec(fixer_base.BaseFix): BM_compatible = True PATTERN = """ exec_stmt< 'exec' a=any 'in' b=any [',' c=any] > | <|code_end|> . Use current file imports: (from .. import fixer_base from ..fixer_util import Comma, Name, Call) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_util.py # def Comma(): # """A comma leaf""" # return Leaf(token.COMMA, u",") # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node . Output only the next line.
exec_stmt< 'exec' (not atom<'(' [any] ')'>) a=any >
Using the snippet: <|code_start|># Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for exec. This converts usages of the exec statement into calls to a built-in exec() function. exec code in ns1, ns2 -> exec(code, ns1, ns2) """ # Local imports class FixExec(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> , determine the next line of code. You have imports: from .. import fixer_base from ..fixer_util import Comma, Name, Call and context (class names, function names, or code) available: # Path: py3kwarn2to3/fixer_util.py # def Comma(): # """A comma leaf""" # return Leaf(token.COMMA, u",") # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node . Output only the next line.
exec_stmt< 'exec' a=any 'in' b=any [',' c=any] >
Given the following code snippet before the placeholder: <|code_start|># Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for exec. This converts usages of the exec statement into calls to a built-in exec() function. exec code in ns1, ns2 -> exec(code, ns1, ns2) """ # Local imports class FixExec(fixer_base.BaseFix): BM_compatible = True PATTERN = """ exec_stmt< 'exec' a=any 'in' b=any [',' c=any] > | <|code_end|> , predict the next line using imports from the current file: from .. import fixer_base from ..fixer_util import Comma, Name, Call and context including class names, function names, and sometimes code from other files: # Path: py3kwarn2to3/fixer_util.py # def Comma(): # """A comma leaf""" # return Leaf(token.COMMA, u",") # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node . Output only the next line.
exec_stmt< 'exec' (not atom<'(' [any] ')'>) a=any >
Continue the code snippet: <|code_start|># Copyright 2008 Armin Ronacher. # Licensed to PSF under a Contributor Agreement. """Fixer for reduce(). Makes sure reduce() is imported from the functools module if reduce is used in that module. """ class FixReduce(fixer_base.BaseFix): BM_compatible = True order = "pre" PATTERN = """ power< 'reduce' trailer< '(' arglist< ( (not(argument<any '=' any>) any ',' not(argument<any '=' any>) any) | (not(argument<any '=' any>) any ',' not(argument<any '=' any>) any ',' not(argument<any '=' any>) any) ) > <|code_end|> . Use current file imports: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import touch_import and context (classes, functions, or code) from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
')' >
Here is a snippet: <|code_start|># Copyright 2008 Armin Ronacher. # Licensed to PSF under a Contributor Agreement. """Fixer for reduce(). Makes sure reduce() is imported from the functools module if reduce is used in that module. """ class FixReduce(fixer_base.BaseFix): BM_compatible = True order = "pre" PATTERN = """ power< 'reduce' trailer< '(' arglist< ( <|code_end|> . Write the next line using the current file imports: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import touch_import and context from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) , which may include functions, classes, or code. Output only the next line.
(not(argument<any '=' any>) any ','
Given the following code snippet before the placeholder: <|code_start|> class MinNode(object): """This class serves as an intermediate representation of the pattern tree during the conversion to sets of leaf-to-root subpatterns""" def __init__(self, type=None, name=None): self.type = type self.name = name self.children = [] self.leaf = False self.parent = None self.alternatives = [] self.group = [] def __repr__(self): return str(self.type) + ' ' + str(self.name) def leaf_to_root(self): """Internal method. Returns a characteristic path of the pattern tree. This method must be run for all leaves until the linear subpatterns are merged into a single""" node = self subp = [] while node: if node.type == TYPE_ALTERNATIVES: node.alternatives.append(subp) if len(node.alternatives) == len(node.children): #last alternative subp = [tuple(node.alternatives)] <|code_end|> , predict the next line using imports from the current file: from . import pytree from .pgen2 import grammar, token from .pygram import pattern_symbols, python_symbols and context including class names, function names, and sometimes code from other files: # Path: py3kwarn2to3/pgen2/grammar.py # class Grammar(object): # def __init__(self): # def dump(self, filename): # def load(self, filename): # def copy(self): # def report(self): # # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): . Output only the next line.
node.alternatives = []
Continue the code snippet: <|code_start|> self.group = [] def __repr__(self): return str(self.type) + ' ' + str(self.name) def leaf_to_root(self): """Internal method. Returns a characteristic path of the pattern tree. This method must be run for all leaves until the linear subpatterns are merged into a single""" node = self subp = [] while node: if node.type == TYPE_ALTERNATIVES: node.alternatives.append(subp) if len(node.alternatives) == len(node.children): #last alternative subp = [tuple(node.alternatives)] node.alternatives = [] node = node.parent continue else: node = node.parent subp = None break if node.type == TYPE_GROUP: node.group.append(subp) #probably should check the number of leaves if len(node.group) == len(node.children): subp = get_characteristic_subpattern(node.group) <|code_end|> . Use current file imports: from . import pytree from .pgen2 import grammar, token from .pygram import pattern_symbols, python_symbols and context (classes, functions, or code) from other files: # Path: py3kwarn2to3/pgen2/grammar.py # class Grammar(object): # def __init__(self): # def dump(self, filename): # def load(self, filename): # def copy(self): # def report(self): # # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): . Output only the next line.
node.group = []
Given the following code snippet before the placeholder: <|code_start|> def __init__(self, type=None, name=None): self.type = type self.name = name self.children = [] self.leaf = False self.parent = None self.alternatives = [] self.group = [] def __repr__(self): return str(self.type) + ' ' + str(self.name) def leaf_to_root(self): """Internal method. Returns a characteristic path of the pattern tree. This method must be run for all leaves until the linear subpatterns are merged into a single""" node = self subp = [] while node: if node.type == TYPE_ALTERNATIVES: node.alternatives.append(subp) if len(node.alternatives) == len(node.children): #last alternative subp = [tuple(node.alternatives)] node.alternatives = [] node = node.parent continue else: node = node.parent <|code_end|> , predict the next line using imports from the current file: from . import pytree from .pgen2 import grammar, token from .pygram import pattern_symbols, python_symbols and context including class names, function names, and sometimes code from other files: # Path: py3kwarn2to3/pgen2/grammar.py # class Grammar(object): # def __init__(self): # def dump(self, filename): # def load(self, filename): # def copy(self): # def report(self): # # Path: py3kwarn2to3/pygram.py # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") # class Symbols(object): # def __init__(self, grammar): . Output only the next line.
subp = None
Continue the code snippet: <|code_start|> remove_trailing_newline(simple_node) yield (node, i, simple_node) def fixup_indent(suite): """ If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start """ kids = suite.children[::-1] # find the first indent while kids: node = kids.pop() if node.type == token.INDENT: break # find the first Leaf while kids: node = kids.pop() if isinstance(node, Leaf) and node.type != token.DEDENT: if node.prefix: node.prefix = u'' return else: kids.extend(node.children[::-1]) class FixMetaclass(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> . Use current file imports: from .. import fixer_base from ..pgen2 import token from ..fixer_util import syms from ..fixer_util import Node from ..fixer_util import Leaf and context (classes, functions, or code) from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
classdef<any*>
Next line prediction: <|code_start|> remove_trailing_newline(simple_node) yield (node, i, simple_node) def fixup_indent(suite): """ If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start """ kids = suite.children[::-1] # find the first indent while kids: node = kids.pop() if node.type == token.INDENT: break # find the first Leaf while kids: node = kids.pop() if isinstance(node, Leaf) and node.type != token.DEDENT: if node.prefix: node.prefix = u'' return else: kids.extend(node.children[::-1]) class FixMetaclass(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> . Use current file imports: (from .. import fixer_base from ..pgen2 import token from ..fixer_util import syms from ..fixer_util import Node from ..fixer_util import Leaf) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
classdef<any*>
Using the snippet: <|code_start|> remove_trailing_newline(simple_node) yield (node, i, simple_node) def fixup_indent(suite): """ If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start """ kids = suite.children[::-1] # find the first indent while kids: node = kids.pop() if node.type == token.INDENT: break # find the first Leaf while kids: node = kids.pop() if isinstance(node, Leaf) and node.type != token.DEDENT: if node.prefix: node.prefix = u'' return else: kids.extend(node.children[::-1]) class FixMetaclass(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> , determine the next line of code. You have imports: from .. import fixer_base from ..pgen2 import token from ..fixer_util import syms from ..fixer_util import Node from ..fixer_util import Leaf and context (class names, function names, or code) available: # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
classdef<any*>
Here is a snippet: <|code_start|>"""Fixer for __nonzero__ -> __bool__ methods.""" # Author: Collin Winter # Local imports class FixNonzero(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> . Write the next line using the current file imports: from .. import fixer_base from ..fixer_util import Name and context from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) , which may include functions, classes, or code. Output only the next line.
classdef< 'class' any+ ':'
Predict the next line for this snippet: <|code_start|>"""Fixer that changes raw_input(...) into input(...).""" # Author: Andre Roberge class FixRawInput(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> with the help of current file imports: from .. import fixer_base from ..fixer_util import Name from ..fixer_util import find_binding and context from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # Path: py3kwarn2to3/fixer_util.py # def find_binding(name, node, package=None): # """ Returns the node which binds variable name, otherwise None. # If optional argument package is supplied, only imports will # be returned. # See test cases for examples.""" # for child in node.children: # ret = None # if child.type == syms.for_stmt: # if _find(name, child.children[1]): # return child # n = find_binding(name, make_suite(child.children[-1]), package) # if n: ret = n # elif child.type in (syms.if_stmt, syms.while_stmt): # n = find_binding(name, make_suite(child.children[-1]), package) # if n: ret = n # elif child.type == syms.try_stmt: # n = find_binding(name, make_suite(child.children[2]), package) # if n: # ret = n # else: # for i, kid in enumerate(child.children[3:]): # if kid.type == token.COLON and kid.value == ":": # # i+3 is the colon, i+4 is the suite # n = find_binding(name, make_suite(child.children[i+4]), package) # if n: ret = n # elif child.type in _def_syms and child.children[1].value == name: # ret = child # elif _is_import_binding(child, name, package): # ret = child # elif child.type == syms.simple_stmt: # ret = find_binding(name, child, package) # elif child.type == syms.expr_stmt: # if _find(name, child.children[0]): # ret = child # # if ret: # if not package: # return ret # if is_import(ret): # return ret # return None , which may contain function names, class names, or code. Output only the next line.
power< name='raw_input' trailer< '(' [any] ')' > any* >
Predict the next line after this snippet: <|code_start|>"""Fixer that changes raw_input(...) into input(...).""" # Author: Andre Roberge class FixRawInput(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> using the current file's imports: from .. import fixer_base from ..fixer_util import Name from ..fixer_util import find_binding and any relevant context from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # Path: py3kwarn2to3/fixer_util.py # def find_binding(name, node, package=None): # """ Returns the node which binds variable name, otherwise None. # If optional argument package is supplied, only imports will # be returned. # See test cases for examples.""" # for child in node.children: # ret = None # if child.type == syms.for_stmt: # if _find(name, child.children[1]): # return child # n = find_binding(name, make_suite(child.children[-1]), package) # if n: ret = n # elif child.type in (syms.if_stmt, syms.while_stmt): # n = find_binding(name, make_suite(child.children[-1]), package) # if n: ret = n # elif child.type == syms.try_stmt: # n = find_binding(name, make_suite(child.children[2]), package) # if n: # ret = n # else: # for i, kid in enumerate(child.children[3:]): # if kid.type == token.COLON and kid.value == ":": # # i+3 is the colon, i+4 is the suite # n = find_binding(name, make_suite(child.children[i+4]), package) # if n: ret = n # elif child.type in _def_syms and child.children[1].value == name: # ret = child # elif _is_import_binding(child, name, package): # ret = child # elif child.type == syms.simple_stmt: # ret = find_binding(name, child, package) # elif child.type == syms.expr_stmt: # if _find(name, child.children[0]): # ret = child # # if ret: # if not package: # return ret # if is_import(ret): # return ret # return None . Output only the next line.
power< name='raw_input' trailer< '(' [any] ')' > any* >
Given snippet: <|code_start|>""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """ # Local imports class FixItertoolsImports(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> , continue by predicting the next line. Consider current file imports: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import BlankLine, syms, token and context: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): which might include code, classes, or functions. Output only the next line.
import_from< 'from' 'itertools' 'import' imports=any >
Predict the next line for this snippet: <|code_start|>""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """ # Local imports class FixItertoolsImports(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> with the help of current file imports: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import BlankLine, syms, token and context from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): , which may contain function names, class names, or code. Output only the next line.
import_from< 'from' 'itertools' 'import' imports=any >
Next line prediction: <|code_start|>""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """ # Local imports class FixItertoolsImports(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> . Use current file imports: (from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import BlankLine, syms, token) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): . Output only the next line.
import_from< 'from' 'itertools' 'import' imports=any >
Here is a snippet: <|code_start|>""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """ # Local imports class FixItertoolsImports(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> . Write the next line using the current file imports: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import BlankLine, syms, token and context from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def KeywordArg(keyword, value): # def LParen(): # def RParen(): # def Assign(target, source): # def Name(name, prefix=None): # def Attr(obj, attr): # def Comma(): # def Dot(): # def ArgList(args, lparen=LParen(), rparen=RParen()): # def Call(func_name, args=None, prefix=None): # def Newline(): # def BlankLine(): # def Number(n, prefix=None): # def Subscript(index_node): # def String(string, prefix=None): # def ListComp(xp, fp, it, test=None): # def FromImport(package_name, name_leafs): # def is_tuple(node): # def is_list(node): # def parenthesize(node): # def attr_chain(obj, attr): # def in_special_context(node): # def is_probably_builtin(node): # def find_indentation(node): # def make_suite(node): # def find_root(node): # def does_tree_import(package, name, node): # def is_import(node): # def touch_import(package, name, node): # def is_import_stmt(node): # def find_binding(name, node, package=None): # def _find(name, node): # def _is_import_binding(node, name, package=None): , which may include functions, classes, or code. Output only the next line.
import_from< 'from' 'itertools' 'import' imports=any >
Given the code snippet: <|code_start|># Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for callable(). This converts callable(obj) into isinstance(obj, collections.Callable), adding a collections import if needed.""" # Local imports class FixCallable(fixer_base.BaseFix): BM_compatible = True order = "pre" # Ignore callable(*args) or use of keywords. # Either could be a hint that the builtin callable() is not being used. PATTERN = """ power< 'callable' trailer< lpar='(' <|code_end|> , generate the next line using the imports in this file: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, Attr, touch_import and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def Attr(obj, attr): # """A node tuple for obj.attr""" # return [obj, Node(syms.trailer, [Dot(), attr])] # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
( not(arglist | argument<any '=' any>) func=any
Predict the next line for this snippet: <|code_start|># Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for callable(). This converts callable(obj) into isinstance(obj, collections.Callable), adding a collections import if needed.""" # Local imports class FixCallable(fixer_base.BaseFix): BM_compatible = True order = "pre" # Ignore callable(*args) or use of keywords. # Either could be a hint that the builtin callable() is not being used. PATTERN = """ power< 'callable' trailer< lpar='(' ( not(arglist | argument<any '=' any>) func=any | func=arglist<(not argument<any '=' any>) any ','> ) rpar=')' > <|code_end|> with the help of current file imports: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, Attr, touch_import and context from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def Attr(obj, attr): # """A node tuple for obj.attr""" # return [obj, Node(syms.trailer, [Dot(), attr])] # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) , which may contain function names, class names, or code. Output only the next line.
after=any*
Given the code snippet: <|code_start|># Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for callable(). This converts callable(obj) into isinstance(obj, collections.Callable), adding a collections import if needed.""" # Local imports class FixCallable(fixer_base.BaseFix): BM_compatible = True order = "pre" # Ignore callable(*args) or use of keywords. # Either could be a hint that the builtin callable() is not being used. PATTERN = """ <|code_end|> , generate the next line using the imports in this file: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, Attr, touch_import and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def Attr(obj, attr): # """A node tuple for obj.attr""" # return [obj, Node(syms.trailer, [Dot(), attr])] # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
power< 'callable'
Next line prediction: <|code_start|># Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for callable(). This converts callable(obj) into isinstance(obj, collections.Callable), adding a collections import if needed.""" # Local imports class FixCallable(fixer_base.BaseFix): BM_compatible = True order = "pre" # Ignore callable(*args) or use of keywords. # Either could be a hint that the builtin callable() is not being used. PATTERN = """ <|code_end|> . Use current file imports: (from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, Attr, touch_import) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def Attr(obj, attr): # """A node tuple for obj.attr""" # return [obj, Node(syms.trailer, [Dot(), attr])] # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
power< 'callable'
Continue the code snippet: <|code_start|># Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for callable(). This converts callable(obj) into isinstance(obj, collections.Callable), adding a collections import if needed.""" # Local imports class FixCallable(fixer_base.BaseFix): BM_compatible = True order = "pre" # Ignore callable(*args) or use of keywords. # Either could be a hint that the builtin callable() is not being used. <|code_end|> . Use current file imports: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, Attr, touch_import and context (classes, functions, or code) from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def Attr(obj, attr): # """A node tuple for obj.attr""" # return [obj, Node(syms.trailer, [Dot(), attr])] # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
PATTERN = """
Using the snippet: <|code_start|># Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for callable(). This converts callable(obj) into isinstance(obj, collections.Callable), adding a collections import if needed.""" # Local imports class FixCallable(fixer_base.BaseFix): BM_compatible = True order = "pre" # Ignore callable(*args) or use of keywords. # Either could be a hint that the builtin callable() is not being used. <|code_end|> , determine the next line of code. You have imports: from py3kwarn2to3 import fixer_base from py3kwarn2to3.fixer_util import Call, Name, String, Attr, touch_import and context (class names, function names, or code) available: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # class ConditionalFix(BaseFix): # PATTERN = None # Most subclasses should override with a string literal # PC = PatternCompiler() # def __init__(self, options, log): # def compile_pattern(self): # def set_filename(self, filename): # def match(self, node): # def transform(self, node, results): # def new_name(self, template=u"xxx_todo_changeme"): # def log_message(self, message): # def cannot_convert(self, node, reason=None): # def warning(self, node, reason): # def start_tree(self, tree, filename): # def finish_tree(self, tree, filename): # def start_tree(self, *args): # def should_skip(self, node): # # Path: py3kwarn2to3/fixer_util.py # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) # # def Attr(obj, attr): # """A node tuple for obj.attr""" # return [obj, Node(syms.trailer, [Dot(), attr])] # # def touch_import(package, name, node): # """ Works like `does_tree_import` but adds an import statement # if it was not imported. """ # def is_import_stmt(node): # return (node.type == syms.simple_stmt and node.children and # is_import(node.children[0])) # # root = find_root(node) # # if does_tree_import(package, name, root): # return # # # figure out where to insert the new import. First try to find # # the first import and then skip to the last one. # insert_pos = offset = 0 # for idx, node in enumerate(root.children): # if not is_import_stmt(node): # continue # for offset, node2 in enumerate(root.children[idx:]): # if not is_import_stmt(node2): # break # insert_pos = idx + offset # break # # # if there are no imports where we can insert, find the docstring. # # if that also fails, we stick to the beginning of the file # if insert_pos == 0: # for idx, node in enumerate(root.children): # if (node.type == syms.simple_stmt and node.children and # node.children[0].type == token.STRING): # insert_pos = idx + 1 # break # # if package is None: # import_ = Node(syms.import_name, [ # Leaf(token.NAME, u"import"), # Leaf(token.NAME, name, prefix=u" ") # ]) # else: # import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) # # children = [import_, Newline()] # root.insert_child(insert_pos, Node(syms.simple_stmt, children)) . Output only the next line.
PATTERN = """
Next line prediction: <|code_start|># Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports parend_expr = patcomp.compile_pattern( """atom< '(' [arith_expr|atom|power|term|STRING|NAME] ')' >""" ) class FixPrint(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> . Use current file imports: (from .. import patcomp from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, Call, Comma, String) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Comma(): # """A comma leaf""" # return Leaf(token.COMMA, u",") # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) . Output only the next line.
simple_stmt< any* bare='print' any* > | print_stmt
Given snippet: <|code_start|># Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports parend_expr = patcomp.compile_pattern( """atom< '(' [arith_expr|atom|power|term|STRING|NAME] ')' >""" ) class FixPrint(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> , continue by predicting the next line. Consider current file imports: from .. import patcomp from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, Call, Comma, String and context: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Comma(): # """A comma leaf""" # return Leaf(token.COMMA, u",") # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) which might include code, classes, or functions. Output only the next line.
simple_stmt< any* bare='print' any* > | print_stmt
Given snippet: <|code_start|># Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports parend_expr = patcomp.compile_pattern( """atom< '(' [arith_expr|atom|power|term|STRING|NAME] ')' >""" ) class FixPrint(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> , continue by predicting the next line. Consider current file imports: from .. import patcomp from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, Call, Comma, String and context: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Comma(): # """A comma leaf""" # return Leaf(token.COMMA, u",") # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) which might include code, classes, or functions. Output only the next line.
simple_stmt< any* bare='print' any* > | print_stmt
Here is a snippet: <|code_start|># Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports parend_expr = patcomp.compile_pattern( """atom< '(' [arith_expr|atom|power|term|STRING|NAME] ')' >""" ) class FixPrint(fixer_base.BaseFix): BM_compatible = True PATTERN = """ <|code_end|> . Write the next line using the current file imports: from .. import patcomp from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, Call, Comma, String and context from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def Comma(): # """A comma leaf""" # return Leaf(token.COMMA, u",") # # def String(string, prefix=None): # """A string leaf""" # return Leaf(token.STRING, string, prefix=prefix) , which may include functions, classes, or code. Output only the next line.
simple_stmt< any* bare='print' any* > | print_stmt
Given the code snippet: <|code_start|> be added using the add_fixer method""" def __init__(self): self.match = set() self.root = BMNode() self.nodes = [self.root] self.fixers = [] self.logger = logging.getLogger("RefactoringTool") def add_fixer(self, fixer): """Reduces a fixer's pattern tree to a linear path and adds it to the matcher(a common Aho-Corasick automaton). The fixer is appended on the matching states and called when they are reached""" self.fixers.append(fixer) tree = reduce_tree(fixer.pattern_tree) linear = tree.get_linear_subpattern() match_nodes = self.add(linear, start=self.root) for match_node in match_nodes: match_node.fixers.append(fixer) def add(self, pattern, start): "Recursively adds a linear pattern to the AC automaton" #print("adding pattern", pattern, "to", start) if not pattern: #print("empty pattern") return [start] if isinstance(pattern[0], tuple): #alternatives #print("alternatives") <|code_end|> , generate the next line using the imports in this file: import logging import itertools from collections import defaultdict from . import pytree from .btm_utils import reduce_tree from .pygram import python_symbols and context (functions, classes, or occasionally code) from other files: # Path: py3kwarn2to3/btm_utils.py # def reduce_tree(node, parent=None): # """ # Internal function. Reduces a compiled pattern tree to an # intermediate representation suitable for feeding the # automaton. This also trims off any optional pattern elements(like # [a], a*). # """ # # new_node = None # #switch on the node type # if node.type == syms.Matcher: # #skip # node = node.children[0] # # if node.type == syms.Alternatives: # #2 cases # if len(node.children) <= 2: # #just a single 'Alternative', skip this node # new_node = reduce_tree(node.children[0], parent) # else: # #real alternatives # new_node = MinNode(type=TYPE_ALTERNATIVES) # #skip odd children('|' tokens) # for child in node.children: # if node.children.index(child) % 2: # continue # reduced = reduce_tree(child, new_node) # if reduced is not None: # new_node.children.append(reduced) # elif node.type == syms.Alternative: # if len(node.children) > 1: # # new_node = MinNode(type=TYPE_GROUP) # for child in node.children: # reduced = reduce_tree(child, new_node) # if reduced: # new_node.children.append(reduced) # if not new_node.children: # # delete the group if all of the children were reduced to None # new_node = None # # else: # new_node = reduce_tree(node.children[0], parent) # # elif node.type == syms.Unit: # if (isinstance(node.children[0], pytree.Leaf) and # node.children[0].value == '('): # #skip parentheses # return reduce_tree(node.children[1], parent) # if ((isinstance(node.children[0], pytree.Leaf) and # node.children[0].value == '[') # or # (len(node.children)>1 and # hasattr(node.children[1], "value") and # node.children[1].value == '[')): # #skip whole unit if its optional # return None # # leaf = True # details_node = None # alternatives_node = None # has_repeater = False # repeater_node = None # has_variable_name = False # # for child in node.children: # if child.type == syms.Details: # leaf = False # details_node = child # elif child.type == syms.Repeater: # has_repeater = True # repeater_node = child # elif child.type == syms.Alternatives: # alternatives_node = child # if hasattr(child, 'value') and child.value == '=': # variable name # has_variable_name = True # # #skip variable name # if has_variable_name: # #skip variable name, '=' # name_leaf = node.children[2] # if hasattr(name_leaf, 'value') and name_leaf.value == '(': # # skip parenthesis # name_leaf = node.children[3] # else: # name_leaf = node.children[0] # # #set node type # if name_leaf.type == token_labels.NAME: # #(python) non-name or wildcard # if name_leaf.value == 'any': # new_node = MinNode(type=TYPE_ANY) # else: # if hasattr(token_labels, name_leaf.value): # new_node = MinNode(type=getattr(token_labels, name_leaf.value)) # else: # new_node = MinNode(type=getattr(pysyms, name_leaf.value)) # # elif name_leaf.type == token_labels.STRING: # #(python) name or character; remove the apostrophes from # #the string value # name = name_leaf.value.strip("'") # if name in tokens: # new_node = MinNode(type=tokens[name]) # else: # new_node = MinNode(type=token_labels.NAME, name=name) # elif name_leaf.type == syms.Alternatives: # new_node = reduce_tree(alternatives_node, parent) # # #handle repeaters # if has_repeater: # if repeater_node.children[0].value == '*': # #reduce to None # new_node = None # elif repeater_node.children[0].value == '+': # #reduce to a single occurrence i.e. do nothing # pass # else: # #TODO: handle {min, max} repeaters # raise NotImplementedError # # #add children # if details_node and new_node is not None: # for child in details_node.children[1:-1]: # #skip '<', '>' markers # reduced = reduce_tree(child, new_node) # if reduced is not None: # new_node.children.append(reduced) # if new_node: # new_node.parent = parent # return new_node . Output only the next line.
match_nodes = []
Here is a snippet: <|code_start|> class FixParrot(BaseFix): """ Change functions named 'parrot' to 'cheese'. """ PATTERN = """funcdef < 'def' name='parrot' any* >""" <|code_end|> . Write the next line using the current file imports: from py3kwarn2to3.fixer_base import BaseFix from py3kwarn2to3.fixer_util import Name and context from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # # """Optional base class for fixers. # # The subclass name must be FixFooBar where FooBar is the result of # removing underscores and capitalizing the words of the fix name. # For example, the class name for a fixer named 'has_key' should be # FixHasKey. # """ # # PATTERN = None # Most subclasses should override with a string literal # pattern = None # Compiled pattern, set by compile_pattern() # pattern_tree = None # Tree representation of the pattern # options = None # Options object passed to initializer # filename = None # The filename (set by set_filename) # logger = None # A logger (set by set_filename) # numbers = itertools.count(1) # For new_name() # used_names = set() # A set of all used NAMEs # order = "post" # Does the fixer prefer pre- or post-order traversal # explicit = False # Is this ignored by refactor.py -f all? # run_order = 5 # Fixers will be sorted by run order before execution # # Lower numbers will be run first. # _accept_type = None # [Advanced and not public] This tells RefactoringTool # # which node type to accept when there's not a pattern. # # keep_line_order = False # For the bottom matcher: match with the # # original line order # BM_compatible = False # Compatibility with the bottom matching # # module; every fixer should set this # # manually # # # Shortcut for access to Python grammar symbols # syms = pygram.python_symbols # # def __init__(self, options, log): # """Initializer. Subclass may override. # # Args: # options: an dict containing the options passed to RefactoringTool # that could be used to customize the fixer through the command line. # log: a list to append warnings and other messages to. # """ # self.options = options # self.log = log # self.compile_pattern() # # def compile_pattern(self): # """Compiles self.PATTERN into self.pattern. # # Subclass may override if it doesn't want to use # self.{pattern,PATTERN} in .match(). # """ # if self.PATTERN is not None: # PC = PatternCompiler() # self.pattern, self.pattern_tree = PC.compile_pattern(self.PATTERN, # with_tree=True) # # def set_filename(self, filename): # """Set the filename, and a logger derived from it. # # The main refactoring tool should call this. # """ # self.filename = filename # self.logger = logging.getLogger(filename) # # def match(self, node): # """Returns match for a given parse tree node. # # Should return a true or false object (not necessarily a bool). # It may return a non-empty dict of matching sub-nodes as # returned by a matching pattern. # # Subclass may override. # """ # results = {"node": node} # return self.pattern.match(node, results) and results # # def transform(self, node, results): # """Returns the transformation for a given parse tree node. # # Args: # node: the root of the parse tree that matched the fixer. # results: a dict mapping symbolic names to part of the match. # # Returns: # None, or a node that is a modified copy of the # argument node. The node argument may also be modified in-place to # effect the same change. # # Subclass *must* override. # """ # raise NotImplementedError() # # def new_name(self, template=u"xxx_todo_changeme"): # """Return a string suitable for use as an identifier # # The new name is guaranteed not to conflict with other identifiers. # """ # name = template # while name in self.used_names: # name = template + unicode(next(self.numbers)) # self.used_names.add(name) # return name # # def log_message(self, message): # if self.first_log: # self.first_log = False # self.log.append("### In file %s ###" % self.filename) # self.log.append(message) # # def cannot_convert(self, node, reason=None): # """Warn the user that a given chunk of code is not valid Python 3, # but that it cannot be converted automatically. # # First argument is the top-level node for the code in question. # Optional second argument is why it can't be converted. # """ # lineno = node.get_lineno() # for_output = node.clone() # for_output.prefix = u"" # msg = "Line %d: could not convert: %s" # self.log_message(msg % (lineno, for_output)) # if reason: # self.log_message(reason) # # def warning(self, node, reason): # """Used for warning the user about possible uncertainty in the # translation. # # First argument is the top-level node for the code in question. # Optional second argument is why it can't be converted. # """ # lineno = node.get_lineno() # self.log_message("Line %d: %s" % (lineno, reason)) # # def start_tree(self, tree, filename): # """Some fixers need to maintain tree-wide state. # This method is called once, at the start of tree fix-up. # # tree - the root node of the tree to be processed. # filename - the name of the file the tree came from. # """ # self.used_names = tree.used_names # self.set_filename(filename) # self.numbers = itertools.count(1) # self.first_log = True # # def finish_tree(self, tree, filename): # """Some fixers need to maintain tree-wide state. # This method is called once, at the conclusion of tree fix-up. # # tree - the root node of the tree to be processed. # filename - the name of the file the tree came from. # """ # # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) , which may include functions, classes, or code. Output only the next line.
def transform(self, node, results):
Here is a snippet: <|code_start|> class FixParrot(BaseFix): """ Change functions named 'parrot' to 'cheese'. """ PATTERN = """funcdef < 'def' name='parrot' any* >""" <|code_end|> . Write the next line using the current file imports: from py3kwarn2to3.fixer_base import BaseFix from py3kwarn2to3.fixer_util import Name and context from other files: # Path: py3kwarn2to3/fixer_base.py # class BaseFix(object): # # """Optional base class for fixers. # # The subclass name must be FixFooBar where FooBar is the result of # removing underscores and capitalizing the words of the fix name. # For example, the class name for a fixer named 'has_key' should be # FixHasKey. # """ # # PATTERN = None # Most subclasses should override with a string literal # pattern = None # Compiled pattern, set by compile_pattern() # pattern_tree = None # Tree representation of the pattern # options = None # Options object passed to initializer # filename = None # The filename (set by set_filename) # logger = None # A logger (set by set_filename) # numbers = itertools.count(1) # For new_name() # used_names = set() # A set of all used NAMEs # order = "post" # Does the fixer prefer pre- or post-order traversal # explicit = False # Is this ignored by refactor.py -f all? # run_order = 5 # Fixers will be sorted by run order before execution # # Lower numbers will be run first. # _accept_type = None # [Advanced and not public] This tells RefactoringTool # # which node type to accept when there's not a pattern. # # keep_line_order = False # For the bottom matcher: match with the # # original line order # BM_compatible = False # Compatibility with the bottom matching # # module; every fixer should set this # # manually # # # Shortcut for access to Python grammar symbols # syms = pygram.python_symbols # # def __init__(self, options, log): # """Initializer. Subclass may override. # # Args: # options: an dict containing the options passed to RefactoringTool # that could be used to customize the fixer through the command line. # log: a list to append warnings and other messages to. # """ # self.options = options # self.log = log # self.compile_pattern() # # def compile_pattern(self): # """Compiles self.PATTERN into self.pattern. # # Subclass may override if it doesn't want to use # self.{pattern,PATTERN} in .match(). # """ # if self.PATTERN is not None: # PC = PatternCompiler() # self.pattern, self.pattern_tree = PC.compile_pattern(self.PATTERN, # with_tree=True) # # def set_filename(self, filename): # """Set the filename, and a logger derived from it. # # The main refactoring tool should call this. # """ # self.filename = filename # self.logger = logging.getLogger(filename) # # def match(self, node): # """Returns match for a given parse tree node. # # Should return a true or false object (not necessarily a bool). # It may return a non-empty dict of matching sub-nodes as # returned by a matching pattern. # # Subclass may override. # """ # results = {"node": node} # return self.pattern.match(node, results) and results # # def transform(self, node, results): # """Returns the transformation for a given parse tree node. # # Args: # node: the root of the parse tree that matched the fixer. # results: a dict mapping symbolic names to part of the match. # # Returns: # None, or a node that is a modified copy of the # argument node. The node argument may also be modified in-place to # effect the same change. # # Subclass *must* override. # """ # raise NotImplementedError() # # def new_name(self, template=u"xxx_todo_changeme"): # """Return a string suitable for use as an identifier # # The new name is guaranteed not to conflict with other identifiers. # """ # name = template # while name in self.used_names: # name = template + unicode(next(self.numbers)) # self.used_names.add(name) # return name # # def log_message(self, message): # if self.first_log: # self.first_log = False # self.log.append("### In file %s ###" % self.filename) # self.log.append(message) # # def cannot_convert(self, node, reason=None): # """Warn the user that a given chunk of code is not valid Python 3, # but that it cannot be converted automatically. # # First argument is the top-level node for the code in question. # Optional second argument is why it can't be converted. # """ # lineno = node.get_lineno() # for_output = node.clone() # for_output.prefix = u"" # msg = "Line %d: could not convert: %s" # self.log_message(msg % (lineno, for_output)) # if reason: # self.log_message(reason) # # def warning(self, node, reason): # """Used for warning the user about possible uncertainty in the # translation. # # First argument is the top-level node for the code in question. # Optional second argument is why it can't be converted. # """ # lineno = node.get_lineno() # self.log_message("Line %d: %s" % (lineno, reason)) # # def start_tree(self, tree, filename): # """Some fixers need to maintain tree-wide state. # This method is called once, at the start of tree fix-up. # # tree - the root node of the tree to be processed. # filename - the name of the file the tree came from. # """ # self.used_names = tree.used_names # self.set_filename(filename) # self.numbers = itertools.count(1) # self.first_log = True # # def finish_tree(self, tree, filename): # """Some fixers need to maintain tree-wide state. # This method is called once, at the conclusion of tree fix-up. # # tree - the root node of the tree to be processed. # filename - the name of the file the tree came from. # """ # # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) , which may include functions, classes, or code. Output only the next line.
def transform(self, node, results):
Next line prediction: <|code_start|>in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V in <>:. NOTE: This is still not correct if the original code was depending on filter(F, X) to return a string if X is a string and a tuple if X is a tuple. That would require type inference, which we don't do. Let Python 2.6 figure it out. """ # Local imports class FixFilter(fixer_base.ConditionalFix): BM_compatible = True PATTERN = """ filter_lambda=power< 'filter' trailer< '(' arglist< lambdef< 'lambda' (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any > ',' it=any > ')' > > | <|code_end|> . Use current file imports: (from .. import fixer_base from ..fixer_util import Name, Call, ListComp, in_special_context) and context including class names, function names, or small code snippets from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def ListComp(xp, fp, it, test=None): # """A list comprehension of the form [xp for fp in it if test]. # # If test is None, the "if test" part is omitted. # """ # xp.prefix = u"" # fp.prefix = u" " # it.prefix = u" " # for_leaf = Leaf(token.NAME, u"for") # for_leaf.prefix = u" " # in_leaf = Leaf(token.NAME, u"in") # in_leaf.prefix = u" " # inner_args = [for_leaf, fp, in_leaf, it] # if test: # test.prefix = u" " # if_leaf = Leaf(token.NAME, u"if") # if_leaf.prefix = u" " # inner_args.append(Node(syms.comp_if, [if_leaf, test])) # inner = Node(syms.listmaker, [xp, Node(syms.comp_for, inner_args)]) # return Node(syms.atom, # [Leaf(token.LBRACE, u"["), # inner, # Leaf(token.RBRACE, u"]")]) # # def in_special_context(node): # """ Returns true if node is in an environment where all that is required # of it is being itterable (ie, it doesn't matter if it returns a list # or an itterator). # See test_map_nochange in test_fixers.py for some examples and tests. # """ # global p0, p1, p2, pats_built # if not pats_built: # p1 = patcomp.compile_pattern(p1) # p0 = patcomp.compile_pattern(p0) # p2 = patcomp.compile_pattern(p2) # pats_built = True # patterns = [p0, p1, p2] # for pattern, parent in zip(patterns, attr_chain(node, "parent")): # results = {} # if pattern.match(parent, results) and results["node"] is node: # return True # return False . Output only the next line.
power<
Here is a snippet: <|code_start|> # Local imports class FixFilter(fixer_base.ConditionalFix): BM_compatible = True PATTERN = """ filter_lambda=power< 'filter' trailer< '(' arglist< lambdef< 'lambda' (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any > ',' it=any > ')' > > | power< 'filter' trailer< '(' arglist< none='None' ',' seq=any > ')' > > | power< 'filter' args=trailer< '(' [any] ')' > <|code_end|> . Write the next line using the current file imports: from .. import fixer_base from ..fixer_util import Name, Call, ListComp, in_special_context and context from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def ListComp(xp, fp, it, test=None): # """A list comprehension of the form [xp for fp in it if test]. # # If test is None, the "if test" part is omitted. # """ # xp.prefix = u"" # fp.prefix = u" " # it.prefix = u" " # for_leaf = Leaf(token.NAME, u"for") # for_leaf.prefix = u" " # in_leaf = Leaf(token.NAME, u"in") # in_leaf.prefix = u" " # inner_args = [for_leaf, fp, in_leaf, it] # if test: # test.prefix = u" " # if_leaf = Leaf(token.NAME, u"if") # if_leaf.prefix = u" " # inner_args.append(Node(syms.comp_if, [if_leaf, test])) # inner = Node(syms.listmaker, [xp, Node(syms.comp_for, inner_args)]) # return Node(syms.atom, # [Leaf(token.LBRACE, u"["), # inner, # Leaf(token.RBRACE, u"]")]) # # def in_special_context(node): # """ Returns true if node is in an environment where all that is required # of it is being itterable (ie, it doesn't matter if it returns a list # or an itterator). # See test_map_nochange in test_fixers.py for some examples and tests. # """ # global p0, p1, p2, pats_built # if not pats_built: # p1 = patcomp.compile_pattern(p1) # p0 = patcomp.compile_pattern(p0) # p2 = patcomp.compile_pattern(p2) # pats_built = True # patterns = [p0, p1, p2] # for pattern, parent in zip(patterns, attr_chain(node, "parent")): # results = {} # if pattern.match(parent, results) and results["node"] is node: # return True # return False , which may include functions, classes, or code. Output only the next line.
>
Here is a snippet: <|code_start|>NOTE: This is still not correct if the original code was depending on filter(F, X) to return a string if X is a string and a tuple if X is a tuple. That would require type inference, which we don't do. Let Python 2.6 figure it out. """ # Local imports class FixFilter(fixer_base.ConditionalFix): BM_compatible = True PATTERN = """ filter_lambda=power< 'filter' trailer< '(' arglist< lambdef< 'lambda' (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any > ',' it=any > ')' > > | power< 'filter' trailer< '(' arglist< none='None' ',' seq=any > ')' > <|code_end|> . Write the next line using the current file imports: from .. import fixer_base from ..fixer_util import Name, Call, ListComp, in_special_context and context from other files: # Path: py3kwarn2to3/fixer_util.py # def Name(name, prefix=None): # """Return a NAME leaf""" # return Leaf(token.NAME, name, prefix=prefix) # # def Call(func_name, args=None, prefix=None): # """A function call""" # node = Node(syms.power, [func_name, ArgList(args)]) # if prefix is not None: # node.prefix = prefix # return node # # def ListComp(xp, fp, it, test=None): # """A list comprehension of the form [xp for fp in it if test]. # # If test is None, the "if test" part is omitted. # """ # xp.prefix = u"" # fp.prefix = u" " # it.prefix = u" " # for_leaf = Leaf(token.NAME, u"for") # for_leaf.prefix = u" " # in_leaf = Leaf(token.NAME, u"in") # in_leaf.prefix = u" " # inner_args = [for_leaf, fp, in_leaf, it] # if test: # test.prefix = u" " # if_leaf = Leaf(token.NAME, u"if") # if_leaf.prefix = u" " # inner_args.append(Node(syms.comp_if, [if_leaf, test])) # inner = Node(syms.listmaker, [xp, Node(syms.comp_for, inner_args)]) # return Node(syms.atom, # [Leaf(token.LBRACE, u"["), # inner, # Leaf(token.RBRACE, u"]")]) # # def in_special_context(node): # """ Returns true if node is in an environment where all that is required # of it is being itterable (ie, it doesn't matter if it returns a list # or an itterator). # See test_map_nochange in test_fixers.py for some examples and tests. # """ # global p0, p1, p2, pats_built # if not pats_built: # p1 = patcomp.compile_pattern(p1) # p0 = patcomp.compile_pattern(p0) # p2 = patcomp.compile_pattern(p2) # pats_built = True # patterns = [p0, p1, p2] # for pattern, parent in zip(patterns, attr_chain(node, "parent")): # results = {} # if pattern.match(parent, results) and results["node"] is node: # return True # return False , which may include functions, classes, or code. Output only the next line.
>