Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|>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|> using the current file's imports: from .. import fixer_base from ..fixer_util import Name, Call, ListComp, in_special_context 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) # # 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.
|
Continue the code snippet: <|code_start|> def handle_unmatchable(*args, **kwargs): # return 'unmatchable page', 404 data = get_base_data() return render_template('main/404.html', **data), 404 def page_not_found(e): data = get_base_data() return render_template('main/404.html', **data), 404 # return '404 page', 404 def handle_bad_request(e): return 'bad request!', 400 def handle_forbidden(e): # return 'request forbidden', 403 <|code_end|> . Use current file imports: from flask import render_template from .views import get_base_data and context (classes, functions, or code) from other files: # Path: app/main/views.py # def get_base_data(): # pages = models.Post.objects.filter(post_type='page', is_draft=False) # blog_meta = OctBlogSettings['blog_meta'] # data = { # 'blog_meta': blog_meta, # 'pages': pages, # 'bg_home': BACKGROUND['home'], # 'bg_post': BACKGROUND['post'], # 'bg_about': BACKGROUND['about'], # 'qiniu': BACKGROUND['qiniu'], # 'allow_daovoice': DAOVOICE['allow_daovoice'], # 'dao_app_id': DAOVOICE['app_id'], # } # return data . Output only the next line.
return render_template('blog_admin/403.html', msg=e.description), 403
Given the code snippet: <|code_start|> user.save() return redirect(url_for('accounts.users')) return render_template('accounts/registration.html', form=form) def get_current_user(): user = models.User.objects.get(username=current_user.username) return user class Users(MethodView): decorators = [login_required, admin_permission.require(401)] template_name = 'accounts/users.html' def get(self): users = models.User.objects.all() return render_template(self.template_name, users=users) class User(MethodView): decorators = [login_required, admin_permission.require(401)] template_name = 'accounts/user.html' def get_context(self, username, form=None): if not form: user = models.User.objects.get_or_404(username=username) form = forms.UserForm(obj=user) data = {'form':form, 'user': user} return data def get(self, username, form=None): <|code_end|> , generate the next line using the imports in this file: import datetime from flask import render_template, redirect, request, flash, url_for, current_app, session, abort from flask.views import MethodView from flask_login import login_user, logout_user, login_required, current_user from flask_principal import Identity, AnonymousIdentity, identity_changed from . import models, forms, misc from .permissions import admin_permission, su_permission from OctBlog.config import OctBlogSettings and context (functions, classes, or occasionally code) from other files: # Path: app/accounts/permissions.py # def on_identity_loaded(sender, identity): . Output only the next line.
data = self.get_context(username, form)
Given snippet: <|code_start|> user.biography = form.biography.data user.homepage_url = form.homepage_url.data or None user.social_networks['weibo']['url'] = form.weibo.data or None user.social_networks['weixin']['url'] = form.weixin.data or None user.social_networks['twitter']['url'] = form.twitter.data or None user.social_networks['github']['url'] = form.github.data or None user.social_networks['facebook']['url'] = form.facebook.data or None user.social_networks['linkedin']['url'] = form.linkedin.data or None user.save() msg = 'Succeed to update user profile' flash(msg, 'success') return redirect(url_for('accounts.su_edit_user', username=user.username)) return self.get(form) class Profile(MethodView): decorators = [login_required] template_name = 'accounts/settings.html' def get(self, form=None): if not form: # user = get_current_user() user = current_user user.weibo = user.social_networks['weibo'].get('url') user.weixin = user.social_networks['weixin'].get('url') user.twitter = user.social_networks['twitter'].get('url') user.github = user.social_networks['github'].get('url') user.facebook = user.social_networks['facebook'].get('url') <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime from flask import render_template, redirect, request, flash, url_for, current_app, session, abort from flask.views import MethodView from flask_login import login_user, logout_user, login_required, current_user from flask_principal import Identity, AnonymousIdentity, identity_changed from . import models, forms, misc from .permissions import admin_permission, su_permission from OctBlog.config import OctBlogSettings and context: # Path: app/accounts/permissions.py # def on_identity_loaded(sender, identity): which might include code, classes, or functions. Output only the next line.
user.linkedin = user.social_networks['linkedin'].get('url')
Given the code snippet: <|code_start|> class SubmitFormBuilder(WagtailCaptchaFormBuilder if has_recaptcha() else FormBuilder): def get_form_class(self): form_class = super(SubmitFormBuilder, self).get_form_class() form_class.required_css_class = 'required' <|code_end|> , generate the next line using the imports in this file: from core.utilities import has_recaptcha from wagtail.wagtailforms.forms import FormBuilder from wagtailcaptcha.forms import WagtailCaptchaFormBuilder and context (functions, classes, or occasionally code) from other files: # Path: core/utilities.py # def has_recaptcha(): # """ # Check if the WagtailCaptcha settings are properly set # """ # wagtailcaptcha_public_key = getattr(settings, 'RECAPTCHA_PUBLIC_KEY', None) # wagtailcaptcha_private_key = getattr(settings, 'RECAPTCHA_PRIVATE_KEY', None) # # return wagtailcaptcha_public_key and wagtailcaptcha_private_key . Output only the next line.
return form_class
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger('core') # Signals for Models. Some for performing specific class tasks, some just for clearing the cache. # Set your own classes PAGE_CLASSES = [WagtailPage] @receiver(pre_save) <|code_end|> , predict the next line using imports from the current file: import logging import re from datetime import timedelta from urllib.error import HTTPError from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils.encoding import force_text from core.models import WagtailPage, WagtailSitePage from core.utilities import replace_tags from slackweb import Slack from wagtail.wagtailcore.models import PageRevision from wagtail.wagtailcore.signals import page_published and context including class names, function names, and sometimes code from other files: # Path: core/models.py # class WagtailPage(Page): # """ # Our main custom Page class. All content pages should inherit from this one. # """ # # parent_types = ['core.HomePage'] # subpage_types = ['core.WagtailPage'] # # is_creatable = False # # feed_image = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+' # ) # body = RichTextField(blank=True, features=['bold', 'italic', 'ol', 'ul', 'link', 'cleanhtml']) # tags = ClusterTaggableManager(through=PageTag, blank=True) # search_fields = [] # # @property # def parent(self): # try: # return self.get_ancestors().reverse()[0] # except IndexError: # return None # # @property # def child(self): # for related_object in self._meta.get_all_related_objects(): # if not issubclass(related_object.model, self.__class__): # continue # try: # return getattr(self, related_object.get_accessor_name()) # except ObjectDoesNotExist: # pass # # @property # def body_text(self): # return BeautifulSoup(self.body, "html5lib").get_text() # # @property # def body_excerpt(self): # """ # Return body text replacing end of lines (. ? ! chars) with a blank space # """ # return re.sub(r'([\.?!])([a-zA-Z])', r'\1 \2', self.body_text) # # @property # def og_image(self): # # Returns image and image type of feed_image or image as fallback, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # class Meta: # verbose_name = "Content Page" # # content_panels = panels.WAGTAIL_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_PAGE_PROMOTE_PANELS # # class WagtailSitePage(WagtailPage): # """ # Site page # """ # parent_types = ['core.WagtailCompanyPage'] # subpage_types = [] # is_featured = models.BooleanField( # "Featured", # default=False, # blank=False, # help_text='If enabled, this site will appear on top of the sites list of the homepage.' # ) # site_screenshot = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+', # help_text=mark_safe( # 'Use a <b>ratio</b> of <i>16:13.28</i> ' # 'and a <b>size</b> of at least <i>1200x996 pixels</i> ' # 'for an optimal display.' # ), # ) # site_url = models.URLField( # blank=True, # null=True, # help_text='The URL of your site, something like "https://www.springload.co.nz"', # ) # # in_cooperation_with = models.ForeignKey( # 'core.WagtailCompanyPage', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+', # ) # # search_fields = Page.search_fields + [ # index.SearchField('site_url'), # index.SearchField('body_text') # ] # # @property # def og_image(self): # # Returns image and image type of feed_image, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # elif self.site_screenshot: # image['image'] = self.site_screenshot # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # def __str__(self): # if self.site_url: # return '%s - %s' % (self.title, self.site_url) # return self.title # # class Meta: # verbose_name = "Site Page" # # content_panels = panels.WAGTAIL_SITE_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_SITE_PAGE_PROMOTE_PANELS # # Path: core/utilities.py # def replace_tags(string=None, tags=dict()): # """ # Replace tags from a given string # """ # if string is None: # raise TypeError("string type needed") # else: # for key, value in tags.items(): # string = string.replace(key, value) # return string . Output only the next line.
def pre_page_save(sender, instance, **kwargs):
Here is a snippet: <|code_start|> #Tests can't use manage.py createcachetable due to temporary database, so use dummy CACHES = DEV_CACHES.copy() TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ normpath(join(DJANGO_ROOT, 'core/templates')), ], <|code_end|> . Write the next line using the current file imports: from .base import * from .grains.logging import DEV_LOGGING from .grains.cache import * from .grains.cache import DEV_CACHES and context from other files: # Path: madewithwagtail/settings/grains/logging.py # DEV_LOGGING = { # 'version': 1, # 'disable_existing_loggers': True, # 'formatters': {}, # 'handlers': { # "dev_console": { # "level": "DEBUG", # "class": "logging.StreamHandler", # "stream": sys.stderr, # }, # }, # "root": { # using root logger to catch and log all interesting messages # "level": "WARNING", # "handlers": ["dev_console"], # }, # 'loggers': { # 'django': { # 'handlers': ['dev_console'], # 'propagate': False, # 'level': 'INFO', # }, # 'core': { # 'handlers': ['dev_console'], # 'propagate': False, # 'level': 'DEBUG', # } # } # } # # Path: madewithwagtail/settings/grains/cache.py # DEV_CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', # } # } , which may include functions, classes, or code. Output only the next line.
'APP_DIRS': True,
Given snippet: <|code_start|> #Tests can't use manage.py createcachetable due to temporary database, so use dummy CACHES = DEV_CACHES.copy() TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ normpath(join(DJANGO_ROOT, 'core/templates')), ], 'APP_DIRS': True, 'OPTIONS': { 'debug': True, <|code_end|> , continue by predicting the next line. Consider current file imports: from .base import * from .grains.logging import DEV_LOGGING from .grains.cache import * from .grains.cache import DEV_CACHES and context: # Path: madewithwagtail/settings/grains/logging.py # DEV_LOGGING = { # 'version': 1, # 'disable_existing_loggers': True, # 'formatters': {}, # 'handlers': { # "dev_console": { # "level": "DEBUG", # "class": "logging.StreamHandler", # "stream": sys.stderr, # }, # }, # "root": { # using root logger to catch and log all interesting messages # "level": "WARNING", # "handlers": ["dev_console"], # }, # 'loggers': { # 'django': { # 'handlers': ['dev_console'], # 'propagate': False, # 'level': 'INFO', # }, # 'core': { # 'handlers': ['dev_console'], # 'propagate': False, # 'level': 'DEBUG', # } # } # } # # Path: madewithwagtail/settings/grains/cache.py # DEV_CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', # } # } which might include code, classes, or functions. Output only the next line.
'context_processors': ['django.template.context_processors.debug'] + CONTEXT_PROCESSORS
Here is a snippet: <|code_start|> class ClientTestCase(WagtailTest): def setUp(self): super(ClientTestCase, self).setUp() def testHomePage(self): home_page = HomePage.objects.all()[0] response = self.client.get(home_page.url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, home_page.template) # Check it comes with the appropiate number of pages pages = WagtailSitePage.objects.live().descendant_of(home_page) self.assertEqual(response.context['pages'].paginator.count, pages.count()) self.assertContains( response, 'one-half--medium one-third--large', count=response.context['pages'].paginator.count) # Check the first page is featured self.assertEqual(response.context['pages'][0].is_featured, True) # Check the tags are printed tags = Tag.objects.all().filter( <|code_end|> . Write the next line using the current file imports: from taggit.models import Tag from core.models import HomePage, WagtailSitePage from core.tests.utils import WagtailTest and context from other files: # Path: core/models.py # class HomePage(Page, IndexPage): # """ # HomePage class, inheriting from wagtailcore.Page straight away # """ # # subpage_types = [ # 'core.CompanyIndex', # 'core.SubmitFormPage', # ] # feed_image = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+' # ) # search_fields = [] # # body = RichTextField(blank=True, features=['bold', 'italic', 'ol', 'ul', 'link', 'cleanhtml']) # # @property # def og_image(self): # # Returns image and image type of feed_image, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # def children(self): # return self.get_children().live() # # def get_context(self, request, *args, **kwargs): # # Get pages # pages = WagtailSitePage.objects\ # .live()\ # .descendant_of(self)\ # .order_by('-is_featured', '-latest_revision_created_at') # # # Filter by tag # tag = request.GET.get('tag') # if tag: # pages = pages.filter(tags__slug__iexact=tag) # # # Pagination # page = request.GET.get('page') # paginator = Paginator(pages, 12) # Show 12 pages per page # try: # pages = paginator.page(page) # except PageNotAnInteger: # pages = paginator.page(1) # except EmptyPage: # pages = paginator.page(paginator.num_pages) # # # Update template context # context = super(HomePage, self).get_context(request, *args, **kwargs) # context['pages'] = pages # context['tag'] = tag # # Only tags used by live pages # context['tags'] = Tag.objects.filter( # core_pagetag_items__isnull=False, # core_pagetag_items__content_object__live=True # ).annotate(count=Count('core_pagetag_items')).distinct().order_by('-count', 'name') # # return context # # class Meta: # verbose_name = "Home Page" # # content_panels = panels.HOME_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_PAGE_PROMOTE_PANELS # # class WagtailSitePage(WagtailPage): # """ # Site page # """ # parent_types = ['core.WagtailCompanyPage'] # subpage_types = [] # is_featured = models.BooleanField( # "Featured", # default=False, # blank=False, # help_text='If enabled, this site will appear on top of the sites list of the homepage.' # ) # site_screenshot = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+', # help_text=mark_safe( # 'Use a <b>ratio</b> of <i>16:13.28</i> ' # 'and a <b>size</b> of at least <i>1200x996 pixels</i> ' # 'for an optimal display.' # ), # ) # site_url = models.URLField( # blank=True, # null=True, # help_text='The URL of your site, something like "https://www.springload.co.nz"', # ) # # in_cooperation_with = models.ForeignKey( # 'core.WagtailCompanyPage', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+', # ) # # search_fields = Page.search_fields + [ # index.SearchField('site_url'), # index.SearchField('body_text') # ] # # @property # def og_image(self): # # Returns image and image type of feed_image, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # elif self.site_screenshot: # image['image'] = self.site_screenshot # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # def __str__(self): # if self.site_url: # return '%s - %s' % (self.title, self.site_url) # return self.title # # class Meta: # verbose_name = "Site Page" # # content_panels = panels.WAGTAIL_SITE_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_SITE_PAGE_PROMOTE_PANELS # # Path: core/tests/utils.py # class WagtailTest(TestCase): # """ # TestCase that loads a number fo fixtures before each execution. # """ # def setUp(self): # call_command('loaddata', FIXTURES_FILE, verbosity=1) # self.client = Client() , which may include functions, classes, or code. Output only the next line.
core_pagetag_items__isnull=False,
Next line prediction: <|code_start|> class ClientTestCase(WagtailTest): def setUp(self): super(ClientTestCase, self).setUp() def testHomePage(self): home_page = HomePage.objects.all()[0] response = self.client.get(home_page.url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, home_page.template) # Check it comes with the appropiate number of pages pages = WagtailSitePage.objects.live().descendant_of(home_page) self.assertEqual(response.context['pages'].paginator.count, pages.count()) <|code_end|> . Use current file imports: (from taggit.models import Tag from core.models import HomePage, WagtailSitePage from core.tests.utils import WagtailTest) and context including class names, function names, or small code snippets from other files: # Path: core/models.py # class HomePage(Page, IndexPage): # """ # HomePage class, inheriting from wagtailcore.Page straight away # """ # # subpage_types = [ # 'core.CompanyIndex', # 'core.SubmitFormPage', # ] # feed_image = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+' # ) # search_fields = [] # # body = RichTextField(blank=True, features=['bold', 'italic', 'ol', 'ul', 'link', 'cleanhtml']) # # @property # def og_image(self): # # Returns image and image type of feed_image, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # def children(self): # return self.get_children().live() # # def get_context(self, request, *args, **kwargs): # # Get pages # pages = WagtailSitePage.objects\ # .live()\ # .descendant_of(self)\ # .order_by('-is_featured', '-latest_revision_created_at') # # # Filter by tag # tag = request.GET.get('tag') # if tag: # pages = pages.filter(tags__slug__iexact=tag) # # # Pagination # page = request.GET.get('page') # paginator = Paginator(pages, 12) # Show 12 pages per page # try: # pages = paginator.page(page) # except PageNotAnInteger: # pages = paginator.page(1) # except EmptyPage: # pages = paginator.page(paginator.num_pages) # # # Update template context # context = super(HomePage, self).get_context(request, *args, **kwargs) # context['pages'] = pages # context['tag'] = tag # # Only tags used by live pages # context['tags'] = Tag.objects.filter( # core_pagetag_items__isnull=False, # core_pagetag_items__content_object__live=True # ).annotate(count=Count('core_pagetag_items')).distinct().order_by('-count', 'name') # # return context # # class Meta: # verbose_name = "Home Page" # # content_panels = panels.HOME_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_PAGE_PROMOTE_PANELS # # class WagtailSitePage(WagtailPage): # """ # Site page # """ # parent_types = ['core.WagtailCompanyPage'] # subpage_types = [] # is_featured = models.BooleanField( # "Featured", # default=False, # blank=False, # help_text='If enabled, this site will appear on top of the sites list of the homepage.' # ) # site_screenshot = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+', # help_text=mark_safe( # 'Use a <b>ratio</b> of <i>16:13.28</i> ' # 'and a <b>size</b> of at least <i>1200x996 pixels</i> ' # 'for an optimal display.' # ), # ) # site_url = models.URLField( # blank=True, # null=True, # help_text='The URL of your site, something like "https://www.springload.co.nz"', # ) # # in_cooperation_with = models.ForeignKey( # 'core.WagtailCompanyPage', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+', # ) # # search_fields = Page.search_fields + [ # index.SearchField('site_url'), # index.SearchField('body_text') # ] # # @property # def og_image(self): # # Returns image and image type of feed_image, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # elif self.site_screenshot: # image['image'] = self.site_screenshot # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # def __str__(self): # if self.site_url: # return '%s - %s' % (self.title, self.site_url) # return self.title # # class Meta: # verbose_name = "Site Page" # # content_panels = panels.WAGTAIL_SITE_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_SITE_PAGE_PROMOTE_PANELS # # Path: core/tests/utils.py # class WagtailTest(TestCase): # """ # TestCase that loads a number fo fixtures before each execution. # """ # def setUp(self): # call_command('loaddata', FIXTURES_FILE, verbosity=1) # self.client = Client() . Output only the next line.
self.assertContains(
Predict the next line after this snippet: <|code_start|> class ClientTestCase(WagtailTest): def setUp(self): super(ClientTestCase, self).setUp() <|code_end|> using the current file's imports: from taggit.models import Tag from core.models import HomePage, WagtailSitePage from core.tests.utils import WagtailTest and any relevant context from other files: # Path: core/models.py # class HomePage(Page, IndexPage): # """ # HomePage class, inheriting from wagtailcore.Page straight away # """ # # subpage_types = [ # 'core.CompanyIndex', # 'core.SubmitFormPage', # ] # feed_image = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+' # ) # search_fields = [] # # body = RichTextField(blank=True, features=['bold', 'italic', 'ol', 'ul', 'link', 'cleanhtml']) # # @property # def og_image(self): # # Returns image and image type of feed_image, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # def children(self): # return self.get_children().live() # # def get_context(self, request, *args, **kwargs): # # Get pages # pages = WagtailSitePage.objects\ # .live()\ # .descendant_of(self)\ # .order_by('-is_featured', '-latest_revision_created_at') # # # Filter by tag # tag = request.GET.get('tag') # if tag: # pages = pages.filter(tags__slug__iexact=tag) # # # Pagination # page = request.GET.get('page') # paginator = Paginator(pages, 12) # Show 12 pages per page # try: # pages = paginator.page(page) # except PageNotAnInteger: # pages = paginator.page(1) # except EmptyPage: # pages = paginator.page(paginator.num_pages) # # # Update template context # context = super(HomePage, self).get_context(request, *args, **kwargs) # context['pages'] = pages # context['tag'] = tag # # Only tags used by live pages # context['tags'] = Tag.objects.filter( # core_pagetag_items__isnull=False, # core_pagetag_items__content_object__live=True # ).annotate(count=Count('core_pagetag_items')).distinct().order_by('-count', 'name') # # return context # # class Meta: # verbose_name = "Home Page" # # content_panels = panels.HOME_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_PAGE_PROMOTE_PANELS # # class WagtailSitePage(WagtailPage): # """ # Site page # """ # parent_types = ['core.WagtailCompanyPage'] # subpage_types = [] # is_featured = models.BooleanField( # "Featured", # default=False, # blank=False, # help_text='If enabled, this site will appear on top of the sites list of the homepage.' # ) # site_screenshot = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+', # help_text=mark_safe( # 'Use a <b>ratio</b> of <i>16:13.28</i> ' # 'and a <b>size</b> of at least <i>1200x996 pixels</i> ' # 'for an optimal display.' # ), # ) # site_url = models.URLField( # blank=True, # null=True, # help_text='The URL of your site, something like "https://www.springload.co.nz"', # ) # # in_cooperation_with = models.ForeignKey( # 'core.WagtailCompanyPage', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+', # ) # # search_fields = Page.search_fields + [ # index.SearchField('site_url'), # index.SearchField('body_text') # ] # # @property # def og_image(self): # # Returns image and image type of feed_image, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # elif self.site_screenshot: # image['image'] = self.site_screenshot # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # def __str__(self): # if self.site_url: # return '%s - %s' % (self.title, self.site_url) # return self.title # # class Meta: # verbose_name = "Site Page" # # content_panels = panels.WAGTAIL_SITE_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_SITE_PAGE_PROMOTE_PANELS # # Path: core/tests/utils.py # class WagtailTest(TestCase): # """ # TestCase that loads a number fo fixtures before each execution. # """ # def setUp(self): # call_command('loaddata', FIXTURES_FILE, verbosity=1) # self.client = Client() . Output only the next line.
def testHomePage(self):
Continue the code snippet: <|code_start|> class TemplateFiltersTestCase(WagtailTest): def setUp(self): super(TemplateFiltersTestCase, self).setUp() <|code_end|> . Use current file imports: from django.template import Context, Template from core.models import HomePage from core.tests.utils import WagtailTest and context (classes, functions, or code) from other files: # Path: core/models.py # class HomePage(Page, IndexPage): # """ # HomePage class, inheriting from wagtailcore.Page straight away # """ # # subpage_types = [ # 'core.CompanyIndex', # 'core.SubmitFormPage', # ] # feed_image = models.ForeignKey( # 'wagtailimages.Image', # null=True, # blank=True, # on_delete=models.SET_NULL, # related_name='+' # ) # search_fields = [] # # body = RichTextField(blank=True, features=['bold', 'italic', 'ol', 'ul', 'link', 'cleanhtml']) # # @property # def og_image(self): # # Returns image and image type of feed_image, if exists # image = {'image': None, 'type': None} # if self.feed_image: # image['image'] = self.feed_image # name, extension = os.path.splitext(image['image'].file.url) # image['type'] = extension[1:] # return image # # def children(self): # return self.get_children().live() # # def get_context(self, request, *args, **kwargs): # # Get pages # pages = WagtailSitePage.objects\ # .live()\ # .descendant_of(self)\ # .order_by('-is_featured', '-latest_revision_created_at') # # # Filter by tag # tag = request.GET.get('tag') # if tag: # pages = pages.filter(tags__slug__iexact=tag) # # # Pagination # page = request.GET.get('page') # paginator = Paginator(pages, 12) # Show 12 pages per page # try: # pages = paginator.page(page) # except PageNotAnInteger: # pages = paginator.page(1) # except EmptyPage: # pages = paginator.page(paginator.num_pages) # # # Update template context # context = super(HomePage, self).get_context(request, *args, **kwargs) # context['pages'] = pages # context['tag'] = tag # # Only tags used by live pages # context['tags'] = Tag.objects.filter( # core_pagetag_items__isnull=False, # core_pagetag_items__content_object__live=True # ).annotate(count=Count('core_pagetag_items')).distinct().order_by('-count', 'name') # # return context # # class Meta: # verbose_name = "Home Page" # # content_panels = panels.HOME_PAGE_CONTENT_PANELS # promote_panels = panels.WAGTAIL_PAGE_PROMOTE_PANELS # # Path: core/tests/utils.py # class WagtailTest(TestCase): # """ # TestCase that loads a number fo fixtures before each execution. # """ # def setUp(self): # call_command('loaddata', FIXTURES_FILE, verbosity=1) # self.client = Client() . Output only the next line.
def test_content_type(self):
Given snippet: <|code_start|> admin.autodiscover() # Register search signal handlers wagtailsearch_register_signal_handlers() urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^search/', include(wagtailsearch_urls)), url(r'^documents/', include(wagtaildocs_urls)), <|code_end|> , continue by predicting the next line. Consider current file imports: import os import debug_toolbar from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from api import urls as api_urls from wagtail.contrib.wagtailsitemaps.views import sitemap from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailimages import urls as wagtailimages_urls from wagtail.wagtailsearch import urls as wagtailsearch_urls from wagtail.wagtailsearch.signal_handlers import register_signal_handlers as wagtailsearch_register_signal_handlers from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.static import serve and context: # Path: api/urls.py which might include code, classes, or functions. Output only the next line.
url(r'^images/', include(wagtailimages_urls)),
Predict the next line for this snippet: <|code_start|> class WagtailCompanyPageTestCase(test_utils.WagtailTest): def test_twitter_handler(self): twitter_user = 'springloadnz' twitter_url = 'https://twitter.com/{}'.format(twitter_user) <|code_end|> with the help of current file imports: import core.tests.utils as test_utils from core import models and context from other files: # Path: core/models.py # class IndexPage(models.Model): # class Meta: # class HomePage(Page, IndexPage): # class Meta: # class CompanyIndex(Page, IndexPage): # class Meta: # class PageTag(TaggedItemBase): # class WagtailPage(Page): # class Meta: # class WagtailCompanyPage(WagtailPage): # class Meta: # class WagtailSitePage(WagtailPage): # class Meta: # class SubmitFormField(AbstractFormField): # class SubmitFormPage(WagtailCaptchaEmailForm if has_recaptcha() else AbstractEmailForm): # class Meta: # def clean(self): # def children(self): # def get_context(self, request, *args, **kwargs): # def og_image(self): # def children(self): # def get_context(self, request, *args, **kwargs): # def children(self): # def get_context(self, request, *args, **kwargs): # def parent(self): # def child(self): # def body_text(self): # def body_excerpt(self): # def og_image(self): # def lat(self): # def lon(self): # def twitter_handler(self): # def github_user(self): # def children_count(self): # def og_image(self): # def children(self): # def get_context(self, request, *args, **kwargs): # def sites_count(self): # def og_image(self): # def __str__(self): # def __init__(self, *args, **kwargs): # SITES_ORDERING_ALPHABETICAL = 'alphabetical' # SITES_ORDERING_CREATED = 'created' # SITES_ORDERING_PATH = 'path' # SITES_ORDERING = { # SITES_ORDERING_PATH: { # 'name': 'Path (i.e. manual)', # 'ordering': ['-path'], # }, # SITES_ORDERING_ALPHABETICAL: { # 'name': 'Alphabetical', # 'ordering': ['title'], # }, # SITES_ORDERING_CREATED: { # 'name': 'Created', # 'ordering': ['-first_published_at'], # }, # } # SITES_ORDERING_CHOICES = [ # (key, opts['name']) # for key, opts in sorted(SITES_ORDERING.items(), key=lambda k: k[1]['name']) # ] , which may contain function names, class names, or code. Output only the next line.
twitter_handle = '@{}'.format(twitter_user)
Using the snippet: <|code_start|> # Hacks to prevent pyroma from screwing up the logging system for everyone else old_config = logging.basicConfig try: logging.basicConfig = lambda **k: None finally: logging.basicConfig = old_config # Hacks so we can get the messages of these tests without running them. HACKS = ( ('PythonVersion', '_major_version_specified', False), ('ValidREST', '_message', ''), ('ClassifierVerification', '_incorrect', []), ('Licensing', '_message', ''), ) for clazz, attr, value in HACKS: if hasattr(ratings, clazz): <|code_end|> , determine the next line of code. You have imports: import logging import os import warnings from ..util import SysOutCapture from .base import Tool, Issue, ToolIssue from pyroma import projectdata, ratings and context (class names, function names, or code) available: # Path: src/tidypy/util.py # class SysOutCapture: # """ # A context manager that captures output to ``stdout`` and ``stderr`` during # the execution of the block. # """ # # def __init__(self): # self._original_streams = None # self._stdout = None # self._stderr = None # # def __enter__(self): # self._stdout = StringIO() # self._stderr = StringIO() # self._original_streams = (sys.stdout, sys.stderr) # sys.stdout, sys.stderr = self._stdout, self._stderr # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # sys.stdout, sys.stderr = self._original_streams # self._original_streams = None # # def get_stdout(self): # """ # Retrieves the content that was written to ``stdout``. # # :returns: str # """ # # return self._stdout.getvalue() # # def get_stderr(self): # """ # Retrieves the content that was written to ``stderr``. # # :returns: str # """ # # return self._stderr.getvalue() # # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ToolIssue(TidyPyIssue): # """ # An issue indicating that a tool completely crashed/failed during its # execution. # """ # # def __init__(self, message, project_path, details=None, failure=False): # if details: # if isinstance(details, tuple): # details = ''.join(traceback.format_exception(*details)) # message = '%s:\n%s' % (message, details) # # super().__init__( # 'tool', # message, # project_path, # ) # # self.pylint_type = 'F' if failure else 'E' . Output only the next line.
setattr(getattr(ratings, clazz), attr, value)
Given the following code snippet before the placeholder: <|code_start|> # Hacks to prevent pyroma from screwing up the logging system for everyone else old_config = logging.basicConfig try: logging.basicConfig = lambda **k: None finally: logging.basicConfig = old_config # Hacks so we can get the messages of these tests without running them. HACKS = ( ('PythonVersion', '_major_version_specified', False), <|code_end|> , predict the next line using imports from the current file: import logging import os import warnings from ..util import SysOutCapture from .base import Tool, Issue, ToolIssue from pyroma import projectdata, ratings and context including class names, function names, and sometimes code from other files: # Path: src/tidypy/util.py # class SysOutCapture: # """ # A context manager that captures output to ``stdout`` and ``stderr`` during # the execution of the block. # """ # # def __init__(self): # self._original_streams = None # self._stdout = None # self._stderr = None # # def __enter__(self): # self._stdout = StringIO() # self._stderr = StringIO() # self._original_streams = (sys.stdout, sys.stderr) # sys.stdout, sys.stderr = self._stdout, self._stderr # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # sys.stdout, sys.stderr = self._original_streams # self._original_streams = None # # def get_stdout(self): # """ # Retrieves the content that was written to ``stdout``. # # :returns: str # """ # # return self._stdout.getvalue() # # def get_stderr(self): # """ # Retrieves the content that was written to ``stderr``. # # :returns: str # """ # # return self._stderr.getvalue() # # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ToolIssue(TidyPyIssue): # """ # An issue indicating that a tool completely crashed/failed during its # execution. # """ # # def __init__(self, message, project_path, details=None, failure=False): # if details: # if isinstance(details, tuple): # details = ''.join(traceback.format_exception(*details)) # message = '%s:\n%s' % (message, details) # # super().__init__( # 'tool', # message, # project_path, # ) # # self.pylint_type = 'F' if failure else 'E' . Output only the next line.
('ValidREST', '_message', ''),
Predict the next line after this snippet: <|code_start|> # Hacks to prevent pyroma from screwing up the logging system for everyone else old_config = logging.basicConfig try: logging.basicConfig = lambda **k: None finally: logging.basicConfig = old_config # Hacks so we can get the messages of these tests without running them. HACKS = ( ('PythonVersion', '_major_version_specified', False), ('ValidREST', '_message', ''), ('ClassifierVerification', '_incorrect', []), ('Licensing', '_message', ''), <|code_end|> using the current file's imports: import logging import os import warnings from ..util import SysOutCapture from .base import Tool, Issue, ToolIssue from pyroma import projectdata, ratings and any relevant context from other files: # Path: src/tidypy/util.py # class SysOutCapture: # """ # A context manager that captures output to ``stdout`` and ``stderr`` during # the execution of the block. # """ # # def __init__(self): # self._original_streams = None # self._stdout = None # self._stderr = None # # def __enter__(self): # self._stdout = StringIO() # self._stderr = StringIO() # self._original_streams = (sys.stdout, sys.stderr) # sys.stdout, sys.stderr = self._stdout, self._stderr # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # sys.stdout, sys.stderr = self._original_streams # self._original_streams = None # # def get_stdout(self): # """ # Retrieves the content that was written to ``stdout``. # # :returns: str # """ # # return self._stdout.getvalue() # # def get_stderr(self): # """ # Retrieves the content that was written to ``stderr``. # # :returns: str # """ # # return self._stderr.getvalue() # # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ToolIssue(TidyPyIssue): # """ # An issue indicating that a tool completely crashed/failed during its # execution. # """ # # def __init__(self, message, project_path, details=None, failure=False): # if details: # if isinstance(details, tuple): # details = ''.join(traceback.format_exception(*details)) # message = '%s:\n%s' % (message, details) # # super().__init__( # 'tool', # message, # project_path, # ) # # self.pylint_type = 'F' if failure else 'E' . Output only the next line.
)
Here is a snippet: <|code_start|> class EradicateIssue(Issue): tool = 'eradicate' pylint_type = 'R' CODE = 'commented' <|code_end|> . Write the next line using the current file imports: from eradicate import Eradicator from .base import PythonTool, Issue, AccessIssue and context from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) , which may include functions, classes, or code. Output only the next line.
DESCRIPTION = 'Commented-out code'
Given the code snippet: <|code_start|> class EradicateIssue(Issue): tool = 'eradicate' pylint_type = 'R' <|code_end|> , generate the next line using the imports in this file: from eradicate import Eradicator from .base import PythonTool, Issue, AccessIssue and context (functions, classes, or occasionally code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) . Output only the next line.
CODE = 'commented'
Based on the snippet: <|code_start|> class EradicateIssue(Issue): tool = 'eradicate' pylint_type = 'R' CODE = 'commented' <|code_end|> , predict the immediate next line with the help of imports: from eradicate import Eradicator from .base import PythonTool, Issue, AccessIssue and context (classes, functions, sometimes code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) . Output only the next line.
DESCRIPTION = 'Commented-out code'
Given snippet: <|code_start|> class DetectSecretsIssue(Issue): tool = 'secrets' pylint_type = 'W' PLUGINS = tuple(get_mapping_from_secret_type_to_class().values()) <|code_end|> , continue by predicting the next line. Consider current file imports: from detect_secrets import SecretsCollection from detect_secrets.core.potential_secret import PotentialSecret from detect_secrets.core.plugins.util import \ get_mapping_from_secret_type_to_class from detect_secrets.settings import transient_settings from .base import Tool, Issue, AccessIssue, UnknownIssue and context: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) which might include code, classes, or functions. Output only the next line.
DESCRIPTION = 'Possible secret detected: {description}'
Next line prediction: <|code_start|> class DetectSecretsIssue(Issue): tool = 'secrets' pylint_type = 'W' <|code_end|> . Use current file imports: (from detect_secrets import SecretsCollection from detect_secrets.core.potential_secret import PotentialSecret from detect_secrets.core.plugins.util import \ get_mapping_from_secret_type_to_class from detect_secrets.settings import transient_settings from .base import Tool, Issue, AccessIssue, UnknownIssue) and context including class names, function names, or small code snippets from other files: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) . Output only the next line.
PLUGINS = tuple(get_mapping_from_secret_type_to_class().values())
Here is a snippet: <|code_start|> class VultureIssue(Issue): tool = 'vulture' pylint_type = 'R' class TidyPyVulture(Vulture): ISSUE_TYPES = ( ('unused-class', 'Unused class {entity}', 'unused_classes'), ('unused-function', 'Unused function {entity}', 'unused_funcs'), ('unused-import', 'Unused import {entity}', 'unused_imports'), ('unused-property', 'Unused property {entity}', 'unused_props'), ('unused-variable', 'Unused variable {entity}', 'unused_vars'), ('unused-attribute', 'Unused attribute {entity}', 'unused_attrs') ) def __init__(self, config): <|code_end|> . Write the next line using the current file imports: from pathlib import Path from vulture import Vulture, noqa from vulture.utils import VultureInputException from .base import PythonTool, Issue, ParseIssue, AccessIssue from ..util import parse_python_file and context from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] , which may include functions, classes, or code. Output only the next line.
ignore_names = config['options']['ignore-names']
Based on the snippet: <|code_start|> # Unfortunately instead of raising exceptions, this base implementation of # this method writes directly to stdout. This is a copy&paste with that # piece replaced by capturing an issue def scan(self, code, filename=''): self.code = code.splitlines() self.noqa_lines = noqa.parse_noqa(self.code) self.filename = Path(filename) try: node = parse_python_file(filename) except (SyntaxError, TypeError, ValueError) as err: self._tidypy_issues.append(ParseIssue(err, filename)) self.found_dead_code_or_error = True else: self.visit(node) def get_issues(self): issues = [] min_confidence = self.config['options']['min-confidence'] for code, template, prop_name in self.ISSUE_TYPES: if code in self.config['disabled']: continue for item in getattr(self, prop_name): if item.confidence < min_confidence: continue issues.append(VultureIssue( code, <|code_end|> , predict the immediate next line with the help of imports: from pathlib import Path from vulture import Vulture, noqa from vulture.utils import VultureInputException from .base import PythonTool, Issue, ParseIssue, AccessIssue from ..util import parse_python_file and context (classes, functions, sometimes code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] . Output only the next line.
template.format(entity=str(item)),
Given snippet: <|code_start|> class VultureIssue(Issue): tool = 'vulture' pylint_type = 'R' class TidyPyVulture(Vulture): ISSUE_TYPES = ( ('unused-class', 'Unused class {entity}', 'unused_classes'), ('unused-function', 'Unused function {entity}', 'unused_funcs'), ('unused-import', 'Unused import {entity}', 'unused_imports'), ('unused-property', 'Unused property {entity}', 'unused_props'), ('unused-variable', 'Unused variable {entity}', 'unused_vars'), ('unused-attribute', 'Unused attribute {entity}', 'unused_attrs') ) def __init__(self, config): ignore_names = config['options']['ignore-names'] if isinstance(ignore_names, str): ignore_names = ignore_names.split(',') ignore_decorators = config['options']['ignore-decorators'] if isinstance(ignore_decorators, str): <|code_end|> , continue by predicting the next line. Consider current file imports: from pathlib import Path from vulture import Vulture, noqa from vulture.utils import VultureInputException from .base import PythonTool, Issue, ParseIssue, AccessIssue from ..util import parse_python_file and context: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] which might include code, classes, or functions. Output only the next line.
ignore_decorators = ignore_decorators.split(',')
Here is a snippet: <|code_start|> # Unfortunately instead of raising exceptions, this base implementation of # this method writes directly to stdout. This is a copy&paste with that # piece replaced by capturing an issue def scan(self, code, filename=''): self.code = code.splitlines() self.noqa_lines = noqa.parse_noqa(self.code) self.filename = Path(filename) try: node = parse_python_file(filename) except (SyntaxError, TypeError, ValueError) as err: self._tidypy_issues.append(ParseIssue(err, filename)) self.found_dead_code_or_error = True else: self.visit(node) def get_issues(self): issues = [] min_confidence = self.config['options']['min-confidence'] for code, template, prop_name in self.ISSUE_TYPES: if code in self.config['disabled']: continue for item in getattr(self, prop_name): if item.confidence < min_confidence: continue issues.append(VultureIssue( code, <|code_end|> . Write the next line using the current file imports: from pathlib import Path from vulture import Vulture, noqa from vulture.utils import VultureInputException from .base import PythonTool, Issue, ParseIssue, AccessIssue from ..util import parse_python_file and context from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] , which may include functions, classes, or code. Output only the next line.
template.format(entity=str(item)),
Using the snippet: <|code_start|> class McCabeIssue(Issue): tool = 'mccabe' pylint_type = 'W' <|code_end|> , determine the next line of code. You have imports: from mccabe import PathGraphingAstVisitor from .base import PythonTool, Issue, AccessIssue, ParseIssue from ..util import parse_python_file and context (class names, function names, or code) available: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] . Output only the next line.
CODE = 'complex'
Given the code snippet: <|code_start|> class McCabeIssue(Issue): tool = 'mccabe' pylint_type = 'W' CODE = 'complex' <|code_end|> , generate the next line using the imports in this file: from mccabe import PathGraphingAstVisitor from .base import PythonTool, Issue, AccessIssue, ParseIssue from ..util import parse_python_file and context (functions, classes, or occasionally code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] . Output only the next line.
DESCRIPTION = '"{entity}" is too complex ({score})'
Given snippet: <|code_start|> class McCabeIssue(Issue): tool = 'mccabe' pylint_type = 'W' CODE = 'complex' <|code_end|> , continue by predicting the next line. Consider current file imports: from mccabe import PathGraphingAstVisitor from .base import PythonTool, Issue, AccessIssue, ParseIssue from ..util import parse_python_file and context: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] which might include code, classes, or functions. Output only the next line.
DESCRIPTION = '"{entity}" is too complex ({score})'
Continue the code snippet: <|code_start|> TMPL_FILENAME = click.style('{filename}', underline=True) + ' ({num_errors})' TMPL_LOCATION = click.style( '{line:>5}{position_splitter}{character:<3} ', dim=True, ) TMPL_TOOLINFO = click.style('({tool}:{code})', fg='yellow', dim=True) <|code_end|> . Use current file imports: import sys import click from .base import Report and context (classes, functions, or code) from other files: # Path: src/tidypy/reports/base.py # class Report: # """ # The base class for TidyPy issue reporters. # """ # # def __init__(self, config, base_path, output_file=None): # """ # :param config: # the configuration used during the analysis of the project # :type config: dict # :param base_path: the path to the project base directory # :type base_path: str # """ # # self.config = config # self.base_path = base_path # self._output_needs_closing = False # if output_file: # self.output_file = output_file # elif self.config.get('file'): # self.output_file = click.open_file( # self.config['file'], # mode='w', # encoding='utf-8', # ) # self._output_needs_closing = True # else: # self.output_file = click.get_text_stream('stdout') # # def execute(self, collector): # """ # Produces the contents of the report. # # Must be implemented by concrete classes. # # :param collector: the collection of issues to report on # :type collector: tidypy.Collector # """ # # def produce(self, collector): # self.execute(collector) # if self._output_needs_closing: # self.output_file.close() # # def relative_filename(self, filename): # """ # Generates a path for the specified filename that is relative to the # project path. # # :param filename: the filename to generate the path for # :type filename: str # :rtype: str # """ # # return Path(filename).relative_to(self.base_path).as_posix() # # def output(self, msg, newline=True): # """ # Writes the specified string to the output target of the report. # # :param msg: the message to output. # :type msg: str # :param newline: # whether or not to append a newline to the end of the message # :type newline: str # """ # # click.echo(str(msg), nl=newline, file=self.output_file) . Output only the next line.
TAB = ' ' * 8
Predict the next line after this snippet: <|code_start|> ALWAYS_EXCLUDED_DIRS = compile_masks([ r'^\.hg$', r'^\.git$', r'^\.svn$', r'^CVS$', <|code_end|> using the current file's imports: from pathlib import Path from .util import read_file, compile_masks, matches_masks and any relevant context from other files: # Path: src/tidypy/util.py # def read_file(filepath): # """ # Retrieves the contents of the specified file. # # This function performs simple caching so that the same file isn't read more # than once per process. # # :param filepath: the file to read # :type filepath: str # :returns: str # """ # # with _FILE_CACHE_LOCK: # if filepath not in _FILE_CACHE: # _FILE_CACHE[filepath] = _read_file(filepath) # return _FILE_CACHE[filepath] # # def compile_masks(masks): # """ # Compiles a list of regular expressions. # # :param masks: the regular expressions to compile # :type masks: list(str) or str # :returns: list(regular expression object) # """ # # if not masks: # masks = [] # elif not isinstance(masks, (list, tuple)): # masks = [masks] # # return [ # re.compile(mask) # for mask in masks # ] # # def matches_masks(target, masks): # """ # Determines whether or not the target string matches any of the regular # expressions specified. # # :param target: the string to check # :type target: str # :param masks: the regular expressions to check against # :type masks: list(regular expression object) # :returns: bool # """ # # for mask in masks: # if mask.search(target): # return True # return False . Output only the next line.
r'^\.bzr$',
Given the following code snippet before the placeholder: <|code_start|> ALWAYS_EXCLUDED_DIRS = compile_masks([ r'^\.hg$', r'^\.git$', <|code_end|> , predict the next line using imports from the current file: from pathlib import Path from .util import read_file, compile_masks, matches_masks and context including class names, function names, and sometimes code from other files: # Path: src/tidypy/util.py # def read_file(filepath): # """ # Retrieves the contents of the specified file. # # This function performs simple caching so that the same file isn't read more # than once per process. # # :param filepath: the file to read # :type filepath: str # :returns: str # """ # # with _FILE_CACHE_LOCK: # if filepath not in _FILE_CACHE: # _FILE_CACHE[filepath] = _read_file(filepath) # return _FILE_CACHE[filepath] # # def compile_masks(masks): # """ # Compiles a list of regular expressions. # # :param masks: the regular expressions to compile # :type masks: list(str) or str # :returns: list(regular expression object) # """ # # if not masks: # masks = [] # elif not isinstance(masks, (list, tuple)): # masks = [masks] # # return [ # re.compile(mask) # for mask in masks # ] # # def matches_masks(target, masks): # """ # Determines whether or not the target string matches any of the regular # expressions specified. # # :param target: the string to check # :type target: str # :param masks: the regular expressions to check against # :type masks: list(regular expression object) # :returns: bool # """ # # for mask in masks: # if mask.search(target): # return True # return False . Output only the next line.
r'^\.svn$',
Based on the snippet: <|code_start|> HOOK_TEMPLATE = '''#!{executable} # TIDYPY-INSTALLED-HOOK import os.path import sys <|code_end|> , predict the immediate next line with the help of imports: import os.path import stat import subprocess # noqa: bandit:B404 import sys from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport from ..util import read_file and context (classes, functions, sometimes code) from other files: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) # # Path: src/tidypy/util.py # def read_file(filepath): # """ # Retrieves the contents of the specified file. # # This function performs simple caching so that the same file isn't read more # than once per process. # # :param filepath: the file to read # :type filepath: str # :returns: str # """ # # with _FILE_CACHE_LOCK: # if filepath not in _FILE_CACHE: # _FILE_CACHE[filepath] = _read_file(filepath) # return _FILE_CACHE[filepath] . Output only the next line.
from tidypy.plugin import git
Based on the snippet: <|code_start|> class DummyDirective(Directive): has_content = True def run(self, *args, **kwargs): # pylint: disable=unused-argument <|code_end|> , predict the immediate next line with the help of imports: import os from importlib import import_module from shutil import rmtree from tempfile import mkdtemp from docutils.nodes import system_message from docutils.parsers.rst import Directive, directives, roles from docutils.utils import Reporter from restructuredtext_lint import lint from .base import Tool, Issue, AccessIssue, UnknownIssue, ToolIssue from sphinx.application import Sphinx # noqa: import-outside-toplevel and context (classes, functions, sometimes code) from other files: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) # # class ToolIssue(TidyPyIssue): # """ # An issue indicating that a tool completely crashed/failed during its # execution. # """ # # def __init__(self, message, project_path, details=None, failure=False): # if details: # if isinstance(details, tuple): # details = ''.join(traceback.format_exception(*details)) # message = '%s:\n%s' % (message, details) # # super().__init__( # 'tool', # message, # project_path, # ) # # self.pylint_type = 'F' if failure else 'E' . Output only the next line.
return []
Given snippet: <|code_start|> class DummyDirective(Directive): has_content = True def run(self, *args, **kwargs): # pylint: disable=unused-argument return [] <|code_end|> , continue by predicting the next line. Consider current file imports: import os from importlib import import_module from shutil import rmtree from tempfile import mkdtemp from docutils.nodes import system_message from docutils.parsers.rst import Directive, directives, roles from docutils.utils import Reporter from restructuredtext_lint import lint from .base import Tool, Issue, AccessIssue, UnknownIssue, ToolIssue from sphinx.application import Sphinx # noqa: import-outside-toplevel and context: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) # # class ToolIssue(TidyPyIssue): # """ # An issue indicating that a tool completely crashed/failed during its # execution. # """ # # def __init__(self, message, project_path, details=None, failure=False): # if details: # if isinstance(details, tuple): # details = ''.join(traceback.format_exception(*details)) # message = '%s:\n%s' % (message, details) # # super().__init__( # 'tool', # message, # project_path, # ) # # self.pylint_type = 'F' if failure else 'E' which might include code, classes, or functions. Output only the next line.
def dummy_role(*args, **kwargs):
Here is a snippet: <|code_start|> class DummyDirective(Directive): has_content = True def run(self, *args, **kwargs): # pylint: disable=unused-argument return [] <|code_end|> . Write the next line using the current file imports: import os from importlib import import_module from shutil import rmtree from tempfile import mkdtemp from docutils.nodes import system_message from docutils.parsers.rst import Directive, directives, roles from docutils.utils import Reporter from restructuredtext_lint import lint from .base import Tool, Issue, AccessIssue, UnknownIssue, ToolIssue from sphinx.application import Sphinx # noqa: import-outside-toplevel and context from other files: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) # # class ToolIssue(TidyPyIssue): # """ # An issue indicating that a tool completely crashed/failed during its # execution. # """ # # def __init__(self, message, project_path, details=None, failure=False): # if details: # if isinstance(details, tuple): # details = ''.join(traceback.format_exception(*details)) # message = '%s:\n%s' % (message, details) # # super().__init__( # 'tool', # message, # project_path, # ) # # self.pylint_type = 'F' if failure else 'E' , which may include functions, classes, or code. Output only the next line.
def dummy_role(*args, **kwargs):
Given the code snippet: <|code_start|> class DummyDirective(Directive): has_content = True def run(self, *args, **kwargs): # pylint: disable=unused-argument return [] def dummy_role(*args, **kwargs): # pylint: disable=unused-argument return [], [] dummy_role.content = True class RstLintIssue(Issue): tool = 'rstlint' @property def pylint_type(self): if self.code in ('error', 'severe'): <|code_end|> , generate the next line using the imports in this file: import os from importlib import import_module from shutil import rmtree from tempfile import mkdtemp from docutils.nodes import system_message from docutils.parsers.rst import Directive, directives, roles from docutils.utils import Reporter from restructuredtext_lint import lint from .base import Tool, Issue, AccessIssue, UnknownIssue, ToolIssue from sphinx.application import Sphinx # noqa: import-outside-toplevel and context (functions, classes, or occasionally code) from other files: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) # # class ToolIssue(TidyPyIssue): # """ # An issue indicating that a tool completely crashed/failed during its # execution. # """ # # def __init__(self, message, project_path, details=None, failure=False): # if details: # if isinstance(details, tuple): # details = ''.join(traceback.format_exception(*details)) # message = '%s:\n%s' % (message, details) # # super().__init__( # 'tool', # message, # project_path, # ) # # self.pylint_type = 'F' if failure else 'E' . Output only the next line.
return 'E'
Using the snippet: <|code_start|> class DummyDirective(Directive): has_content = True def run(self, *args, **kwargs): # pylint: disable=unused-argument return [] def dummy_role(*args, **kwargs): # pylint: disable=unused-argument return [], [] dummy_role.content = True class RstLintIssue(Issue): tool = 'rstlint' <|code_end|> , determine the next line of code. You have imports: import os from importlib import import_module from shutil import rmtree from tempfile import mkdtemp from docutils.nodes import system_message from docutils.parsers.rst import Directive, directives, roles from docutils.utils import Reporter from restructuredtext_lint import lint from .base import Tool, Issue, AccessIssue, UnknownIssue, ToolIssue from sphinx.application import Sphinx # noqa: import-outside-toplevel and context (class names, function names, or code) available: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) # # class ToolIssue(TidyPyIssue): # """ # An issue indicating that a tool completely crashed/failed during its # execution. # """ # # def __init__(self, message, project_path, details=None, failure=False): # if details: # if isinstance(details, tuple): # details = ''.join(traceback.format_exception(*details)) # message = '%s:\n%s' % (message, details) # # super().__init__( # 'tool', # message, # project_path, # ) # # self.pylint_type = 'F' if failure else 'E' . Output only the next line.
@property
Next line prediction: <|code_start|> def pytest_addoption(parser): group = parser.getgroup( 'tidypy', 'static analysis of a project with TidyPy', ) group.addoption( <|code_end|> . Use current file imports: (import pytest from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport) and context including class names, function names, or small code snippets from other files: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) . Output only the next line.
'--tidypy',
Next line prediction: <|code_start|> self.output('TidyPy Results:\n') super().execute(collector) class TidyPyPlugin: def __init__(self, config): self.enabled = config.getoption('tidypy') self.project_path = config.getoption('tidypy_project_path') \ or str(config.rootdir) self.fail_on_issue = config.getoption('tidypy_fail_on_issue') self.tidypy_config = get_project_config(self.project_path) self._session_results = None @pytest.hookimpl(hookwrapper=True) def pytest_runtestloop(self, session): yield if self.enabled: self._session_results = execute_tools( self.tidypy_config, self.project_path, ) if self.fail_on_issue and self._session_results.issue_count() > 0: session.testsfailed += 1 def pytest_terminal_summary(self, terminalreporter): report = PyTestReport( self.tidypy_config, self.project_path, <|code_end|> . Use current file imports: (import pytest from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport) and context including class names, function names, or small code snippets from other files: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) . Output only the next line.
terminalreporter,
Here is a snippet: <|code_start|> message, self.filename, line=line_number, character=offset + 1, )) elif code == 'E902': message = text[5:].split(':', 1)[1].lstrip() self._tidypy_issues.append(AccessIssue(message, self.filename)) elif code: self._tidypy_issues.append(PyCodeStyleIssue( code, text[5:], self.filename, line_number, offset + 1, )) return code def get_issues(self): return self._tidypy_issues class TidyPyStyleGuide(StyleGuide): def __init__(self, config): kwargs = { 'reporter': TidyPyReport, 'ignore': config['disabled'], } <|code_end|> . Write the next line using the current file imports: from pep8ext_naming import NamingChecker from pycodestyle import StyleGuide, BaseReport, register_check from .base import PythonTool, Issue, AccessIssue, ParseIssue and context from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) , which may include functions, classes, or code. Output only the next line.
super().__init__(**kwargs)
Continue the code snippet: <|code_start|> class PyCodeStyleIssue(Issue): tool = 'pycodestyle' pylint_type = 'C' def __init__(self, code, message, filename, line, character): if code in ('E101',): line = None super().__init__( code, message, filename, line, character, <|code_end|> . Use current file imports: from pep8ext_naming import NamingChecker from pycodestyle import StyleGuide, BaseReport, register_check from .base import PythonTool, Issue, AccessIssue, ParseIssue and context (classes, functions, or code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) . Output only the next line.
)
Next line prediction: <|code_start|> message, self.filename, line=line_number, character=offset + 1, )) elif code == 'E902': message = text[5:].split(':', 1)[1].lstrip() self._tidypy_issues.append(AccessIssue(message, self.filename)) elif code: self._tidypy_issues.append(PyCodeStyleIssue( code, text[5:], self.filename, line_number, offset + 1, )) return code def get_issues(self): return self._tidypy_issues class TidyPyStyleGuide(StyleGuide): def __init__(self, config): kwargs = { 'reporter': TidyPyReport, 'ignore': config['disabled'], } <|code_end|> . Use current file imports: (from pep8ext_naming import NamingChecker from pycodestyle import StyleGuide, BaseReport, register_check from .base import PythonTool, Issue, AccessIssue, ParseIssue) and context including class names, function names, or small code snippets from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) . Output only the next line.
super().__init__(**kwargs)
Predict the next line for this snippet: <|code_start|> class PyCodeStyleIssue(Issue): tool = 'pycodestyle' pylint_type = 'C' def __init__(self, code, message, filename, line, character): if code in ('E101',): line = None super().__init__( <|code_end|> with the help of current file imports: from pep8ext_naming import NamingChecker from pycodestyle import StyleGuide, BaseReport, register_check from .base import PythonTool, Issue, AccessIssue, ParseIssue and context from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) , which may contain function names, class names, or code. Output only the next line.
code,
Given the code snippet: <|code_start|> class TidyPyReporter(Reporter): def __init__(self, config): super().__init__(None, None) self._tidypy_issues = [] self._config = config def unexpectedError(self, filename, msg): # noqa if msg == 'problem decoding source': issue = ParseIssue else: issue = AccessIssue self._tidypy_issues.append(issue( msg, filename, )) def syntaxError(self, filename, msg, lineno, offset, text): # noqa self._tidypy_issues.append(ParseIssue( msg, filename, line=lineno, character=offset, )) def flake(self, message): if message.__class__.__name__ in self._config['disabled']: return self._tidypy_issues.append(PyFlakesIssue( <|code_end|> , generate the next line using the imports in this file: import inspect from pyflakes import messages from pyflakes.api import check from pyflakes.reporter import Reporter from .base import PythonTool, Issue, AccessIssue, ParseIssue and context (functions, classes, or occasionally code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) . Output only the next line.
message.__class__.__name__,
Here is a snippet: <|code_start|>class TidyPyReporter(Reporter): def __init__(self, config): super().__init__(None, None) self._tidypy_issues = [] self._config = config def unexpectedError(self, filename, msg): # noqa if msg == 'problem decoding source': issue = ParseIssue else: issue = AccessIssue self._tidypy_issues.append(issue( msg, filename, )) def syntaxError(self, filename, msg, lineno, offset, text): # noqa self._tidypy_issues.append(ParseIssue( msg, filename, line=lineno, character=offset, )) def flake(self, message): if message.__class__.__name__ in self._config['disabled']: return self._tidypy_issues.append(PyFlakesIssue( message.__class__.__name__, <|code_end|> . Write the next line using the current file imports: import inspect from pyflakes import messages from pyflakes.api import check from pyflakes.reporter import Reporter from .base import PythonTool, Issue, AccessIssue, ParseIssue and context from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) , which may include functions, classes, or code. Output only the next line.
message.message % message.message_args,
Predict the next line for this snippet: <|code_start|> class PyFlakesIssue(Issue): tool = 'pyflakes' class TidyPyReporter(Reporter): def __init__(self, config): super().__init__(None, None) self._tidypy_issues = [] self._config = config def unexpectedError(self, filename, msg): # noqa if msg == 'problem decoding source': issue = ParseIssue else: issue = AccessIssue self._tidypy_issues.append(issue( msg, filename, )) def syntaxError(self, filename, msg, lineno, offset, text): # noqa self._tidypy_issues.append(ParseIssue( msg, filename, line=lineno, character=offset, )) def flake(self, message): <|code_end|> with the help of current file imports: import inspect from pyflakes import messages from pyflakes.api import check from pyflakes.reporter import Reporter from .base import PythonTool, Issue, AccessIssue, ParseIssue and context from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) , which may contain function names, class names, or code. Output only the next line.
if message.__class__.__name__ in self._config['disabled']:
Given the following code snippet before the placeholder: <|code_start|> def unexpectedError(self, filename, msg): # noqa if msg == 'problem decoding source': issue = ParseIssue else: issue = AccessIssue self._tidypy_issues.append(issue( msg, filename, )) def syntaxError(self, filename, msg, lineno, offset, text): # noqa self._tidypy_issues.append(ParseIssue( msg, filename, line=lineno, character=offset, )) def flake(self, message): if message.__class__.__name__ in self._config['disabled']: return self._tidypy_issues.append(PyFlakesIssue( message.__class__.__name__, message.message % message.message_args, message.filename, message.lineno, message.col + 1, )) <|code_end|> , predict the next line using imports from the current file: import inspect from pyflakes import messages from pyflakes.api import check from pyflakes.reporter import Reporter from .base import PythonTool, Issue, AccessIssue, ParseIssue and context including class names, function names, and sometimes code from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) . Output only the next line.
def get_issues(self):
Based on the snippet: <|code_start|> class YamlLintIssue(Issue): tool = 'yamllint' def __init__(self, *args, **kwargs): <|code_end|> , predict the immediate next line with the help of imports: import basicserial from yamllint import linter from yamllint.config import YamlLintConfig from .base import Tool, Issue, AccessIssue, UnknownIssue and context (classes, functions, sometimes code) from other files: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) . Output only the next line.
super().__init__(*args, **kwargs)
Continue the code snippet: <|code_start|> class YamlLintIssue(Issue): tool = 'yamllint' def __init__(self, *args, **kwargs): <|code_end|> . Use current file imports: import basicserial from yamllint import linter from yamllint.config import YamlLintConfig from .base import Tool, Issue, AccessIssue, UnknownIssue and context (classes, functions, or code) from other files: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) . Output only the next line.
super().__init__(*args, **kwargs)
Continue the code snippet: <|code_start|> class FilesysExtender(Extender): @classmethod def can_handle(cls, location): return True @classmethod def retrieve(cls, location, project_path): path = Path(location) if not path.is_absolute(): path = Path(project_path).joinpath(path) if not path.exists(): raise DoesNotExistError() with path.open('r', encoding='utf-8') as config_file: <|code_end|> . Use current file imports: from pathlib import Path from .base import Extender, DoesNotExistError and context (classes, functions, or code) from other files: # Path: src/tidypy/extenders/base.py # class Extender: # """ # The base class for TidyPy configuration extenders. # """ # # @classmethod # def can_handle(cls, location): # """ # Indicates whether or not this Extender is capable of retrieving the # specified location. # # :param location: # a URI indicating where to retrieve the TidyPy configuration from # :type location: str # :rtype: bool # """ # # raise NotImplementedError() # # @classmethod # def retrieve(cls, location, project_path): # """ # Retrieves a TidyPy configuration from the specified location. # # :param location: # a URI indicating where to retrieve the TidyPy configuration from # :type location: str # :param project_path: the full path to the project's base # :type project_path: str # :rtype: dict # """ # # raise NotImplementedError() # # @classmethod # def parse(cls, content, is_pyproject=False): # """ # A convenience method for parsing a TOML-serialized configuration. # # :param content: a TOML string containing a TidyPy configuration # :type content: str # :param is_pyproject: # whether or not the content is (or resembles) a ``pyproject.toml`` # file, where the TidyPy configuration is located within a key named # ``tool``. # :type is_pyproject: bool # :rtype: dict # """ # # parsed = toml.loads(content) # # if is_pyproject: # parsed = parsed.get('tool', {}) # parsed = parsed.get('tidypy', {}) # # return parsed # # class DoesNotExistError(ExtenderError): # """ # An exception indicating that the specified Extender does not exist in the # current environment. # """ . Output only the next line.
content = config_file.read()
Continue the code snippet: <|code_start|> class FilesysExtender(Extender): @classmethod def can_handle(cls, location): return True @classmethod def retrieve(cls, location, project_path): path = Path(location) if not path.is_absolute(): path = Path(project_path).joinpath(path) if not path.exists(): raise DoesNotExistError() with path.open('r', encoding='utf-8') as config_file: content = config_file.read() return cls.parse( content, is_pyproject=path.parts[-1] == 'pyproject.toml', <|code_end|> . Use current file imports: from pathlib import Path from .base import Extender, DoesNotExistError and context (classes, functions, or code) from other files: # Path: src/tidypy/extenders/base.py # class Extender: # """ # The base class for TidyPy configuration extenders. # """ # # @classmethod # def can_handle(cls, location): # """ # Indicates whether or not this Extender is capable of retrieving the # specified location. # # :param location: # a URI indicating where to retrieve the TidyPy configuration from # :type location: str # :rtype: bool # """ # # raise NotImplementedError() # # @classmethod # def retrieve(cls, location, project_path): # """ # Retrieves a TidyPy configuration from the specified location. # # :param location: # a URI indicating where to retrieve the TidyPy configuration from # :type location: str # :param project_path: the full path to the project's base # :type project_path: str # :rtype: dict # """ # # raise NotImplementedError() # # @classmethod # def parse(cls, content, is_pyproject=False): # """ # A convenience method for parsing a TOML-serialized configuration. # # :param content: a TOML string containing a TidyPy configuration # :type content: str # :param is_pyproject: # whether or not the content is (or resembles) a ``pyproject.toml`` # file, where the TidyPy configuration is located within a key named # ``tool``. # :type is_pyproject: bool # :rtype: dict # """ # # parsed = toml.loads(content) # # if is_pyproject: # parsed = parsed.get('tool', {}) # parsed = parsed.get('tidypy', {}) # # return parsed # # class DoesNotExistError(ExtenderError): # """ # An exception indicating that the specified Extender does not exist in the # current environment. # """ . Output only the next line.
)
Given the following code snippet before the placeholder: <|code_start|> IGNORE_MSGS = ( 'lists of files in version control and sdist match', ) class CheckManifestIssue(Issue): tool = 'manifest' pylint_type = 'W' class CheckManifestUI(check_manifest.UI): def __init__(self, dirname): <|code_end|> , predict the next line using imports from the current file: import os import check_manifest from .base import Tool, Issue and context including class names, function names, and sometimes code from other files: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) . Output only the next line.
super().__init__()
Next line prediction: <|code_start|> IGNORE_MSGS = ( 'lists of files in version control and sdist match', ) class CheckManifestIssue(Issue): tool = 'manifest' pylint_type = 'W' class CheckManifestUI(check_manifest.UI): def __init__(self, dirname): super().__init__() <|code_end|> . Use current file imports: (import os import check_manifest from .base import Tool, Issue) and context including class names, function names, or small code snippets from other files: # Path: src/tidypy/tools/base.py # class Tool: # """ # The base class for TidyPy tools. # """ # # @classmethod # def can_be_used(cls): # """ # Indicates whether or not this tool can be executed now. Useful when you # need to check for certain environmental conditions (e.g., Python # version, dependency availability, etc). # # Unless overridden, always returns ``True``. # # :rtype: bool # """ # # return True # # @classmethod # def get_default_config(cls): # """ # Produces a tool configuration stanza that acts as the base/default for # this tool. # # rtype: dict # """ # # return { # 'use': True, # 'filters': [], # 'disabled': [], # 'options': {}, # } # # @classmethod # def get_all_codes(cls): # """ # Produces a sequence of all the issue codes this tool is capable of # generating. Elements in this sequence must all be 2-element tuples, # where the first element is the code, and the second is a textual # description of what the code means. # # Must be implemented by concrete classes. # # :returns: tuple of tuples containing two strings each # """ # # raise NotImplementedError() # # def __init__(self, config): # """ # :param config: the tool configuration to use during execution # :type config: dict # """ # # #: The tool's configuration to use during its execution. # self.config = config # # def execute(self, finder): # """ # Analyzes the project and generates a list of issues found during that # analysis. # # Must be implemented by concrete classes. # # :param finder: # the Finder class that should be used to identify the files or # directories that the tool will analyze. # :type finder: tidypy.Finder # :rtype: list(tidypy.Issue) # """ # # raise NotImplementedError() # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) . Output only the next line.
self.dirname = dirname
Next line prediction: <|code_start|> class PbbtReport(ConsoleReport): def __init__(self, config, base_path, pbbt_ui): super().__init__(config, base_path) <|code_end|> . Use current file imports: (import os from pbbt import Test, Field, BaseCase, maybe from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport) and context including class names, function names, or small code snippets from other files: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) . Output only the next line.
self.pbbt_ui = pbbt_ui
Using the snippet: <|code_start|>class PbbtReport(ConsoleReport): def __init__(self, config, base_path, pbbt_ui): super().__init__(config, base_path) self.pbbt_ui = pbbt_ui def output(self, msg, newline=True): self.pbbt_ui.literal(msg or ' ') @Test class TidyPyCase(BaseCase): class Input: # noqa: pydocstyle:D106 tidypy = Field( maybe(str), hint='The path to the base of project. Defaults to CWD.', ) fail_on_issue = Field( bool, default=True, hint='Whether or not the test should fail if TidyPy finds issues.' ) def check(self): project_path = self.input.tidypy or os.getcwd() cfg = get_project_config(project_path) collector = execute_tools(cfg, project_path) report = PbbtReport(cfg, project_path, self.ui) <|code_end|> , determine the next line of code. You have imports: import os from pbbt import Test, Field, BaseCase, maybe from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport and context (class names, function names, or code) available: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) . Output only the next line.
report.execute(collector)
Here is a snippet: <|code_start|> class PbbtReport(ConsoleReport): def __init__(self, config, base_path, pbbt_ui): super().__init__(config, base_path) self.pbbt_ui = pbbt_ui def output(self, msg, newline=True): self.pbbt_ui.literal(msg or ' ') @Test class TidyPyCase(BaseCase): class Input: # noqa: pydocstyle:D106 tidypy = Field( maybe(str), hint='The path to the base of project. Defaults to CWD.', ) fail_on_issue = Field( bool, default=True, hint='Whether or not the test should fail if TidyPy finds issues.' <|code_end|> . Write the next line using the current file imports: import os from pbbt import Test, Field, BaseCase, maybe from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport and context from other files: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) , which may include functions, classes, or code. Output only the next line.
)
Using the snippet: <|code_start|> class StructuredReport(Report): def get_structure(self, collector): issues = OrderedDict() for filename, file_issues in collector.get_grouped_issues().items(): issues[self.relative_filename(filename)] = [ OrderedDict(( ('line', issue.line), ('character', issue.character or 0), <|code_end|> , determine the next line of code. You have imports: import csv import basicserial import pkg_resources from collections import OrderedDict from .base import Report and context (class names, function names, or code) available: # Path: src/tidypy/reports/base.py # class Report: # """ # The base class for TidyPy issue reporters. # """ # # def __init__(self, config, base_path, output_file=None): # """ # :param config: # the configuration used during the analysis of the project # :type config: dict # :param base_path: the path to the project base directory # :type base_path: str # """ # # self.config = config # self.base_path = base_path # self._output_needs_closing = False # if output_file: # self.output_file = output_file # elif self.config.get('file'): # self.output_file = click.open_file( # self.config['file'], # mode='w', # encoding='utf-8', # ) # self._output_needs_closing = True # else: # self.output_file = click.get_text_stream('stdout') # # def execute(self, collector): # """ # Produces the contents of the report. # # Must be implemented by concrete classes. # # :param collector: the collection of issues to report on # :type collector: tidypy.Collector # """ # # def produce(self, collector): # self.execute(collector) # if self._output_needs_closing: # self.output_file.close() # # def relative_filename(self, filename): # """ # Generates a path for the specified filename that is relative to the # project path. # # :param filename: the filename to generate the path for # :type filename: str # :rtype: str # """ # # return Path(filename).relative_to(self.base_path).as_posix() # # def output(self, msg, newline=True): # """ # Writes the specified string to the output target of the report. # # :param msg: the message to output. # :type msg: str # :param newline: # whether or not to append a newline to the end of the message # :type newline: str # """ # # click.echo(str(msg), nl=newline, file=self.output_file) . Output only the next line.
('code', issue.code),
Predict the next line after this snippet: <|code_start|> ) ) config = configparser.ConfigParser() config.read(hgrc) if not config.has_section('hooks'): config.add_section('hooks') config.set( 'hooks', 'precommit.tidypy', 'python:tidypy.plugin.mercurial.hook', ) if not config.has_section('tidypy'): config.add_section('tidypy') config.set('tidypy', 'strict', str(strict)) with open(hgrc, 'w', encoding="utf8") as config_file: config.write(config_file) def remove(self, path): hgrc = self.get_hgrc(path) if not hgrc: raise Exception( 'Could not find Mercurial configuration in: %s' % ( path, ) ) <|code_end|> using the current file's imports: import configparser from pathlib import Path from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport and any relevant context from other files: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) . Output only the next line.
config = configparser.ConfigParser()
Given snippet: <|code_start|> report = ConsoleReport(cfg, repo.root) report.execute(collector) strict = ui.configbool('tidypy', 'strict', default=False) if strict and collector.issue_count() > 0: return 1 return 0 class MercurialHook: def get_hgrc(self, path, ensure_exists=False): path = Path(path) if not path.exists(): return None hg_dir = path / '.hg' if not hg_dir.exists(): return None hgrc = hg_dir / 'hgrc' if not hgrc.exists(): if ensure_exists: hgrc.touch() return hgrc return None return hgrc def install(self, path, strict): <|code_end|> , continue by predicting the next line. Consider current file imports: import configparser from pathlib import Path from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport and context: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) which might include code, classes, or functions. Output only the next line.
hgrc = self.get_hgrc(path, ensure_exists=True)
Given snippet: <|code_start|> strict = ui.configbool('tidypy', 'strict', default=False) if strict and collector.issue_count() > 0: return 1 return 0 class MercurialHook: def get_hgrc(self, path, ensure_exists=False): path = Path(path) if not path.exists(): return None hg_dir = path / '.hg' if not hg_dir.exists(): return None hgrc = hg_dir / 'hgrc' if not hgrc.exists(): if ensure_exists: hgrc.touch() return hgrc return None return hgrc def install(self, path, strict): hgrc = self.get_hgrc(path, ensure_exists=True) if not hgrc: <|code_end|> , continue by predicting the next line. Consider current file imports: import configparser from pathlib import Path from ..config import get_project_config from ..core import execute_tools from ..reports.console import ConsoleReport and context: # Path: src/tidypy/config.py # def get_project_config(project_path, use_cache=True): # """ # Produces the Tidypy configuration to use for the specified project. # # If a ``pyproject.toml`` exists, the configuration will be based on that. If # not, the TidyPy configuration in the user's home directory will be used. If # one does not exist, the default configuration will be used. # # :param project_path: the path to the project that is going to be analyzed # :type project_path: str # :param use_cache: # whether or not to use cached versions of any remote/referenced TidyPy # configurations. If not specified, defaults to ``True``. # :type use_cache: bool # :rtype: dict # """ # # return get_local_config(project_path, use_cache=use_cache) \ # or get_user_config(project_path, use_cache=use_cache) \ # or get_default_config() # # Path: src/tidypy/core.py # def execute_tools(config, path, progress=None): # """ # Executes the suite of TidyPy tools upon the project and returns the # issues that are found. # # :param config: the TidyPy configuration to use # :type config: dict # :param path: that path to the project to analyze # :type path: str # :param progress: # the progress reporter object that will receive callbacks during the # execution of the tool suite. If not specified, not progress # notifications will occur. # :type progress: tidypy.Progress # :rtype: tidypy.Collector # """ # # progress = progress or QuietProgress() # progress.on_start() # # with SyncManager() as manager: # num_tools = 0 # tools = manager.Queue() # for name, cls in get_tools().items(): # if config[name]['use'] and cls.can_be_used(): # num_tools += 1 # tools.put({ # 'name': name, # 'config': config[name], # }) # # collector = Collector(config) # if not num_tools: # progress.on_finish() # return collector # # notifications = manager.Queue() # environment = manager.dict({ # 'finder': Finder(path, config), # }) # # workers = [] # for _ in range(config['workers']): # worker = Worker( # args=( # tools, # notifications, # environment, # ), # ) # worker.start() # workers.append(worker) # # while num_tools: # try: # notification = notifications.get(True, 0.25) # except Empty: # pass # else: # if notification['type'] == 'start': # progress.on_tool_start(notification['tool']) # elif notification['type'] == 'complete': # collector.add_issues(notification['issues']) # progress.on_tool_finish(notification['tool']) # num_tools -= 1 # # progress.on_finish() # # return collector # # Path: src/tidypy/reports/console.py # class ConsoleReport(Report): # """ # Prints a colored report to the console that groups issues by the file they # were found in. # """ # # def execute(self, collector): # issues = collector.get_grouped_issues() # # total_issues = 0 # for filename in sorted(issues.keys()): # file_issues = issues[filename] # total_issues += len(file_issues) # # self.output(TMPL_FILENAME.format( # filename=self.relative_filename(filename), # num_errors=len(file_issues), # )) # # for issue in file_issues: # location = TMPL_LOCATION.format( # line=issue.line, # position_splitter=' ' if issue.character is None else ':', # character=issue.character or '', # ) # # toolinfo = TMPL_TOOLINFO.format( # tool=issue.tool, # code=issue.code, # ) # # message = issue.message # if '\n' in message: # pad = '\n' + (' ' * len(click.unstyle(location))) # # message = pad.join( # issue.message.replace('\t', TAB).splitlines() # ) # # toolinfo = pad + toolinfo # else: # toolinfo = ' ' + toolinfo # # self.output(location + message + toolinfo) # # self.output('') # # is_windows = sys.platform == 'win32' # if total_issues: # self.output( # click.style( # '{icon}{num_issues} issues found.'.format( # noqa: @2to3 # icon='' if is_windows else '\u2717 ', # noqa: @2to3 # num_issues=total_issues, # ), # fg='yellow', # bold=True, # ) # ) # else: # self.output( # click.style( # '{icon}No issues found!'.format( # noqa: @2to3 # icon='' if is_windows else '\u2714 ', # noqa: @2to3 # ), # fg='green', # bold=True, # ) # ) which might include code, classes, or functions. Output only the next line.
raise Exception(
Here is a snippet: <|code_start|> RATING = { 'LOW': 1, 'MEDIUM': 2, 'HIGH': 3, } class TidyPyBanditManager(manager.BanditManager): def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self.config = kwargs.pop('config') super().__init__( bandit_config.BanditConfig(), 'file', ignore_nosec=self.config['options']['ignore-nosec'], profile={ 'exclude': self.config['disabled'], }, ) self.progress = sys.maxsize # prevent bandit from printing progress def discover_files(self, finder): # pylint: disable=arguments-differ self.files_list = list(finder.files(self.config['filters'])) self.skipped = [] self.excluded_files = [] def get_issues(self): issues = [] for filepath, reason in self.skipped: <|code_end|> . Write the next line using the current file imports: import re import sys from bandit import manager, config as bandit_config from bandit.core import extension_loader from .base import PythonTool, Issue, ParseIssue, AccessIssue, UnknownIssue and context from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) , which may include functions, classes, or code. Output only the next line.
if SKIPPED_PARSE.search(reason):
Given the following code snippet before the placeholder: <|code_start|> RATING = { 'LOW': 1, 'MEDIUM': 2, 'HIGH': 3, } class TidyPyBanditManager(manager.BanditManager): def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self.config = kwargs.pop('config') super().__init__( bandit_config.BanditConfig(), 'file', ignore_nosec=self.config['options']['ignore-nosec'], profile={ 'exclude': self.config['disabled'], }, ) self.progress = sys.maxsize # prevent bandit from printing progress def discover_files(self, finder): # pylint: disable=arguments-differ self.files_list = list(finder.files(self.config['filters'])) self.skipped = [] self.excluded_files = [] def get_issues(self): issues = [] for filepath, reason in self.skipped: <|code_end|> , predict the next line using imports from the current file: import re import sys from bandit import manager, config as bandit_config from bandit.core import extension_loader from .base import PythonTool, Issue, ParseIssue, AccessIssue, UnknownIssue and context including class names, function names, and sometimes code from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) . Output only the next line.
if SKIPPED_PARSE.search(reason):
Continue the code snippet: <|code_start|> class BanditIssue(Issue): tool = 'bandit' pylint_type = 'R' SKIPPED_PARSE = re.compile( r'(exception while scanning file|syntax error while parsing AST from file)' ) SKIPPED_ACCESS = re.compile( r'Permission denied' <|code_end|> . Use current file imports: import re import sys from bandit import manager, config as bandit_config from bandit.core import extension_loader from .base import PythonTool, Issue, ParseIssue, AccessIssue, UnknownIssue and context (classes, functions, or code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) . Output only the next line.
)
Next line prediction: <|code_start|> class BanditIssue(Issue): tool = 'bandit' pylint_type = 'R' SKIPPED_PARSE = re.compile( r'(exception while scanning file|syntax error while parsing AST from file)' ) SKIPPED_ACCESS = re.compile( r'Permission denied' ) RATING = { 'LOW': 1, 'MEDIUM': 2, 'HIGH': 3, } class TidyPyBanditManager(manager.BanditManager): def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self.config = kwargs.pop('config') super().__init__( bandit_config.BanditConfig(), 'file', ignore_nosec=self.config['options']['ignore-nosec'], <|code_end|> . Use current file imports: (import re import sys from bandit import manager, config as bandit_config from bandit.core import extension_loader from .base import PythonTool, Issue, ParseIssue, AccessIssue, UnknownIssue) and context including class names, function names, or small code snippets from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class UnknownIssue(TidyPyIssue): # """ # A completely unanticipated exception/problem was encountered during the # execution of a tool. # """ # # def __init__(self, exc, filename): # super().__init__( # 'unexpected', # 'Unexpected error (%s)' % (exc,), # filename, # ) . Output only the next line.
profile={
Given the code snippet: <|code_start|> class DlintIssue(Issue): tool = 'dlint' pylint_type = 'W' # pylint: disable=protected-access def get_linter_msg(linter, msg=None): msg = msg or linter._error_tmpl <|code_end|> , generate the next line using the imports in this file: from dlint import linters from .base import PythonTool, Issue, AccessIssue, ParseIssue from ..util import parse_python_file and context (functions, classes, or occasionally code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] . Output only the next line.
if msg.startswith(linter._code):
Given the following code snippet before the placeholder: <|code_start|> class DlintIssue(Issue): tool = 'dlint' pylint_type = 'W' # pylint: disable=protected-access def get_linter_msg(linter, msg=None): msg = msg or linter._error_tmpl if msg.startswith(linter._code): return msg[len(linter._code) + 1:] <|code_end|> , predict the next line using imports from the current file: from dlint import linters from .base import PythonTool, Issue, AccessIssue, ParseIssue from ..util import parse_python_file and context including class names, function names, and sometimes code from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] . Output only the next line.
return msg
Based on the snippet: <|code_start|> class DlintIssue(Issue): tool = 'dlint' pylint_type = 'W' # pylint: disable=protected-access def get_linter_msg(linter, msg=None): msg = msg or linter._error_tmpl if msg.startswith(linter._code): return msg[len(linter._code) + 1:] <|code_end|> , predict the immediate next line with the help of imports: from dlint import linters from .base import PythonTool, Issue, AccessIssue, ParseIssue from ..util import parse_python_file and context (classes, functions, sometimes code) from other files: # Path: src/tidypy/tools/base.py # class PythonTool(Tool): # """ # A convenience abstract class that automatically sets the ``filters`` in the # tool configuration to target Python source files. # """ # # # pylint: disable=abstract-method # # @classmethod # def get_default_config(cls): # config = Tool.get_default_config() # config['filters'] = [ # r'\.py$', # ] # return config # # class Issue: # """ # A class that encapsulates an issue found during the analysis of a project. # """ # # #: A string containing name of the tool that found the issue. # tool = None # # #: A string containing a code that identifies the type of issue found. # code = None # # #: A string containing a description of the issue. # message = None # # #: A string containing the full path to the file where the issue was found. # filename = None # # #: The line number within the file where the issue was found (if known). # #: The first line in a file is notated as 1 (not zero). # line = None # # #: The character number within the line of the file where the issue was # #: found (if known). The first column in a line is notated as 1 (not zero). # character = None # # #: A character indicating the comparable pylint category this issue would # #: fall into: E=error, W=warning, R=refactor, C=convention # pylint_type = 'E' # # def __init__( # self, # code=None, # message=None, # filename=None, # line=None, # character=None): # self.code = code # self.message = message # self.filename = filename # self.line = line if line is not None else 1 # self.character = character or None # # def __repr__(self): # return '%s(%s)' % ( # self.__class__.__name__, # ', '.join([ # repr(self.code), # repr(self.message), # repr(self.filename), # repr(self.line), # repr(self.character), # ]), # ) # # class AccessIssue(TidyPyIssue): # """ # An issue indicating that a file/directory cannot be accessed (typically # due to permissions). # """ # # def __init__(self, exc, filename): # super().__init__( # 'access', # 'Cannot access file (%s)' % (exc,), # filename, # ) # # class ParseIssue(TidyPyIssue): # """ # An issue indicating that a file could not be parsed as expected (e.g., a # Python source file with invalid syntax). # """ # # def __init__(self, exc, filename, line=None, character=None): # if isinstance(exc, SyntaxError): # line = exc.lineno # character = exc.offset # # super().__init__( # 'parse', # 'Unable to parse file (%s)' % (exc,), # filename, # line, # character, # ) # # Path: src/tidypy/util.py # def parse_python_file(filepath): # """ # Retrieves the AST of the specified file. # # This function performs simple caching so that the same file isn't read or # parsed more than once per process. # # :param filepath: the file to parse # :type filepath: str # :returns: ast.AST # """ # # with _AST_CACHE_LOCK: # if filepath not in _AST_CACHE: # source = read_file(filepath) # _AST_CACHE[filepath] = ast.parse(source, filename=filepath) # return _AST_CACHE[filepath] . Output only the next line.
return msg
Next line prediction: <|code_start|> class NumberFieldTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_basic_creation_with_default(self): number = 122 field = NumberField(default=number) self.assertEqual(number, field.number) def test_equals(self): number1 = NumberField(null=False) number1.set(23) number2 = NumberField(null=False) number2.set(23) self.assertEqual(number1, number2) def test_wrong_input(self): number1 = NumberField() <|code_end|> . Use current file imports: (import unittest from arangodb.orm.fields import NumberField) and context including class names, function names, or small code snippets from other files: # Path: arangodb/orm/fields.py # class NumberField(ModelField): # # def __init__(self, **kwargs): # """ # """ # # super(NumberField, self).__init__(**kwargs) # # # # If null is allowed, default value is None # if self.null and not self.default: # self.number = None # else: # # If default value was set # if self.default: # self.number = self.default # else: # self.number = 0 # # def dumps(self): # """ # """ # # return self.number # # def loads(self, number_val): # """ # """ # # self.number = number_val # # def validate(self): # """ # """ # # if self.number is None and self.null is False: # raise NumberField.NotNullableFieldException() # # def set(self, *args, **kwargs): # """ # """ # # if len(args) is 1: # number = args[0] # # if isinstance(number, int) or isinstance(number, float): # self.number = args[0] # else: # raise NumberField.WrongInputTypeException # # def get(self): # """ # """ # # return self.number # # def __eq__(self, other): # """ # """ # # if super(NumberField, self).__eq__(other): # return self.number == other.number # else: # return False . Output only the next line.
try:
Using the snippet: <|code_start|> class BooleanFieldTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): <|code_end|> , determine the next line of code. You have imports: import unittest from arangodb.orm.fields import BooleanField and context (class names, function names, or code) available: # Path: arangodb/orm/fields.py # class BooleanField(ModelField): # # def __init__(self, **kwargs): # """ # """ # # super(BooleanField, self).__init__(**kwargs) # # # If null is allowed, default value is None # if self.null and self.default is None: # self.boolean = None # else: # # If default value was set # if not self.default is None: # self.boolean = self.default # else: # self.boolean = False # # def dumps(self): # """ # """ # # return self.boolean # # def loads(self, boolean_val): # """ # """ # # self.boolean = boolean_val # # def validate(self): # """ # """ # # if self.boolean is None and self.null is False: # raise BooleanField.NotNullableFieldException() # # def set(self, *args, **kwargs): # """ # """ # # if len(args) is 1: # boolean = args[0] # # if isinstance(boolean, bool): # self.boolean = args[0] # else: # raise BooleanField.WrongInputTypeException() # # def get(self): # """ # """ # # return self.boolean # # def __eq__(self, other): # """ # """ # # if super(BooleanField, self).__eq__(other): # return self.boolean == other.boolean # else: # return False . Output only the next line.
pass
Using the snippet: <|code_start|> class UuidFieldTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass <|code_end|> , determine the next line of code. You have imports: import unittest from arangodb import six from arangodb.orm.fields import UuidField and context (class names, function names, or code) available: # Path: arangodb/six.py # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # MAXSIZE = int((1 << 31) - 1) # MAXSIZE = int((1 << 31) - 1) # MAXSIZE = int((1 << 63) - 1) # class X(object): # class _LazyDescr(object): # class MovedModule(_LazyDescr): # class _LazyModule(types.ModuleType): # class MovedAttribute(_LazyDescr): # class _MovedItems(_LazyModule): # class Module_six_moves_urllib_parse(_LazyModule): # class Module_six_moves_urllib_error(_LazyModule): # class Module_six_moves_urllib_request(_LazyModule): # class Module_six_moves_urllib_response(_LazyModule): # class Module_six_moves_urllib_robotparser(_LazyModule): # class Module_six_moves_urllib(types.ModuleType): # class Iterator(object): # def __len__(self): # def _add_doc(func, doc): # def _import_module(name): # def __init__(self, name): # def __get__(self, obj, tp): # def __init__(self, name, old, new=None): # def _resolve(self): # def __getattr__(self, attr): # def __init__(self, name): # def __dir__(self): # def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): # def _resolve(self): # def __dir__(self): # def add_move(move): # def remove_move(name): # def advance_iterator(it): # def callable(obj): # def get_unbound_function(unbound): # def get_unbound_function(unbound): # def create_bound_method(func, obj): # def __next__(self): # def iterkeys(d, **kw): # def itervalues(d, **kw): # def iteritems(d, **kw): # def iterlists(d, **kw): # def b(s): # def u(s): # def int2byte(i): # def b(s): # def u(s): # def byte2int(bs): # def indexbytes(buf, i): # def iterbytes(buf): # def reraise(tp, value, tb=None): # def exec_(_code_, _globs_=None, _locs_=None): # def print_(*args, **kwargs): # def write(data): # def with_metaclass(meta, *bases): # def add_metaclass(metaclass): # def wrapper(cls): # def assertRaisesRegex(self, *args, **kwargs): # def assertRegex(self, *args, **kwargs): # # Path: arangodb/orm/fields.py # class UuidField(CharField): # # def __init__(self, auto_create=True, **kwargs): # """ # """ # # super(UuidField, self).__init__(**kwargs) # # self.auto_create = auto_create # # def on_create(self, model_instance): # """ # """ # # if self.auto_create and self.text is None or self.text == '': # self.text = str(uuid4()) . Output only the next line.
def test_state(self):
Given the following code snippet before the placeholder: <|code_start|> class UserTestCase(ExtendedTestCase): def setUp(self): self.database_name = 'testcase_user_123' self.db = Database.create(name=self.database_name) def tearDown(self): Database.remove(name=self.database_name) <|code_end|> , predict the next line using imports from the current file: from arangodb.tests.base import ExtendedTestCase from arangodb.api import Database from arangodb.user import User and context including class names, function names, and sometimes code from other files: # Path: arangodb/tests/base.py # class ExtendedTestCase(unittest.TestCase): # def assertDocumentsEqual(self, doc1, doc2): # """ # """ # # self.assertEqual(doc1.id, doc2.id) # # for prop in doc1.data: # doc1_val = doc1.data[prop] # doc2_val = doc2.data[prop] # # self.assertEqual(doc1_val, doc2_val) # # Path: arangodb/api.py # class Database(object): # @classmethod # def create(cls, name, users=None): # """ # Creates database and sets itself as the active database. # # :param name Database name # # :returns Database # """ # # api = Client.instance().api # # database_data = { # 'name': name, # 'active': True, # } # # if isinstance(users, list) or isinstance(users, tuple): # database_data['users'] = users # # data = api.database.post(data=database_data) # # db = Database( # name=name, # api=api, # kwargs=data # ) # # Client.instance().set_database(name=name) # # return db # # @classmethod # def get_all(cls): # """ # Returns an array with all databases # # :returns Database list # """ # # api = Client.instance().api # # data = api.database.get() # # database_names = data['result'] # databases = [] # # for name in database_names: # db = Database(name=name, api=api) # databases.append(db) # # return databases # # # @classmethod # def remove(cls, name): # """ # Destroys the database. # """ # # client = Client.instance() # # new_current_database = None # # if client.database != name: # new_current_database = name # # # Deletions are only possible from the system database # client.set_database(name=SYSTEM_DATABASE) # # api = client.api # api.database(name).delete() # # if new_current_database: # client.set_database(name=new_current_database) # # # def __init__(self, name, api, **kwargs): # """ # """ # # self.name = name # self.api = api # # def create_collection(self, name, type=2): # """ # Shortcut to create a collection # # :param name Collection name # :param type Collection type (2 = document / 3 = edge) # # :returns Collection # """ # # return Collection.create(name=name, database=self.name, type=type) # # Path: arangodb/user.py # class User(object): # """ # """ # # @classmethod # def get(cls, name): # """ # """ # # api = Client.instance().api # # user = api.user(name).get() # # user_name = user['user'] # change_password = user['changePassword'] # active = user['active'] # extra = user['extra'] # # user_obj = cls(name=user_name, change_password=change_password, active=active, extra=extra, api=api) # # return user_obj # # @classmethod # def create(cls, name, password='', active=True, extra=None, change_password=False): # """ # """ # # api = Client.instance().api # # api.user.post({ # 'user': name, # 'passwd': password, # 'active': active, # 'exta': extra, # 'changePassword': change_password, # }) # # user_obj = cls(name=name, change_password=change_password, active=active, extra=extra, api=api) # # return user_obj # # @classmethod # def remove(cls, name): # """ # """ # # api = Client.instance().api # # api.user(name).delete() # # # def __init__(self, name, change_password, active, api, extra=None): # """ # """ # # self.name = name # self.change_password = change_password # self.active = active # self.extra = extra # # self.api = api . Output only the next line.
def test_get_root(self):
Continue the code snippet: <|code_start|> class UserTestCase(ExtendedTestCase): def setUp(self): self.database_name = 'testcase_user_123' self.db = Database.create(name=self.database_name) def tearDown(self): Database.remove(name=self.database_name) def test_get_root(self): root = User.get(name='root') <|code_end|> . Use current file imports: from arangodb.tests.base import ExtendedTestCase from arangodb.api import Database from arangodb.user import User and context (classes, functions, or code) from other files: # Path: arangodb/tests/base.py # class ExtendedTestCase(unittest.TestCase): # def assertDocumentsEqual(self, doc1, doc2): # """ # """ # # self.assertEqual(doc1.id, doc2.id) # # for prop in doc1.data: # doc1_val = doc1.data[prop] # doc2_val = doc2.data[prop] # # self.assertEqual(doc1_val, doc2_val) # # Path: arangodb/api.py # class Database(object): # @classmethod # def create(cls, name, users=None): # """ # Creates database and sets itself as the active database. # # :param name Database name # # :returns Database # """ # # api = Client.instance().api # # database_data = { # 'name': name, # 'active': True, # } # # if isinstance(users, list) or isinstance(users, tuple): # database_data['users'] = users # # data = api.database.post(data=database_data) # # db = Database( # name=name, # api=api, # kwargs=data # ) # # Client.instance().set_database(name=name) # # return db # # @classmethod # def get_all(cls): # """ # Returns an array with all databases # # :returns Database list # """ # # api = Client.instance().api # # data = api.database.get() # # database_names = data['result'] # databases = [] # # for name in database_names: # db = Database(name=name, api=api) # databases.append(db) # # return databases # # # @classmethod # def remove(cls, name): # """ # Destroys the database. # """ # # client = Client.instance() # # new_current_database = None # # if client.database != name: # new_current_database = name # # # Deletions are only possible from the system database # client.set_database(name=SYSTEM_DATABASE) # # api = client.api # api.database(name).delete() # # if new_current_database: # client.set_database(name=new_current_database) # # # def __init__(self, name, api, **kwargs): # """ # """ # # self.name = name # self.api = api # # def create_collection(self, name, type=2): # """ # Shortcut to create a collection # # :param name Collection name # :param type Collection type (2 = document / 3 = edge) # # :returns Collection # """ # # return Collection.create(name=name, database=self.name, type=type) # # Path: arangodb/user.py # class User(object): # """ # """ # # @classmethod # def get(cls, name): # """ # """ # # api = Client.instance().api # # user = api.user(name).get() # # user_name = user['user'] # change_password = user['changePassword'] # active = user['active'] # extra = user['extra'] # # user_obj = cls(name=user_name, change_password=change_password, active=active, extra=extra, api=api) # # return user_obj # # @classmethod # def create(cls, name, password='', active=True, extra=None, change_password=False): # """ # """ # # api = Client.instance().api # # api.user.post({ # 'user': name, # 'passwd': password, # 'active': active, # 'exta': extra, # 'changePassword': change_password, # }) # # user_obj = cls(name=name, change_password=change_password, active=active, extra=extra, api=api) # # return user_obj # # @classmethod # def remove(cls, name): # """ # """ # # api = Client.instance().api # # api.user(name).delete() # # # def __init__(self, name, change_password, active, api, extra=None): # """ # """ # # self.name = name # self.change_password = change_password # self.active = active # self.extra = extra # # self.api = api . Output only the next line.
self.assertEqual(root.name, 'root')
Predict the next line for this snippet: <|code_start|> class DocumentTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_document_access_values_by_attribute_getter(self): doc = Document(id='', key='', collection='', api=client.api) # set this to true so it won't make requests to nothing doc.is_loaded = True <|code_end|> with the help of current file imports: import unittest from arangodb.api import Document from arangodb.tests.base import client and context from other files: # Path: arangodb/api.py # class Document(object): # @classmethod # def create(cls, collection): # """ # Creates document object without really creating it in the collection. # # :param collection Collection instance # # :returns Document # """ # # api = Client.instance().api # # doc = Document( # id='', # key='', # collection=collection.name, # api=api, # ) # # return doc # # def __init__(self, id, key, collection, api, **kwargs): # """ # :param id Document id (collection_name/number) # :param key Document key (number) # :param collection Collection name # :param api Slumber API object # # :param rev Document revision, default value is key # """ # # self.data = {} # self.is_loaded = False # # self.id = id # self.key = key # self.revision = kwargs.pop('rev', key) # self.collection = collection # self.api = api # self.resource = api.document # # # def retrieve(self): # """ # Retrieves all data for this document and saves it. # """ # # data = self.resource(self.id).get() # self.data = data # # return data # # def delete(self): # """ # Removes the document from the collection # """ # # self.resource(self.id).delete() # # def save(self): # """ # If its internal state is loaded than it will only updated the # set properties but otherwise it will create a new document. # """ # # # TODO: Add option force_insert # # if not self.is_loaded and self.id is None or self.id == '': # data = self.resource.post(data=self.data, collection=self.collection) # self.id = data['_id'] # self.key = data['_key'] # self.revision = data['_rev'] # self.is_loaded = True # else: # data = self.resource(self.id).patch(data=self.data) # self.revision = data['_rev'] # # def get(self, key): # """ # Returns attribute value. # # :param key # # :returns value # """ # # if not self.is_loaded: # self.retrieve() # # self.is_loaded = True # # if self.has(key=key): # return self.data[key] # else: # return None # # def set(self, key, value): # """ # Sets document value # # :param key # :param value # """ # # self.data[key] = value # # def has(self, key): # """ # Returns if the document has a attribute with the name key # """ # # return key in self.data # # def get_attributes(self): # """ # Return dict with all attributes # """ # # return self.data # # def __getattr__(self, item): # """ # """ # # val = self.get(key=item) # return val # # def __setattr__(self, key, value): # """ # """ # # # Set internal variables normally # if key in ['data', 'is_loaded', 'id', 'key', 'revision', 'collection', 'api', 'resource']: # super(Document, self).__setattr__(key, value) # else: # self.set(key=key, value=value) # # def __repr__(self): # """ # """ # return self.__str__() # # def __str__(self): # return self.__unicode__() # # def __unicode__(self): # return "%s" % self.id # # Path: arangodb/tests/base.py # class ExtendedTestCase(unittest.TestCase): # def assertDocumentsEqual(self, doc1, doc2): , which may contain function names, class names, or code. Output only the next line.
doc_attr_value = 'foo_bar'
Predict the next line after this snippet: <|code_start|> class EndpointTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_all_endpoints(self): endpoints = Endpoint.all() <|code_end|> using the current file's imports: import unittest from arangodb.server.endpoint import Endpoint and any relevant context from other files: # Path: arangodb/server/endpoint.py # class Endpoint(object): # """ # Class to manage endpoints on which the server is listening # """ # # @classmethod # def all(cls): # """ # Returns a list of all configured endpoints the server is listening on. For each endpoint, # the list of allowed databases is returned too if set. # # The result is a JSON hash which has the endpoints as keys, and the list of # mapped database names as values for each endpoint. # # If a list of mapped databases is empty, it means that all databases can be accessed via the endpoint. # If a list of mapped databases contains more than one database name, this means that any of the # databases might be accessed via the endpoint, and the first database in the list will be treated # as the default database for the endpoint. The default database will be used when an incoming request # does not specify a database name in the request explicitly. # # *Note*: retrieving the list of all endpoints is allowed in the system database only. # Calling this action in any other database will make the server return an error. # """ # # api = Client.instance().api # # endpoint_list = api.endpoint.get() # # return endpoint_list # # @classmethod # def create(cls, url, databases): # """ # If databases is an empty list, all databases present in the server will become accessible via the endpoint, # with the _system database being the default database. # # If databases is non-empty, only the specified databases will become available via the endpoint. # The first database name in the databases list will also become the default database for the endpoint. # The default database will always be used if a request coming in on the endpoint does not specify # the database name explicitly. # # *Note*: adding or reconfiguring endpoints is allowed in the system database only. # Calling this action in any other database will make the server return an error. # # Adding SSL endpoints at runtime is only supported if the server was started with SSL # properly configured (e.g. --server.keyfile must have been set). # # :param url the endpoint specification, e.g. tcp://127.0.0.1:8530 # :param databases a list of database names the endpoint is responsible for. # """ # # api = Client.instance().api # # result = api.endpoint.post(data={ # 'endpoint': url, # 'databases': databases, # }) # # return result # # @classmethod # def destroy(cls, url): # """ # This operation deletes an existing endpoint from the list of all endpoints, # and makes the server stop listening on the endpoint. # # *Note*: deleting and disconnecting an endpoint is allowed in the system database only. # Calling this action in any other database will make the server return an error. # # Futhermore, the last remaining endpoint cannot be deleted as this would make the server kaput. # # :param url The endpoint to delete, e.g. tcp://127.0.0.1:8529. # """ # # api = Client.instance().api # # api.endpoint(url).delete() . Output only the next line.
self.assertTrue(len(endpoints) > 0)
Here is a snippet: <|code_start|> class DatabaseTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_create_and_delete_database(self): database_name = 'test_foo_123' db = Database.create(name=database_name) self.assertIsNotNone(db) Database.remove(name=database_name) def test_get_all_databases(self): databases = Database.get_all() self.assertTrue(len(databases) >= 1) <|code_end|> . Write the next line using the current file imports: import unittest from arangodb.api import Database and context from other files: # Path: arangodb/api.py # class Database(object): # @classmethod # def create(cls, name, users=None): # """ # Creates database and sets itself as the active database. # # :param name Database name # # :returns Database # """ # # api = Client.instance().api # # database_data = { # 'name': name, # 'active': True, # } # # if isinstance(users, list) or isinstance(users, tuple): # database_data['users'] = users # # data = api.database.post(data=database_data) # # db = Database( # name=name, # api=api, # kwargs=data # ) # # Client.instance().set_database(name=name) # # return db # # @classmethod # def get_all(cls): # """ # Returns an array with all databases # # :returns Database list # """ # # api = Client.instance().api # # data = api.database.get() # # database_names = data['result'] # databases = [] # # for name in database_names: # db = Database(name=name, api=api) # databases.append(db) # # return databases # # # @classmethod # def remove(cls, name): # """ # Destroys the database. # """ # # client = Client.instance() # # new_current_database = None # # if client.database != name: # new_current_database = name # # # Deletions are only possible from the system database # client.set_database(name=SYSTEM_DATABASE) # # api = client.api # api.database(name).delete() # # if new_current_database: # client.set_database(name=new_current_database) # # # def __init__(self, name, api, **kwargs): # """ # """ # # self.name = name # self.api = api # # def create_collection(self, name, type=2): # """ # Shortcut to create a collection # # :param name Collection name # :param type Collection type (2 = document / 3 = edge) # # :returns Collection # """ # # return Collection.create(name=name, database=self.name, type=type) , which may include functions, classes, or code. Output only the next line.
for db in databases:
Predict the next line for this snippet: <|code_start|> self.assertTrue(True, 'The value is valid') def test_equals(self): choice1 = ChoiceField(choices=[ ('value', 'DESCRIPTION'), ('value2', 'DESCRIPTION 2'), ]) choice1.set('value') choice2 = ChoiceField(choices=[ ('value', 'DESCRIPTION'), ('value2', 'DESCRIPTION 2'), ]) choice2.set('value') self.assertEqual(choice1, choice2) def test_none_validation(self): choice = ChoiceField(choices=[ ('value', 'DESCRIPTION'), ('value2', 'DESCRIPTION 2'), ], null=False) had_exception = False try: <|code_end|> with the help of current file imports: import unittest from arangodb.orm.fields import ChoiceField and context from other files: # Path: arangodb/orm/fields.py # class ChoiceField(ModelField): # """ # """ # # def __init__(self, choices, multiple=False, **kwargs): # """ # """ # # super(ChoiceField, self).__init__(**kwargs) # # self.choices = choices # # # If null is allowed, default value is None # if self.null and not self.default: # self.choice_value = None # else: # # If default value was set # if self.default: # self.choice_value = self.default # else: # self.choice_value = '' # # def dumps(self): # """ # """ # # return self.choice_value # # def loads(self, string_val): # """ # """ # # self.choice_value = string_val # # def validate(self): # """ # """ # # has_match = False # # for choice_pair in self.choices: # if choice_pair[0] == self.choice_value: # has_match = True # break # # if not has_match: # raise ChoiceField.WrongInputTypeException() # # if self.choice_value is None and self.null is False: # raise ChoiceField.NotNullableFieldException() # # def set(self, *args, **kwargs): # """ # """ # # if len(args) is 1: # choice_value = args[0] # self.choice_value = choice_value # # self.validate() # # def get(self): # """ # """ # # return self.choice_value # # def __eq__(self, other): # """ # """ # # if super(ChoiceField, self).__eq__(other): # return self.choice_value == other.choice_value # else: # return False # # def __getattribute__(self, item): # """ # """ # # if item == 'flatchoices': # return object.__getattribute__(self, 'choices') # else: # return super(ChoiceField, self).__getattribute__(item) , which may contain function names, class names, or code. Output only the next line.
choice.validate()
Here is a snippet: <|code_start|> def setUp(self): pass def tearDown(self): pass def test_basic_creation_with_default(self): date = datetime.date.today() field = DateField(default=date) self.assertEqual(date, field.date) def test_equals(self): date = datetime.date.today() field1 = DateField() field1.set(date) field2 = DateField() field2.set(date) self.assertEqual(field1, field2) def test_not_equals(self): field1 = DateField(null=False) field1.set(datetime.date(2012, 12, 2)) field2 = DateField(null=False) field2.set(datetime.date(2011, 11, 4)) <|code_end|> . Write the next line using the current file imports: import unittest import datetime from arangodb.orm.fields import DateField and context from other files: # Path: arangodb/orm/fields.py # class DateField(ModelField): # # DATE_FORMAT = '%Y-%m-%d' # # def __init__(self, **kwargs): # """ # """ # # super(DateField, self).__init__(**kwargs) # # if self.null and not self.default: # self.date = None # else: # if self.default: # self.date = self.default # else: # self.date = date.today() # # def dumps(self): # """ # """ # # if self.null and self.date is None: # return None # else: # if self.date is None: # raise Exception('Datetime cannot be None') # else: # return '%s' % self.date.strftime(DateField.DATE_FORMAT) # # def loads(self, date_string): # """ # """ # # if not self.null: # self.date = datetime.strptime(date_string, DateField.DATE_FORMAT) # else: # self.date = None # # def validate(self): # """ # """ # # def set(self, *args, **kwargs): # """ # """ # # if len(args) is 1: # date = args[0] # if isinstance(args, six.string_types): # self.loads(date) # else: # self.date = date # # def get(self): # """ # """ # # return self.date # # def __eq__(self, other): # """ # """ # # if super(DateField, self).__eq__(other): # return self.date == other.date # else: # return False , which may include functions, classes, or code. Output only the next line.
self.assertTrue(field1 != field2)
Next line prediction: <|code_start|> def create_document_from_result_dict(result_dict, api): collection_name = result_dict['_id'].split('/')[0] doc = Document( id=result_dict['_id'], key=result_dict['_key'], rev=result_dict['_rev'], collection=collection_name, <|code_end|> . Use current file imports: (from arangodb.api import Document) and context including class names, function names, or small code snippets from other files: # Path: arangodb/api.py # class Document(object): # @classmethod # def create(cls, collection): # """ # Creates document object without really creating it in the collection. # # :param collection Collection instance # # :returns Document # """ # # api = Client.instance().api # # doc = Document( # id='', # key='', # collection=collection.name, # api=api, # ) # # return doc # # def __init__(self, id, key, collection, api, **kwargs): # """ # :param id Document id (collection_name/number) # :param key Document key (number) # :param collection Collection name # :param api Slumber API object # # :param rev Document revision, default value is key # """ # # self.data = {} # self.is_loaded = False # # self.id = id # self.key = key # self.revision = kwargs.pop('rev', key) # self.collection = collection # self.api = api # self.resource = api.document # # # def retrieve(self): # """ # Retrieves all data for this document and saves it. # """ # # data = self.resource(self.id).get() # self.data = data # # return data # # def delete(self): # """ # Removes the document from the collection # """ # # self.resource(self.id).delete() # # def save(self): # """ # If its internal state is loaded than it will only updated the # set properties but otherwise it will create a new document. # """ # # # TODO: Add option force_insert # # if not self.is_loaded and self.id is None or self.id == '': # data = self.resource.post(data=self.data, collection=self.collection) # self.id = data['_id'] # self.key = data['_key'] # self.revision = data['_rev'] # self.is_loaded = True # else: # data = self.resource(self.id).patch(data=self.data) # self.revision = data['_rev'] # # def get(self, key): # """ # Returns attribute value. # # :param key # # :returns value # """ # # if not self.is_loaded: # self.retrieve() # # self.is_loaded = True # # if self.has(key=key): # return self.data[key] # else: # return None # # def set(self, key, value): # """ # Sets document value # # :param key # :param value # """ # # self.data[key] = value # # def has(self, key): # """ # Returns if the document has a attribute with the name key # """ # # return key in self.data # # def get_attributes(self): # """ # Return dict with all attributes # """ # # return self.data # # def __getattr__(self, item): # """ # """ # # val = self.get(key=item) # return val # # def __setattr__(self, key, value): # """ # """ # # # Set internal variables normally # if key in ['data', 'is_loaded', 'id', 'key', 'revision', 'collection', 'api', 'resource']: # super(Document, self).__setattr__(key, value) # else: # self.set(key=key, value=value) # # def __repr__(self): # """ # """ # return self.__str__() # # def __str__(self): # return self.__unicode__() # # def __unicode__(self): # return "%s" % self.id . Output only the next line.
api=api,
Continue the code snippet: <|code_start|> [submitter_id] ))) def is_variant_name(self, variant_name): return bool(list(self.cursor.execute( 'SELECT 1 FROM submissions WHERE variant_name=? LIMIT 1', [variant_name] ))) def max_date(self): return list(self.cursor.execute('SELECT MAX(date) FROM submissions'))[0][0] @promise def significance_term_info(self): return list(self.cursor.execute(''' SELECT significance, MIN(date) AS first_seen, MAX(date) AS last_seen FROM submissions GROUP BY significance ORDER BY last_seen DESC, first_seen DESC ''')) def submissions(self, **kwargs): self.query = ''' SELECT variant_name, submitter1_id AS submitter_id, submitter1_name AS submitter_name, rcv1 AS rcv, scv1 AS scv, significance1 AS significance, last_eval1 AS last_eval, review_status1 AS review_status, <|code_end|> . Use current file imports: import sqlite3 from asynchelper import promise and context (classes, functions, or code) from other files: # Path: asynchelper.py # def promise(fn): # return lambda *args, **kwargs: ThreadPoolExecutor(1).submit(fn, *args, **kwargs) . Output only the next line.
condition1_name AS condition_name,
Given snippet: <|code_start|>from __future__ import unicode_literals __author__ = 'luissaguas' def save_upload_file(fname, content, dn, parent=None): content_type = mimetypes.guess_type(fname)[0] file_data = write_file_jrxml(fname, content, dn=dn, content_type=content_type, parent=parent) <|code_end|> , continue by predicting the next line. Consider current file imports: import frappe import mimetypes from frappe import _ from frappe.utils.file_manager import get_uploaded_content from jasper_erpnext_report.utils.jasper_file_jrxml import write_file_jrxml and context: # Path: jasper_erpnext_report/utils/jasper_file_jrxml.py # def write_file_jrxml(fname, content, dn=None, content_type=None, parent=None): # dt = frappe.form_dict.doctype # if dt == "Jasper Reports": # wobj = WriteFileJrxml(dt, fname, content, parent) # f = wobj.process(dn=dn) # # return f which might include code, classes, or functions. Output only the next line.
return file_data
Next line prediction: <|code_start|>no_cache = True def get_context(context): if frappe.local.session['sid'] == 'Guest': return {"message":_("Please login first."), "doc_title":_("Not Permitted")} jasper_report_path = frappe.form_dict.jasper_doc_path if not jasper_report_path: return {"message":_("Switch to Desk to see the list of reports."), "doc_title":_("Not Permitted")} filename = jasper_report_path.rsplit("/",1)[1] doc_title = jasper_report_path.split("/",1)[0] ext = get_extension(filename) if "pdf" == ext: viewer = viewer_pdf elif "html" == ext: viewer = viewer_html else: return {"message":_("Switch to Desk to see the list of reports."), "doc_title":_("Not Permitted")} context.children = get_all_email_reports() context.pathname = "Jasper Reports?jasper_doc_path=" + jasper_report_path return viewer(doc_title) def get_all_email_reports(): approved_childs = [] user_email = frappe.db.get_value("User", frappe.session.user, "email") crit = "`tabJasper Email Report`.jasper_email_sent_to='%s'" % (user_email,) <|code_end|> . Use current file imports: (import frappe import frappe.utils from frappe import _ from jasper_erpnext_report.utils.file import get_extension) and context including class names, function names, or small code snippets from other files: # Path: jasper_erpnext_report/utils/file.py # def get_extension(fname): # # ext = fname.rsplit(".",1) # # if len(ext) > 1: # return ext[1].lower() # # return ext[0] . Output only the next line.
childrens = frappe.get_all("Jasper Email Report", filters=[crit], fields=["jasper_report_path", "jasper_email_report_name", "jasper_file_name", "jasper_email_date"], order_by="jasper_email_date ASC", limit_page_length=10)
Given snippet: <|code_start|> def run_local_report_async(self, path, doc, data=None, params=None, pformat="pdf", ncopies=1, for_all_sites=0): try: self.frappe_task = FrappeTask(frappe.local.task_id, None) cresp = self.prepare_report_async(path, doc, data=data, params=params, pformat=pformat, ncopies=ncopies, for_all_sites=for_all_sites) return [cresp] except Exception as e: frappe.throw(_("Error in report %s, error is: %s." % (doc.jasper_report_name, frappe.get_traceback()))) def _run_report_async(self, path, doc, data=None, params=None, pformat="pdf", ncopies=1, for_all_sites=0): data = data or {} hashmap = jr.HashMap() pram, pram_server, copies = self.do_params(data, params, pformat, doc) pram_copy_index = copies.get("pram_copy_index", -1) pram_copy_page_index = copies.get("pram_copy_page_index", -1) path_join = os.path.join resp = [] custom = doc.get("jasper_custom_fields") pram.extend(self.get_param_hook(doc, data, pram_server)) self.populate_hashmap(pram, hashmap, doc.jasper_report_name) copies = [_("Original"), _("Duplicate"), _("Triplicate")] conn = "" if doc.query: conn = "jdbc:mysql://" + (frappe.conf.db_host or '127.0.0.1') + ":" + (frappe.conf.db_port or "3306") + "/" + frappe.conf.db_name + "?user="+ frappe.conf.db_name +\ <|code_end|> , continue by predicting the next line. Consider current file imports: from frappe import _ from frappe.utils import cint from jasper_erpnext_report.utils.file import get_jasper_path, get_file from jasper_erpnext_report.utils.jasper_file_jrxml import get_compiled_path from jasper_erpnext_report.core.FrappeTask import FrappeTask from jasper_erpnext_report.utils.utils import get_hook_module from jasper_erpnext_report.jasper_reports.FrappeDataSource import _JasperCustomDataSource from jasper_erpnext_report.jasper_reports.ScriptletDefault import _JasperCustomScriptlet from jasper_erpnext_report.utils.utils import get_hook_module from jasper_erpnext_report.jasper_reports.ScriptletDefault import _JasperCustomScriptlet import frappe import jasper_erpnext_report.utils.utils as utils import jasper_erpnext_report.jasper_reports as jr import JasperBase as Jb import os and context: # Path: jasper_erpnext_report/utils/file.py # def get_jasper_path(for_all_sites = False): # if not for_all_sites: # return get_site_path("jasper") # # module_path = os.path.normpath(os.path.join(os.path.dirname(jasper_erpnext_report.__file__), "jasper")) # return module_path # # def get_file(path, modes="r", raise_not_found=False): # if modes != "r": # content = read_file(path, modes=modes, raise_not_found=raise_not_found) # else: # content = frappe.read_file(path, raise_not_found=raise_not_found) # # return content # # Path: jasper_erpnext_report/utils/jasper_file_jrxml.py # def get_compiled_path(dir_path, dn): # jrxml_path = get_jrxml_path(dir_path, dn) # compiled_path = frappe.utils.get_path("compiled", base=jrxml_path) # frappe.create_folder(compiled_path) # return compiled_path which might include code, classes, or functions. Output only the next line.
"&password=" + frappe.conf.db_password
Next line prediction: <|code_start|> res = self.prepareResponse({"reportURI": os.path.relpath(batch.outputPath, batch.jasper_path) + os.sep + batch.reportName + "." + pformat}, batch.sessionId) res["status"] = None res["report_name"] = data.get("report_name") resp.append(res) batch.batchReport.setTaskHandler(self.frappe_task) result = {"fileName": batch.reportName + "." + pformat, "uri":batch.outputPath + os.sep + batch.reportName + "." + pformat, "last_updated": res.get("reqtime"), 'session_expiry': utils.get_expiry_period(batch.sessionId)} self.insert_jasper_reqid_record(batch.sessionId, {"data":{"result":result, "report_name": data.get("report_name"), "last_updated": frappe.utils.now(),'session_expiry': utils.get_expiry_period()}}) frappe.local.batch = batch lang = data.get("params", {}).get("locale", None) or "EN" cur_doctype = data.get("cur_doctype") ids = data.get('ids', [])[:] virtua = 0 if doc.jasper_virtualizer: virtua = cint(frappe.db.get_value('JasperServerConfig', fieldname="jasper_virtualizer_pages")) or 0 if custom and not frappe.local.fds: default = ['jasper_erpnext_report.jasper_reports.FrappeDataSource.JasperCustomDataSourceDefault'] jds_method = utils.jasper_run_method_once_with_default("jasper_custom_data_source", data.get("report_name"), default) if jds_method.__name__ == 'JasperCustomDataSourceDefault': jscriptlet_module = get_hook_module("jasper_custom_data_source", data.get("report_name")) if jscriptlet_module: jds_method = jscriptlet_module.get_data frappe.local.fds = jds_method for m in range(ncopies): if pram_copy_index != -1: <|code_end|> . Use current file imports: (from frappe import _ from frappe.utils import cint from jasper_erpnext_report.utils.file import get_jasper_path, get_file from jasper_erpnext_report.utils.jasper_file_jrxml import get_compiled_path from jasper_erpnext_report.core.FrappeTask import FrappeTask from jasper_erpnext_report.utils.utils import get_hook_module from jasper_erpnext_report.jasper_reports.FrappeDataSource import _JasperCustomDataSource from jasper_erpnext_report.jasper_reports.ScriptletDefault import _JasperCustomScriptlet from jasper_erpnext_report.utils.utils import get_hook_module from jasper_erpnext_report.jasper_reports.ScriptletDefault import _JasperCustomScriptlet import frappe import jasper_erpnext_report.utils.utils as utils import jasper_erpnext_report.jasper_reports as jr import JasperBase as Jb import os) and context including class names, function names, or small code snippets from other files: # Path: jasper_erpnext_report/utils/file.py # def get_jasper_path(for_all_sites = False): # if not for_all_sites: # return get_site_path("jasper") # # module_path = os.path.normpath(os.path.join(os.path.dirname(jasper_erpnext_report.__file__), "jasper")) # return module_path # # def get_file(path, modes="r", raise_not_found=False): # if modes != "r": # content = read_file(path, modes=modes, raise_not_found=raise_not_found) # else: # content = frappe.read_file(path, raise_not_found=raise_not_found) # # return content # # Path: jasper_erpnext_report/utils/jasper_file_jrxml.py # def get_compiled_path(dir_path, dn): # jrxml_path = get_jrxml_path(dir_path, dn) # compiled_path = frappe.utils.get_path("compiled", base=jrxml_path) # frappe.create_folder(compiled_path) # return compiled_path . Output only the next line.
values = pram[pram_copy_index].get("value","")
Predict the next line after this snippet: <|code_start|> for m in range(ncopies): if pram_copy_index != -1: values = pram[pram_copy_index].get("value","") pram_copy_name = pram[pram_copy_index].get("name","") if not values or not values[0]: hashmap.put(pram_copy_name, copies[m]) else: hashmap.put(pram_copy_name, frappe.utils.strip(values[m], ' \t\n\r')) if pram_copy_page_index != -1: pram_copy_page_name = pram[pram_copy_page_index].get("name","") hashmap.put(pram_copy_page_name, str(m) + _(" of ") + str(ncopies)) mparams = jr.HashMap() mparams.put("path_jasper_file", frappe.local.batch.compiled_path + os.sep) mparams.put("reportName", frappe.local.batch.reportName) mparams.put("outputPath", frappe.local.batch.outputPath + os.sep) mparams.put("params", hashmap) mparams.put("conn", conn) mparams.put("type", jr.Integer(frappe.local.batch.outtype)) mparams.put("lang", lang) mparams.put("virtua", jr.Integer(virtua)) #used for xml datasource mparams.put("numberPattern", frappe.db.get_default("number_format")) mparams.put("datePattern", frappe.db.get_default("date_format") + " HH:mm:ss") self._export_report(mparams, data.get("report_name"), data.get("grid_data"), frappe.local.batch.sessionId, cur_doctype, custom, ids, frappe.local.fds) if pram_copy_index != -1 and ncopies > 1: hashmap = jr.HashMap() self.populate_hashmap(pram, hashmap, doc.jasper_report_name) <|code_end|> using the current file's imports: from frappe import _ from frappe.utils import cint from jasper_erpnext_report.utils.file import get_jasper_path, get_file from jasper_erpnext_report.utils.jasper_file_jrxml import get_compiled_path from jasper_erpnext_report.core.FrappeTask import FrappeTask from jasper_erpnext_report.utils.utils import get_hook_module from jasper_erpnext_report.jasper_reports.FrappeDataSource import _JasperCustomDataSource from jasper_erpnext_report.jasper_reports.ScriptletDefault import _JasperCustomScriptlet from jasper_erpnext_report.utils.utils import get_hook_module from jasper_erpnext_report.jasper_reports.ScriptletDefault import _JasperCustomScriptlet import frappe import jasper_erpnext_report.utils.utils as utils import jasper_erpnext_report.jasper_reports as jr import JasperBase as Jb import os and any relevant context from other files: # Path: jasper_erpnext_report/utils/file.py # def get_jasper_path(for_all_sites = False): # if not for_all_sites: # return get_site_path("jasper") # # module_path = os.path.normpath(os.path.join(os.path.dirname(jasper_erpnext_report.__file__), "jasper")) # return module_path # # def get_file(path, modes="r", raise_not_found=False): # if modes != "r": # content = read_file(path, modes=modes, raise_not_found=raise_not_found) # else: # content = frappe.read_file(path, raise_not_found=raise_not_found) # # return content # # Path: jasper_erpnext_report/utils/jasper_file_jrxml.py # def get_compiled_path(dir_path, dn): # jrxml_path = get_jrxml_path(dir_path, dn) # compiled_path = frappe.utils.get_path("compiled", base=jrxml_path) # frappe.create_folder(compiled_path) # return compiled_path . Output only the next line.
return resp
Given snippet: <|code_start|> size += 1 for report in with_param: name = report.parent if name == r.name: if report.jasper_param_action == "Automatic": break report.pop("parent") report.pop("p_name") report.pop("jasper_param_action") ret[r.name]["params"].append(report) break for perm in with_perm_role: name = perm.parent if name == r.name: perm.pop("parent") ret[r.name]["perms"].append(perm) ret["size"] = size ret["origin"] = origin return ret def jasper_print_formats(doc): ret = [] if int(doc.jasper_print_all) == 0: for fmt in jasper_formats: if int(doc.get("jasper_print_" + fmt,0) or 0) == 1: ret.append(fmt) else: ret = jasper_formats <|code_end|> , continue by predicting the next line. Consider current file imports: import frappe import re import jasper_erpnext_report import os, sys import sys import jasper_erpnext_report as jr import semantic_version as sv from frappe import _ from frappe.modules.import_file import import_doc from ast import literal_eval from . cache import * from . jasper_document import * from . jasper_email import set_jasper_email_doctype from jasper_erpnext_report.utils.jasper_iter_hooks import JasperHooks from jasper_erpnext_report.jasper_reports.ScriptletDefault import JasperCustomScripletDefault from datetime import timedelta and context: # Path: jasper_erpnext_report/utils/jasper_iter_hooks.py # class JasperHooks: # def __init__(self, hook_name, docname=None, fallback=None): # self.hook_name = hook_name # self.current = 0 # self.methods = frappe.get_hooks().get(self.hook_name) or (fallback if fallback is not None else []) # if isinstance(self.methods, dict): # if docname in self.methods.keys(): # self.methods = self.methods[docname] # else: # self.methods = fallback if fallback is not None else [] # self.methods_len = len(self.methods) # # # def __iter__(self): # return self # # def next(self): # if self.current >= self.methods_len: # raise StopIteration # else: # return self.get_next_jasper_hook_method() # # def get_next_jasper_hook_method(self): # if self.methods_len > 0: # curr_method = frappe.get_attr(self.methods[self.current]) # self.current += 1 # return curr_method # return None which might include code, classes, or functions. Output only the next line.
return ret
Next line prediction: <|code_start|> xmldoc = JasperXmlReport(jrxml_os_path) if (self.ext!="properties" and self.ext != "xml"): image_path = xmldoc.get_image_path_from_jrxml(self.fname) self.file_path= self.path_join(self.compiled_path, os.path.normpath(image_path)) elif (self.ext == "xml"): xmlname = xmldoc.getProperty("XMLNAME") if xmlname: xname = xmlname + ".xml" if xname != self.fname: frappe.msgprint(_("This report does't have %s as file source." % (self.fname,)),raise_exception=True) self.file_path = self.path_join(self.compiled_path, os.path.normpath(self.fname)) else: frappe.msgprint(_("This report does't have %s as file source." % (self.fname,)),raise_exception=True) else: value = xmldoc.get_attrib("resourceBundle") if not value or value not in self.fname: frappe.msgprint(_("This report does't have %s as properties." % (self.fname,)),raise_exception=True) self.file_path = self.path_join(self.compiled_path, os.path.normpath(self.fname)) break else: frappe.msgprint(_("Add a file for this report first."),raise_exception=True) def process_jrxmls(self): rname = check_if_jrxml_exists_db(self.dt, self.dn, self.fname, self.parent) if rname: if rname: frappe.msgprint(_("Remove first the file (%s) associated with this document or (%s) is a wrong parent." % (rname, rname)), raise_exception=True) <|code_end|> . Use current file imports: (import frappe import os import StringIO import shutil from frappe import _ from io import BytesIO from jasper_erpnext_report.jasper_reports.compile_reports import jasper_compile from jasper_erpnext_report.utils.file import check_extension, get_jasper_path, get_extension, JasperXmlReport,\ write_file from frappe.utils.file_manager import check_max_file_size, get_content_hash from PIL import Image, ImageOps from .file import remove_directory) and context including class names, function names, or small code snippets from other files: # Path: jasper_erpnext_report/jasper_reports/compile_reports.py # def jasper_compile(jrxml, destFileName): # try: # compiler = jr.ReportCompiler() # compiler.compile(jrxml,destFileName) # except Exception as e: # import jasper_erpnext_report as jer # if jer.pyjnius == False: # frappe.throw(_("Please install pyjnius python module.")) # return # frappe.throw(_("Error while compiling report %s, error is: %s." % (jrxml, e))) # # Path: jasper_erpnext_report/utils/file.py # def get_image_name(iname): # def get_images_path(compiled_path): # def get_jasper_path(for_all_sites = False): # def write_StringIO_to_file(file_path, output): # def write_file(content, file_path, modes="w+"): # def check_extension(fname): # def get_extension(fname): # def remove_from_doc(dt, dn, field, where_field = "name"): # def delete_from_doc(dt, dn, field, value, where_field): # def delete_from_FileData(dt, dn, file_url): # def remove_directory(path, ignore_errors=True): # def remove_compiled_report(root_path): # def get_file(path, modes="r", raise_not_found=False): # def read_file(path, modes="r", raise_not_found=False): # def get_html_reports_path(report_name, where="reports", hash=None, localsite=None): # def get_html_reports_images_path(report_path, where="images"): . Output only the next line.
jrxml_path = get_jrxml_path(self.jasper_path, self.dn)
Here is a snippet: <|code_start|> self.dn = frappe.form_dict.docname self.autofilename = None self.ext = check_extension(self.fname) self.jasper_all_sites_report = frappe.db.get_value(self.dt, self.dn, 'jasper_all_sites_report') self.jasper_path = get_jasper_path(self.jasper_all_sites_report) self.compiled_path = get_compiled_path(self.jasper_path, self.dn) self.path_join = os.path.join self.scriptlet = None self.save_path = None self.subreport = False def insert_report_doc(self, dn=None): file_data = {} file_size = check_max_file_size(self.content) content_hash = get_content_hash(self.content) file_name = os.path.basename(self.rel_path) image = False file_url = os.sep + self.rel_path.replace('\\','/') try: Image.open(StringIO.StringIO(self.content)).verify() file_url = os.sep + "files" + os.sep + self.rel_path.replace('\\','/') image = True except Exception: pass file_data.update({ <|code_end|> . Write the next line using the current file imports: import frappe import os import StringIO import shutil from frappe import _ from io import BytesIO from jasper_erpnext_report.jasper_reports.compile_reports import jasper_compile from jasper_erpnext_report.utils.file import check_extension, get_jasper_path, get_extension, JasperXmlReport,\ write_file from frappe.utils.file_manager import check_max_file_size, get_content_hash from PIL import Image, ImageOps from .file import remove_directory and context from other files: # Path: jasper_erpnext_report/jasper_reports/compile_reports.py # def jasper_compile(jrxml, destFileName): # try: # compiler = jr.ReportCompiler() # compiler.compile(jrxml,destFileName) # except Exception as e: # import jasper_erpnext_report as jer # if jer.pyjnius == False: # frappe.throw(_("Please install pyjnius python module.")) # return # frappe.throw(_("Error while compiling report %s, error is: %s." % (jrxml, e))) # # Path: jasper_erpnext_report/utils/file.py # def get_image_name(iname): # def get_images_path(compiled_path): # def get_jasper_path(for_all_sites = False): # def write_StringIO_to_file(file_path, output): # def write_file(content, file_path, modes="w+"): # def check_extension(fname): # def get_extension(fname): # def remove_from_doc(dt, dn, field, where_field = "name"): # def delete_from_doc(dt, dn, field, value, where_field): # def delete_from_FileData(dt, dn, file_url): # def remove_directory(path, ignore_errors=True): # def remove_compiled_report(root_path): # def get_file(path, modes="r", raise_not_found=False): # def read_file(path, modes="r", raise_not_found=False): # def get_html_reports_path(report_name, where="reports", hash=None, localsite=None): # def get_html_reports_images_path(report_path, where="images"): , which may include functions, classes, or code. Output only the next line.
"doctype": "File",
Given the code snippet: <|code_start|> try: f.insert(ignore_permissions=True) if self.ext == "jrxml": self.make_content_jrxml(f.name) except frappe.DuplicateEntryError: return frappe.get_doc("File", f.duplicate_entry) return f def process(self, dn=None): if self.ext != "jrxml": self.process_childs() else: self.process_jrxmls() self.rel_path = os.path.relpath(self.file_path, self.jasper_path) f = self.insert_report_doc(dn=dn) try: self.save() if self.ext == "jrxml": self.compile() except Exception, e: frappe.delete_doc("File", f.name) print "Remove this doc: doctype {} docname {} error: {}".format(f.doctype, f.name, e) frappe.throw(_("Error in report doctype %s docname %s, error is: %s." % (f.doctype, f.name, e))) <|code_end|> , generate the next line using the imports in this file: import frappe import os import StringIO import shutil from frappe import _ from io import BytesIO from jasper_erpnext_report.jasper_reports.compile_reports import jasper_compile from jasper_erpnext_report.utils.file import check_extension, get_jasper_path, get_extension, JasperXmlReport,\ write_file from frappe.utils.file_manager import check_max_file_size, get_content_hash from PIL import Image, ImageOps from .file import remove_directory and context (functions, classes, or occasionally code) from other files: # Path: jasper_erpnext_report/jasper_reports/compile_reports.py # def jasper_compile(jrxml, destFileName): # try: # compiler = jr.ReportCompiler() # compiler.compile(jrxml,destFileName) # except Exception as e: # import jasper_erpnext_report as jer # if jer.pyjnius == False: # frappe.throw(_("Please install pyjnius python module.")) # return # frappe.throw(_("Error while compiling report %s, error is: %s." % (jrxml, e))) # # Path: jasper_erpnext_report/utils/file.py # def get_image_name(iname): # def get_images_path(compiled_path): # def get_jasper_path(for_all_sites = False): # def write_StringIO_to_file(file_path, output): # def write_file(content, file_path, modes="w+"): # def check_extension(fname): # def get_extension(fname): # def remove_from_doc(dt, dn, field, where_field = "name"): # def delete_from_doc(dt, dn, field, value, where_field): # def delete_from_FileData(dt, dn, file_url): # def remove_directory(path, ignore_errors=True): # def remove_compiled_report(root_path): # def get_file(path, modes="r", raise_not_found=False): # def read_file(path, modes="r", raise_not_found=False): # def get_html_reports_path(report_name, where="reports", hash=None, localsite=None): # def get_html_reports_images_path(report_path, where="images"): . Output only the next line.
return f
Based on the snippet: <|code_start|> frappe.msgprint(_("The report %s is not a subreport of %s." % (self.fname[:-6], docs[0].file_name[:-6])),raise_exception=True) elif not (sub[:-7] == self.fname[:-6]): frappe.msgprint(_("The report %s is not a subreport of %s." % (self.fname[:-6], docs[0].file_name[:-6])),raise_exception=True) if not xmldoc.subreports: frappe.msgprint(_("The report %s is not a subreport of %s." % (self.fname[:-6], docs[0].file_name[:-6])),raise_exception=True) #self.subreport = True #self.file_path = self.path_join(jrxml_path, docs[0].file_name) def make_content_jrxml(self, name): #import re xmldoc = JasperXmlReport(BytesIO(self.content)) xmldoc.change_subreport_expression_path() self.scriptlet = xmldoc.get_attrib("scriptletClass") #TODO if not self.scriptlet: pass xmldoc.change_path_images() xmldoc.setProperty("parent", self.parent) xmldoc.setProperty("jasperId", name) self.content = xmldoc.toString() #self.content = re.sub("<queryString>(.*?)</queryString>", "<queryString>%s</queryString>" % self.queryString, self.content, count=1, flags=re.S|re.M) def save(self): self.save_path = write_file(self.content, self.file_path) def compile(self): <|code_end|> , predict the immediate next line with the help of imports: import frappe import os import StringIO import shutil from frappe import _ from io import BytesIO from jasper_erpnext_report.jasper_reports.compile_reports import jasper_compile from jasper_erpnext_report.utils.file import check_extension, get_jasper_path, get_extension, JasperXmlReport,\ write_file from frappe.utils.file_manager import check_max_file_size, get_content_hash from PIL import Image, ImageOps from .file import remove_directory and context (classes, functions, sometimes code) from other files: # Path: jasper_erpnext_report/jasper_reports/compile_reports.py # def jasper_compile(jrxml, destFileName): # try: # compiler = jr.ReportCompiler() # compiler.compile(jrxml,destFileName) # except Exception as e: # import jasper_erpnext_report as jer # if jer.pyjnius == False: # frappe.throw(_("Please install pyjnius python module.")) # return # frappe.throw(_("Error while compiling report %s, error is: %s." % (jrxml, e))) # # Path: jasper_erpnext_report/utils/file.py # def get_image_name(iname): # def get_images_path(compiled_path): # def get_jasper_path(for_all_sites = False): # def write_StringIO_to_file(file_path, output): # def write_file(content, file_path, modes="w+"): # def check_extension(fname): # def get_extension(fname): # def remove_from_doc(dt, dn, field, where_field = "name"): # def delete_from_doc(dt, dn, field, value, where_field): # def delete_from_FileData(dt, dn, file_url): # def remove_directory(path, ignore_errors=True): # def remove_compiled_report(root_path): # def get_file(path, modes="r", raise_not_found=False): # def read_file(path, modes="r", raise_not_found=False): # def get_html_reports_path(report_name, where="reports", hash=None, localsite=None): # def get_html_reports_images_path(report_path, where="images"): . Output only the next line.
jasper_compile_jrxml(self.fname, self.file_path, self.compiled_path)
Predict the next line after this snippet: <|code_start|> class WriteFileJrxml(object): def __init__(self, dt, fname, content, parent): self.file_path = None self.dt = dt self.fname = fname self.content = content self.parent = parent self.dn = frappe.form_dict.docname self.autofilename = None self.ext = check_extension(self.fname) self.jasper_all_sites_report = frappe.db.get_value(self.dt, self.dn, 'jasper_all_sites_report') self.jasper_path = get_jasper_path(self.jasper_all_sites_report) self.compiled_path = get_compiled_path(self.jasper_path, self.dn) self.path_join = os.path.join self.scriptlet = None self.save_path = None self.subreport = False def insert_report_doc(self, dn=None): file_data = {} file_size = check_max_file_size(self.content) content_hash = get_content_hash(self.content) file_name = os.path.basename(self.rel_path) image = False <|code_end|> using the current file's imports: import frappe import os import StringIO import shutil from frappe import _ from io import BytesIO from jasper_erpnext_report.jasper_reports.compile_reports import jasper_compile from jasper_erpnext_report.utils.file import check_extension, get_jasper_path, get_extension, JasperXmlReport,\ write_file from frappe.utils.file_manager import check_max_file_size, get_content_hash from PIL import Image, ImageOps from .file import remove_directory and any relevant context from other files: # Path: jasper_erpnext_report/jasper_reports/compile_reports.py # def jasper_compile(jrxml, destFileName): # try: # compiler = jr.ReportCompiler() # compiler.compile(jrxml,destFileName) # except Exception as e: # import jasper_erpnext_report as jer # if jer.pyjnius == False: # frappe.throw(_("Please install pyjnius python module.")) # return # frappe.throw(_("Error while compiling report %s, error is: %s." % (jrxml, e))) # # Path: jasper_erpnext_report/utils/file.py # def get_image_name(iname): # def get_images_path(compiled_path): # def get_jasper_path(for_all_sites = False): # def write_StringIO_to_file(file_path, output): # def write_file(content, file_path, modes="w+"): # def check_extension(fname): # def get_extension(fname): # def remove_from_doc(dt, dn, field, where_field = "name"): # def delete_from_doc(dt, dn, field, value, where_field): # def delete_from_FileData(dt, dn, file_url): # def remove_directory(path, ignore_errors=True): # def remove_compiled_report(root_path): # def get_file(path, modes="r", raise_not_found=False): # def read_file(path, modes="r", raise_not_found=False): # def get_html_reports_path(report_name, where="reports", hash=None, localsite=None): # def get_html_reports_images_path(report_path, where="images"): . Output only the next line.
file_url = os.sep + self.rel_path.replace('\\','/')
Given snippet: <|code_start|> frappe.msgprint(_("The report %s is not a subreport of %s." % (self.fname[:-6], docs[0].file_name[:-6])),raise_exception=True) if not xmldoc.subreports: frappe.msgprint(_("The report %s is not a subreport of %s." % (self.fname[:-6], docs[0].file_name[:-6])),raise_exception=True) #self.subreport = True #self.file_path = self.path_join(jrxml_path, docs[0].file_name) def make_content_jrxml(self, name): #import re xmldoc = JasperXmlReport(BytesIO(self.content)) xmldoc.change_subreport_expression_path() self.scriptlet = xmldoc.get_attrib("scriptletClass") #TODO if not self.scriptlet: pass xmldoc.change_path_images() xmldoc.setProperty("parent", self.parent) xmldoc.setProperty("jasperId", name) self.content = xmldoc.toString() #self.content = re.sub("<queryString>(.*?)</queryString>", "<queryString>%s</queryString>" % self.queryString, self.content, count=1, flags=re.S|re.M) def save(self): self.save_path = write_file(self.content, self.file_path) def compile(self): jasper_compile_jrxml(self.fname, self.file_path, self.compiled_path) <|code_end|> , continue by predicting the next line. Consider current file imports: import frappe import os import StringIO import shutil from frappe import _ from io import BytesIO from jasper_erpnext_report.jasper_reports.compile_reports import jasper_compile from jasper_erpnext_report.utils.file import check_extension, get_jasper_path, get_extension, JasperXmlReport,\ write_file from frappe.utils.file_manager import check_max_file_size, get_content_hash from PIL import Image, ImageOps from .file import remove_directory and context: # Path: jasper_erpnext_report/jasper_reports/compile_reports.py # def jasper_compile(jrxml, destFileName): # try: # compiler = jr.ReportCompiler() # compiler.compile(jrxml,destFileName) # except Exception as e: # import jasper_erpnext_report as jer # if jer.pyjnius == False: # frappe.throw(_("Please install pyjnius python module.")) # return # frappe.throw(_("Error while compiling report %s, error is: %s." % (jrxml, e))) # # Path: jasper_erpnext_report/utils/file.py # def get_image_name(iname): # def get_images_path(compiled_path): # def get_jasper_path(for_all_sites = False): # def write_StringIO_to_file(file_path, output): # def write_file(content, file_path, modes="w+"): # def check_extension(fname): # def get_extension(fname): # def remove_from_doc(dt, dn, field, where_field = "name"): # def delete_from_doc(dt, dn, field, value, where_field): # def delete_from_FileData(dt, dn, file_url): # def remove_directory(path, ignore_errors=True): # def remove_compiled_report(root_path): # def get_file(path, modes="r", raise_not_found=False): # def read_file(path, modes="r", raise_not_found=False): # def get_html_reports_path(report_name, where="reports", hash=None, localsite=None): # def get_html_reports_images_path(report_path, where="images"): which might include code, classes, or functions. Output only the next line.
def make_thumbnail(self, file_url, doc, dn):
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) 2013, Luis Fernandes and contributors # For license information, please see license.txt from __future__ import unicode_literals class JasperEmailReport(Document): def validate(self): if not self.jasper_email_report_name: <|code_end|> , predict the next line using imports from the current file: import frappe import os from frappe import _ from frappe.model.document import Document from jasper_erpnext_report.utils.file import remove_directory and context including class names, function names, and sometimes code from other files: # Path: jasper_erpnext_report/utils/file.py # def remove_directory(path, ignore_errors=True): # import shutil # shutil.rmtree(path, ignore_errors) . Output only the next line.
raise frappe.PermissionError(_("You are not allowed to add this document."))
Predict the next line for this snippet: <|code_start|> #call from bench frappe --python session or #to be called from terminal: bench frappe --execute jasper_erpnext_report.utils.scheduler.list_all_memcached_keys_v4 def list_all_memcached_keys_v4(value=None): keys = [] memc = MemcachedStats() if value: for m in memc.keys(): if value in m: print m keys.append(m) else: keys = memc.keys() print (keys) return keys def list_all_redis_keys(key): redis = frappe.cache() return redis.get_keys(key) #to be called from terminal: bench frappe --execute jasper_erpnext_report.utils.scheduler.clear_all_jasper_cache_v4 to force clear cache def clear_all_jasper_from_cache_v4(key="jasper"): #use memcache_stats for delete any cache that remains memc = MemcachedStats() for m in memc.keys(): if key in m: value = m.split(":", 1) <|code_end|> with the help of current file imports: import frappe import ast import frappe.utils from frappe import _ from jasper_erpnext_report.utils.utils import jaspersession_get_value,get_expiry_in_seconds,\ get_jasper_data, get_jasper_session_expiry_seconds, getFrappeVersion from jasper_erpnext_report.utils.file import remove_directory from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from jasper_erpnext_report.utils.jasper_email import get_email_pdf_path and context from other files: # Path: jasper_erpnext_report/utils/utils.py # def jasper_report_names_from_db(origin="both", filters_report=None, filters_param=None, filters_permrole=None): # def jasper_print_formats(doc): # def validate_print_permission(doc): # def import_all_jasper_remote_reports(docs, force=True): # def check_queryString_with_param(query, param): # def check_queryString_param(query, param): # def get_default_param_value(param, error=True): # def call_hook_for_param(doc, method, *args): # def call_hook_for_param_with_default(doc, hook_name, *args): # def testHookScriptlet(JasperScriptlet, ids, data, cols, cur_doctype, cur_docname): # def __init__(self, JasperScriplet, ids=None, data=None, cols=None, doctype=None): # def test(self, args): # def make_jasper_hooks_path(): # def get_hook_module(hook_name, report_name=None): # def jasper_run_method(hook_name, *args, **kargs): # def jasper_run_method_once_with_default(hook_name, docname, default): # def check_jasper_perm(perms, ptypes=("read",), user=None): # def check_perm(perms, user_roles, ptype): # def check_frappe_permission(doctype, docname, ptypes=("read", )): # def jasper_users_login(user): # def pipInstall(package=None): # def get_Frappe_Version(version=None): # def getFrappeVersion(): # def add_to_time_str(date=None, hours=0, days=0, weeks=0): # def __init__(self, site, user): # def __enter__(self): # def __exit__(self, type, value, trace): # class MyJasperCustomScripletDefault(JasperCustomScripletDefault): # class FrappeContext: # # Path: jasper_erpnext_report/utils/file.py # def remove_directory(path, ignore_errors=True): # import shutil # shutil.rmtree(path, ignore_errors) , which may contain function names, class names, or code. Output only the next line.
frappe.cache().delete_value(value[1])
Based on the snippet: <|code_start|> keys = redis.get_keys("jasper:user") for key in keys: if check_if_expire(key): redis.delete_value(key) removed += 1 print _("Was removed {0} user(s) from redis cache".format(removed)) return removed #to be called from terminal: bench frappe --execute jasper_erpnext_report.utils.scheduler.clear_all_jasper_user_cache_v4 to force clear cache def clear_all_jasper_user_cache_v4(force=True): removed = 0 #use memcache_stats for delete any cache that remains memc = MemcachedStats() for m in memc.keys(): if "jasper:user" in m: if force: #remove site from key value = m.split(":", 1) frappe.cache().delete_value(value[1]) removed += 1 else: #remove jasper from key value = m.split(":", 1) v = value[1].split(":", 1) deleted = check_if_expire(v[1]) if deleted: frappe.cache().delete_value(value[1]) removed += 1 <|code_end|> , predict the immediate next line with the help of imports: import frappe import ast import frappe.utils from frappe import _ from jasper_erpnext_report.utils.utils import jaspersession_get_value,get_expiry_in_seconds,\ get_jasper_data, get_jasper_session_expiry_seconds, getFrappeVersion from jasper_erpnext_report.utils.file import remove_directory from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from jasper_erpnext_report.utils.jasper_email import get_email_pdf_path and context (classes, functions, sometimes code) from other files: # Path: jasper_erpnext_report/utils/utils.py # def jasper_report_names_from_db(origin="both", filters_report=None, filters_param=None, filters_permrole=None): # def jasper_print_formats(doc): # def validate_print_permission(doc): # def import_all_jasper_remote_reports(docs, force=True): # def check_queryString_with_param(query, param): # def check_queryString_param(query, param): # def get_default_param_value(param, error=True): # def call_hook_for_param(doc, method, *args): # def call_hook_for_param_with_default(doc, hook_name, *args): # def testHookScriptlet(JasperScriptlet, ids, data, cols, cur_doctype, cur_docname): # def __init__(self, JasperScriplet, ids=None, data=None, cols=None, doctype=None): # def test(self, args): # def make_jasper_hooks_path(): # def get_hook_module(hook_name, report_name=None): # def jasper_run_method(hook_name, *args, **kargs): # def jasper_run_method_once_with_default(hook_name, docname, default): # def check_jasper_perm(perms, ptypes=("read",), user=None): # def check_perm(perms, user_roles, ptype): # def check_frappe_permission(doctype, docname, ptypes=("read", )): # def jasper_users_login(user): # def pipInstall(package=None): # def get_Frappe_Version(version=None): # def getFrappeVersion(): # def add_to_time_str(date=None, hours=0, days=0, weeks=0): # def __init__(self, site, user): # def __enter__(self): # def __exit__(self, type, value, trace): # class MyJasperCustomScripletDefault(JasperCustomScripletDefault): # class FrappeContext: # # Path: jasper_erpnext_report/utils/file.py # def remove_directory(path, ignore_errors=True): # import shutil # shutil.rmtree(path, ignore_errors) . Output only the next line.
if removed == 0:
Using the snippet: <|code_start|>def clear_all_jasper_user_redis_cache(force=True): removed = 0 if force: clear_all_jasper_from_redis_cache("jasper:user") print _("Was removed by force jasper:user* pattern from redis cache") return 1 else: redis = frappe.cache() keys = redis.get_keys("jasper:user") for key in keys: if check_if_expire(key): redis.delete_value(key) removed += 1 print _("Was removed {0} user(s) from redis cache".format(removed)) return removed #to be called from terminal: bench frappe --execute jasper_erpnext_report.utils.scheduler.clear_all_jasper_user_cache_v4 to force clear cache def clear_all_jasper_user_cache_v4(force=True): removed = 0 #use memcache_stats for delete any cache that remains memc = MemcachedStats() for m in memc.keys(): if "jasper:user" in m: if force: #remove site from key value = m.split(":", 1) frappe.cache().delete_value(value[1]) removed += 1 <|code_end|> , determine the next line of code. You have imports: import frappe import ast import frappe.utils from frappe import _ from jasper_erpnext_report.utils.utils import jaspersession_get_value,get_expiry_in_seconds,\ get_jasper_data, get_jasper_session_expiry_seconds, getFrappeVersion from jasper_erpnext_report.utils.file import remove_directory from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from jasper_erpnext_report.utils.jasper_email import get_email_pdf_path and context (class names, function names, or code) available: # Path: jasper_erpnext_report/utils/utils.py # def jasper_report_names_from_db(origin="both", filters_report=None, filters_param=None, filters_permrole=None): # def jasper_print_formats(doc): # def validate_print_permission(doc): # def import_all_jasper_remote_reports(docs, force=True): # def check_queryString_with_param(query, param): # def check_queryString_param(query, param): # def get_default_param_value(param, error=True): # def call_hook_for_param(doc, method, *args): # def call_hook_for_param_with_default(doc, hook_name, *args): # def testHookScriptlet(JasperScriptlet, ids, data, cols, cur_doctype, cur_docname): # def __init__(self, JasperScriplet, ids=None, data=None, cols=None, doctype=None): # def test(self, args): # def make_jasper_hooks_path(): # def get_hook_module(hook_name, report_name=None): # def jasper_run_method(hook_name, *args, **kargs): # def jasper_run_method_once_with_default(hook_name, docname, default): # def check_jasper_perm(perms, ptypes=("read",), user=None): # def check_perm(perms, user_roles, ptype): # def check_frappe_permission(doctype, docname, ptypes=("read", )): # def jasper_users_login(user): # def pipInstall(package=None): # def get_Frappe_Version(version=None): # def getFrappeVersion(): # def add_to_time_str(date=None, hours=0, days=0, weeks=0): # def __init__(self, site, user): # def __enter__(self): # def __exit__(self, type, value, trace): # class MyJasperCustomScripletDefault(JasperCustomScripletDefault): # class FrappeContext: # # Path: jasper_erpnext_report/utils/file.py # def remove_directory(path, ignore_errors=True): # import shutil # shutil.rmtree(path, ignore_errors) . Output only the next line.
else:
Using the snippet: <|code_start|>__author__ = 'luissaguas' #call from bench frappe --python session or #to be called from terminal: bench frappe --execute jasper_erpnext_report.utils.scheduler.list_all_memcached_keys_v4 def list_all_memcached_keys_v4(value=None): keys = [] memc = MemcachedStats() if value: for m in memc.keys(): if value in m: print m keys.append(m) else: keys = memc.keys() <|code_end|> , determine the next line of code. You have imports: import frappe import ast import frappe.utils from frappe import _ from jasper_erpnext_report.utils.utils import jaspersession_get_value,get_expiry_in_seconds,\ get_jasper_data, get_jasper_session_expiry_seconds, getFrappeVersion from jasper_erpnext_report.utils.file import remove_directory from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from jasper_erpnext_report.utils.jasper_email import get_email_pdf_path and context (class names, function names, or code) available: # Path: jasper_erpnext_report/utils/utils.py # def jasper_report_names_from_db(origin="both", filters_report=None, filters_param=None, filters_permrole=None): # def jasper_print_formats(doc): # def validate_print_permission(doc): # def import_all_jasper_remote_reports(docs, force=True): # def check_queryString_with_param(query, param): # def check_queryString_param(query, param): # def get_default_param_value(param, error=True): # def call_hook_for_param(doc, method, *args): # def call_hook_for_param_with_default(doc, hook_name, *args): # def testHookScriptlet(JasperScriptlet, ids, data, cols, cur_doctype, cur_docname): # def __init__(self, JasperScriplet, ids=None, data=None, cols=None, doctype=None): # def test(self, args): # def make_jasper_hooks_path(): # def get_hook_module(hook_name, report_name=None): # def jasper_run_method(hook_name, *args, **kargs): # def jasper_run_method_once_with_default(hook_name, docname, default): # def check_jasper_perm(perms, ptypes=("read",), user=None): # def check_perm(perms, user_roles, ptype): # def check_frappe_permission(doctype, docname, ptypes=("read", )): # def jasper_users_login(user): # def pipInstall(package=None): # def get_Frappe_Version(version=None): # def getFrappeVersion(): # def add_to_time_str(date=None, hours=0, days=0, weeks=0): # def __init__(self, site, user): # def __enter__(self): # def __exit__(self, type, value, trace): # class MyJasperCustomScripletDefault(JasperCustomScripletDefault): # class FrappeContext: # # Path: jasper_erpnext_report/utils/file.py # def remove_directory(path, ignore_errors=True): # import shutil # shutil.rmtree(path, ignore_errors) . Output only the next line.
print (keys)
Using the snippet: <|code_start|> if check_if_expire("report_list_doctype"): frappe.cache().delete_value("jasper:report_list_doctype") removed += 1 return removed #remove the files in compiled directory #from command line remove and don't check expire time #from scheduler remove only if past expire time def clear_all_jasper_reports(force=True): deleted = force compiled_removed = 0 emailed_removed = 0 #to every intern_reqid is one local_report_ or from server?(to check) tabReqids = frappe.db.sql("select * from tabJasperReqids where reqid like 'intern_reqid_%'", as_dict=True) for m in tabReqids: d = m.get('data') req = ast.literal_eval(d) reqId = req.get("reqids")[0][0] data = jaspersession_get_value(reqId) if not force: deleted = _f(data) if deleted: if "local_report_" not in reqId: continue <|code_end|> , determine the next line of code. You have imports: import frappe import ast import frappe.utils from frappe import _ from jasper_erpnext_report.utils.utils import jaspersession_get_value,get_expiry_in_seconds,\ get_jasper_data, get_jasper_session_expiry_seconds, getFrappeVersion from jasper_erpnext_report.utils.file import remove_directory from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from jasper_erpnext_report.utils.jasper_email import get_email_pdf_path and context (class names, function names, or code) available: # Path: jasper_erpnext_report/utils/utils.py # def jasper_report_names_from_db(origin="both", filters_report=None, filters_param=None, filters_permrole=None): # def jasper_print_formats(doc): # def validate_print_permission(doc): # def import_all_jasper_remote_reports(docs, force=True): # def check_queryString_with_param(query, param): # def check_queryString_param(query, param): # def get_default_param_value(param, error=True): # def call_hook_for_param(doc, method, *args): # def call_hook_for_param_with_default(doc, hook_name, *args): # def testHookScriptlet(JasperScriptlet, ids, data, cols, cur_doctype, cur_docname): # def __init__(self, JasperScriplet, ids=None, data=None, cols=None, doctype=None): # def test(self, args): # def make_jasper_hooks_path(): # def get_hook_module(hook_name, report_name=None): # def jasper_run_method(hook_name, *args, **kargs): # def jasper_run_method_once_with_default(hook_name, docname, default): # def check_jasper_perm(perms, ptypes=("read",), user=None): # def check_perm(perms, user_roles, ptype): # def check_frappe_permission(doctype, docname, ptypes=("read", )): # def jasper_users_login(user): # def pipInstall(package=None): # def get_Frappe_Version(version=None): # def getFrappeVersion(): # def add_to_time_str(date=None, hours=0, days=0, weeks=0): # def __init__(self, site, user): # def __enter__(self): # def __exit__(self, type, value, trace): # class MyJasperCustomScripletDefault(JasperCustomScripletDefault): # class FrappeContext: # # Path: jasper_erpnext_report/utils/file.py # def remove_directory(path, ignore_errors=True): # import shutil # shutil.rmtree(path, ignore_errors) . Output only the next line.
intern_reqid = m.get("reqid")
Next line prediction: <|code_start|> for key in keys: if check_if_expire(key): redis.delete_value(key) removed += 1 print _("Was removed {0} user(s) from redis cache".format(removed)) return removed #to be called from terminal: bench frappe --execute jasper_erpnext_report.utils.scheduler.clear_all_jasper_user_cache_v4 to force clear cache def clear_all_jasper_user_cache_v4(force=True): removed = 0 #use memcache_stats for delete any cache that remains memc = MemcachedStats() for m in memc.keys(): if "jasper:user" in m: if force: #remove site from key value = m.split(":", 1) frappe.cache().delete_value(value[1]) removed += 1 else: #remove jasper from key value = m.split(":", 1) v = value[1].split(":", 1) deleted = check_if_expire(v[1]) if deleted: frappe.cache().delete_value(value[1]) removed += 1 if removed == 0: <|code_end|> . Use current file imports: (import frappe import ast import frappe.utils from frappe import _ from jasper_erpnext_report.utils.utils import jaspersession_get_value,get_expiry_in_seconds,\ get_jasper_data, get_jasper_session_expiry_seconds, getFrappeVersion from jasper_erpnext_report.utils.file import remove_directory from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from memcache_stats import MemcachedStats from jasper_erpnext_report.utils.jasper_email import get_email_pdf_path) and context including class names, function names, or small code snippets from other files: # Path: jasper_erpnext_report/utils/utils.py # def jasper_report_names_from_db(origin="both", filters_report=None, filters_param=None, filters_permrole=None): # def jasper_print_formats(doc): # def validate_print_permission(doc): # def import_all_jasper_remote_reports(docs, force=True): # def check_queryString_with_param(query, param): # def check_queryString_param(query, param): # def get_default_param_value(param, error=True): # def call_hook_for_param(doc, method, *args): # def call_hook_for_param_with_default(doc, hook_name, *args): # def testHookScriptlet(JasperScriptlet, ids, data, cols, cur_doctype, cur_docname): # def __init__(self, JasperScriplet, ids=None, data=None, cols=None, doctype=None): # def test(self, args): # def make_jasper_hooks_path(): # def get_hook_module(hook_name, report_name=None): # def jasper_run_method(hook_name, *args, **kargs): # def jasper_run_method_once_with_default(hook_name, docname, default): # def check_jasper_perm(perms, ptypes=("read",), user=None): # def check_perm(perms, user_roles, ptype): # def check_frappe_permission(doctype, docname, ptypes=("read", )): # def jasper_users_login(user): # def pipInstall(package=None): # def get_Frappe_Version(version=None): # def getFrappeVersion(): # def add_to_time_str(date=None, hours=0, days=0, weeks=0): # def __init__(self, site, user): # def __enter__(self): # def __exit__(self, type, value, trace): # class MyJasperCustomScripletDefault(JasperCustomScripletDefault): # class FrappeContext: # # Path: jasper_erpnext_report/utils/file.py # def remove_directory(path, ignore_errors=True): # import shutil # shutil.rmtree(path, ignore_errors) . Output only the next line.
print _("No user cache was removed.")
Given the following code snippet before the placeholder: <|code_start|>class JasperBase(object): def __init__(self, doc=None, origin=None): doc = doc or {} if isinstance(doc, Document): self.doc = frappe._dict(doc.as_dict()) else: self.doc = frappe._dict(doc) self.user = frappe.local.session["user"] self.sid = frappe.local.session["sid"] self.frappe_task = None self.reset_data_session() self.report_html_path = None self.html_hash = None self.report_origin = origin self.resume() def reset_data_session(self): self.data = frappe._dict({'data': frappe._dict({})}) def in_jasper_session(self): return False def use_server(self): try: doc_jasper_server = self.doc.use_jasper_server.lower() return doc_jasper_server == "jasperserver only" or doc_jasper_server == "both" except: return False def use_local(self): <|code_end|> , predict the next line using imports from the current file: from frappe.model.document import Document from frappe import _ from io import BytesIO from jasper_erpnext_report.utils.file import get_file, get_html_reports_images_path from jasper_erpnext_report.utils.file import JasperXmlReport, get_html_reports_path from distutils.dir_util import copy_tree from jasper_erpnext_report.utils.utils import getFrappeVersion import frappe import uuid, os import jasper_erpnext_report.utils.utils as utils import re import hashlib import frappe.utils.email_lib import frappe.email and context including class names, function names, and sometimes code from other files: # Path: jasper_erpnext_report/utils/file.py # def get_file(path, modes="r", raise_not_found=False): # if modes != "r": # content = read_file(path, modes=modes, raise_not_found=raise_not_found) # else: # content = frappe.read_file(path, raise_not_found=raise_not_found) # # return content # # def get_html_reports_images_path(report_path, where="images"): # path = os.path.join(report_path, where) # frappe.create_folder(path) # return path # # Path: jasper_erpnext_report/utils/file.py # def get_image_name(iname): # def get_images_path(compiled_path): # def get_jasper_path(for_all_sites = False): # def write_StringIO_to_file(file_path, output): # def write_file(content, file_path, modes="w+"): # def check_extension(fname): # def get_extension(fname): # def remove_from_doc(dt, dn, field, where_field = "name"): # def delete_from_doc(dt, dn, field, value, where_field): # def delete_from_FileData(dt, dn, file_url): # def remove_directory(path, ignore_errors=True): # def remove_compiled_report(root_path): # def get_file(path, modes="r", raise_not_found=False): # def read_file(path, modes="r", raise_not_found=False): # def get_html_reports_path(report_name, where="reports", hash=None, localsite=None): # def get_html_reports_images_path(report_path, where="images"): . Output only the next line.
doc_jasper_server = self.doc.use_jasper_server.lower()