Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|> def write(self, row, cells=None):
"""Independend write to cell method"""
raise NotImplementedError
def read(self, row, cells=None):
"""Independend read from cell method"""
raise NotImplementedError
def create(self, path):
"""Create file for given path"""
raise NotImplementedError
def open(self, path):
"""Open file for given path"""
raise NotImplementedError
def save(self):
"""Save result file"""
raise NotImplementedError
def create_export_path(self):
# TODO: refactor filepath
filename = '{}{}'.format(
self.settings.filename or str(self.report.id), self.file_format)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import traceback
from django.utils.six.moves import range
from django.utils import timezone
from django.db import transaction, Error
from django.core.exceptions import ValidationError
from .signals import export_started, export_completed, \
import_started, import_completed, error_raised
from .exceptions import ErrorChoicesMixin
from ..settings import SETTINGS
and context (classes, functions, sometimes code) from other files:
# Path: mtr/sync/lib/signals.py
#
# Path: mtr/sync/lib/exceptions.py
# class ErrorChoicesMixin(object):
# IMPORT_DATA = 0
# UNDEFINED = 1
#
# STEP_CHOICES = (
# (IMPORT_DATA, _('import data')),
# (UNDEFINED, _('unexpected error'))
# )
#
# Path: mtr/sync/settings.py
# SETTINGS = getattr_with_prefix('SYNC', 'SETTINGS', {
# 'path': get_buffer_file_path,
# 'default_processor': 'XlsxProcessor',
# 'actions': ['mtr.sync.lib.actions'],
# 'converters': ['mtr.sync.lib.converters'],
# 'processors': [
# 'mtr.sync.lib.processors.xlsx',
# 'mtr.sync.lib.processors.xls',
# 'mtr.sync.lib.processors.ods',
# 'mtr.sync.lib.processors.csv',
# ],
# 'broker': 'rq',
# 'include': {
# 'api': False,
# 'admin': True,
# }
# })
. Output only the next line. | path = SETTINGS['path'](self.report, '', absolute=True) |
Given the following code snippet before the placeholder: <|code_start|>
class MtrSyncConfig(AppConfig):
name = 'mtr.sync'
label = 'mtr_sync'
<|code_end|>
, predict the next line using imports from the current file:
from django.apps import AppConfig
from .translation import gettext_lazy as _
and context including class names, function names, and sometimes code from other files:
# Path: mtr/sync/translation.py
. Output only the next line. | verbose_name = _('Data sync') |
Given the following code snippet before the placeholder: <|code_start|>
class ErrorChoicesMixin(object):
IMPORT_DATA = 0
UNDEFINED = 1
STEP_CHOICES = (
<|code_end|>
, predict the next line using imports from the current file:
from ..translation import gettext_lazy as _
and context including class names, function names, and sometimes code from other files:
# Path: mtr/sync/translation.py
. Output only the next line. | (IMPORT_DATA, _('import data')), |
Here is a snippet: <|code_start|>
class MockInstance(object):
action = 1
class SettingsTest(TestCase):
def test_default_filepath_name(self):
new_settings = {
'MEDIA_ROOT': '/some/path/'
}
instance = MockInstance()
with self.settings(**new_settings):
self.assertEqual(
<|code_end|>
. Write the next line using the current file imports:
from django.test import TestCase
from mtr.sync.settings import SETTINGS
and context from other files:
# Path: mtr/sync/settings.py
# SETTINGS = getattr_with_prefix('SYNC', 'SETTINGS', {
# 'path': get_buffer_file_path,
# 'default_processor': 'XlsxProcessor',
# 'actions': ['mtr.sync.lib.actions'],
# 'converters': ['mtr.sync.lib.converters'],
# 'processors': [
# 'mtr.sync.lib.processors.xlsx',
# 'mtr.sync.lib.processors.xls',
# 'mtr.sync.lib.processors.ods',
# 'mtr.sync.lib.processors.csv',
# ],
# 'broker': 'rq',
# 'include': {
# 'api': False,
# 'admin': True,
# }
# })
, which may include functions, classes, or code. Output only the next line. | SETTINGS['path'](instance, 'filename.xls'), |
Using the snippet: <|code_start|>
if fields is None:
pass
def filter_dataset(self, settings, dataset=None):
if settings.filter_dataset and settings.filter_querystring:
params = QueryDict(settings.filter_querystring).dict()
orders = params.pop('o', '').split('.')
fields = params.pop('fields', '').split(',')
for ignore in IGNORED_PARAMS:
params.pop(ignore, None)
if not dataset:
return params
dataset = dataset.filter(**params)
if '' not in orders and '' not in fields:
ordering = []
for order in orders:
field = fields[abs(int(order))]
if int(order) < 0:
field = '-{}'.format(field)
ordering.append(field)
dataset = dataset.order_by(*ordering)
return dataset
def prepare_export_dataset(self, settings):
<|code_end|>
, determine the next line of code. You have imports:
from django.utils.six.moves import filterfalse
from django.utils.translation import activate
from django.http import QueryDict
from django.contrib.admin.views.main import IGNORED_PARAMS
from mtr.utils.manager import BaseManager
from .helpers import make_model_class, process_attribute, \
model_fields, cell_value, model_settings
from ..settings import SETTINGS
and context (class names, function names, or code) available:
# Path: mtr/sync/lib/helpers.py
# def cell_value(row, cols, processor=None):
# def column_name(index):
# def column_index(value):
# def model_fields(model, settings=None):
# def model_attributes(settings, prefix=None, model=None, parent=None, level=0):
# def make_model_class(settings):
# def _process_fk_attribute(model, attribute):
# def _process_mtm_attribute(model, attribute):
# def process_attribute(model, attribute):
#
# Path: mtr/sync/settings.py
# SETTINGS = getattr_with_prefix('SYNC', 'SETTINGS', {
# 'path': get_buffer_file_path,
# 'default_processor': 'XlsxProcessor',
# 'actions': ['mtr.sync.lib.actions'],
# 'converters': ['mtr.sync.lib.converters'],
# 'processors': [
# 'mtr.sync.lib.processors.xlsx',
# 'mtr.sync.lib.processors.xls',
# 'mtr.sync.lib.processors.ods',
# 'mtr.sync.lib.processors.csv',
# ],
# 'broker': 'rq',
# 'include': {
# 'api': False,
# 'admin': True,
# }
# })
. Output only the next line. | current_model = make_model_class(settings) |
Given the following code snippet before the placeholder: <|code_start|> """Prepare data using filters from settings
and return data with dimensions"""
settings = processor.settings
model = make_model_class(settings)
msettings = model_settings(model, 'sync')
exclude = msettings.get('exclude', [])
fields = settings.fields_with_converters()
fields = list(filterfalse(
lambda f: f.attribute in exclude, fields))
if settings.end_row:
rows = settings.end_row
if settings.start_row:
rows -= settings.start_row
rows += 1
queryset = queryset[:rows]
mfields = model_fields(model)
return {
'rows': queryset.count(),
'cols': len(fields),
'fields': fields,
'mfields': mfields,
'items': (
self.convert_value(
<|code_end|>
, predict the next line using imports from the current file:
from django.utils.six.moves import filterfalse
from django.utils.translation import activate
from django.http import QueryDict
from django.contrib.admin.views.main import IGNORED_PARAMS
from mtr.utils.manager import BaseManager
from .helpers import make_model_class, process_attribute, \
model_fields, cell_value, model_settings
from ..settings import SETTINGS
and context including class names, function names, and sometimes code from other files:
# Path: mtr/sync/lib/helpers.py
# def cell_value(row, cols, processor=None):
# def column_name(index):
# def column_index(value):
# def model_fields(model, settings=None):
# def model_attributes(settings, prefix=None, model=None, parent=None, level=0):
# def make_model_class(settings):
# def _process_fk_attribute(model, attribute):
# def _process_mtm_attribute(model, attribute):
# def process_attribute(model, attribute):
#
# Path: mtr/sync/settings.py
# SETTINGS = getattr_with_prefix('SYNC', 'SETTINGS', {
# 'path': get_buffer_file_path,
# 'default_processor': 'XlsxProcessor',
# 'actions': ['mtr.sync.lib.actions'],
# 'converters': ['mtr.sync.lib.converters'],
# 'processors': [
# 'mtr.sync.lib.processors.xlsx',
# 'mtr.sync.lib.processors.xls',
# 'mtr.sync.lib.processors.ods',
# 'mtr.sync.lib.processors.csv',
# ],
# 'broker': 'rq',
# 'include': {
# 'api': False,
# 'admin': True,
# }
# })
. Output only the next line. | process_attribute(item, field.attribute), |
Given the following code snippet before the placeholder: <|code_start|> dataset = dataset(current_model, settings)
else:
dataset = current_model._default_manager.all()
dataset = self.filter_dataset(settings, dataset)
return dataset
def prepare_export_data(self, processor, queryset):
"""Prepare data using filters from settings
and return data with dimensions"""
settings = processor.settings
model = make_model_class(settings)
msettings = model_settings(model, 'sync')
exclude = msettings.get('exclude', [])
fields = settings.fields_with_converters()
fields = list(filterfalse(
lambda f: f.attribute in exclude, fields))
if settings.end_row:
rows = settings.end_row
if settings.start_row:
rows -= settings.start_row
rows += 1
queryset = queryset[:rows]
<|code_end|>
, predict the next line using imports from the current file:
from django.utils.six.moves import filterfalse
from django.utils.translation import activate
from django.http import QueryDict
from django.contrib.admin.views.main import IGNORED_PARAMS
from mtr.utils.manager import BaseManager
from .helpers import make_model_class, process_attribute, \
model_fields, cell_value, model_settings
from ..settings import SETTINGS
and context including class names, function names, and sometimes code from other files:
# Path: mtr/sync/lib/helpers.py
# def cell_value(row, cols, processor=None):
# def column_name(index):
# def column_index(value):
# def model_fields(model, settings=None):
# def model_attributes(settings, prefix=None, model=None, parent=None, level=0):
# def make_model_class(settings):
# def _process_fk_attribute(model, attribute):
# def _process_mtm_attribute(model, attribute):
# def process_attribute(model, attribute):
#
# Path: mtr/sync/settings.py
# SETTINGS = getattr_with_prefix('SYNC', 'SETTINGS', {
# 'path': get_buffer_file_path,
# 'default_processor': 'XlsxProcessor',
# 'actions': ['mtr.sync.lib.actions'],
# 'converters': ['mtr.sync.lib.converters'],
# 'processors': [
# 'mtr.sync.lib.processors.xlsx',
# 'mtr.sync.lib.processors.xls',
# 'mtr.sync.lib.processors.ods',
# 'mtr.sync.lib.processors.csv',
# ],
# 'broker': 'rq',
# 'include': {
# 'api': False,
# 'admin': True,
# }
# })
. Output only the next line. | mfields = model_fields(model) |
Given snippet: <|code_start|> }
def prepare_handlers(self, key_name, processor, model, context=None):
prepares = []
handlers = self.all(key_name) or {}
for handler in handlers.keys():
if processor.settings.data_action in handler:
prepares.append(handlers[handler])
context = context or {}
for prepare in prepares:
context = prepare(model, context)
return context
def prepare_context(self, settings, path):
context = {}
contexts = settings.contexts.all()
if not contexts:
return {}
processor = self.make_processor(settings)
max_rows, max_cols = processor.open(path)
processor.set_dimensions(
0, 0, max_rows, max_cols,
import_data=True)
processor._read_from_start = True
for field in contexts:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.utils.six.moves import filterfalse
from django.utils.translation import activate
from django.http import QueryDict
from django.contrib.admin.views.main import IGNORED_PARAMS
from mtr.utils.manager import BaseManager
from .helpers import make_model_class, process_attribute, \
model_fields, cell_value, model_settings
from ..settings import SETTINGS
and context:
# Path: mtr/sync/lib/helpers.py
# def cell_value(row, cols, processor=None):
# def column_name(index):
# def column_index(value):
# def model_fields(model, settings=None):
# def model_attributes(settings, prefix=None, model=None, parent=None, level=0):
# def make_model_class(settings):
# def _process_fk_attribute(model, attribute):
# def _process_mtm_attribute(model, attribute):
# def process_attribute(model, attribute):
#
# Path: mtr/sync/settings.py
# SETTINGS = getattr_with_prefix('SYNC', 'SETTINGS', {
# 'path': get_buffer_file_path,
# 'default_processor': 'XlsxProcessor',
# 'actions': ['mtr.sync.lib.actions'],
# 'converters': ['mtr.sync.lib.converters'],
# 'processors': [
# 'mtr.sync.lib.processors.xlsx',
# 'mtr.sync.lib.processors.xls',
# 'mtr.sync.lib.processors.ods',
# 'mtr.sync.lib.processors.csv',
# ],
# 'broker': 'rq',
# 'include': {
# 'api': False,
# 'admin': True,
# }
# })
which might include code, classes, or functions. Output only the next line. | context[field.name] = field.value or cell_value( |
Continue the code snippet: <|code_start|> ordering = []
for order in orders:
field = fields[abs(int(order))]
if int(order) < 0:
field = '-{}'.format(field)
ordering.append(field)
dataset = dataset.order_by(*ordering)
return dataset
def prepare_export_dataset(self, settings):
current_model = make_model_class(settings)
if settings.dataset:
dataset = self.get('dataset', settings.dataset)
dataset = dataset(current_model, settings)
else:
dataset = current_model._default_manager.all()
dataset = self.filter_dataset(settings, dataset)
return dataset
def prepare_export_data(self, processor, queryset):
"""Prepare data using filters from settings
and return data with dimensions"""
settings = processor.settings
model = make_model_class(settings)
<|code_end|>
. Use current file imports:
from django.utils.six.moves import filterfalse
from django.utils.translation import activate
from django.http import QueryDict
from django.contrib.admin.views.main import IGNORED_PARAMS
from mtr.utils.manager import BaseManager
from .helpers import make_model_class, process_attribute, \
model_fields, cell_value, model_settings
from ..settings import SETTINGS
and context (classes, functions, or code) from other files:
# Path: mtr/sync/lib/helpers.py
# def cell_value(row, cols, processor=None):
# def column_name(index):
# def column_index(value):
# def model_fields(model, settings=None):
# def model_attributes(settings, prefix=None, model=None, parent=None, level=0):
# def make_model_class(settings):
# def _process_fk_attribute(model, attribute):
# def _process_mtm_attribute(model, attribute):
# def process_attribute(model, attribute):
#
# Path: mtr/sync/settings.py
# SETTINGS = getattr_with_prefix('SYNC', 'SETTINGS', {
# 'path': get_buffer_file_path,
# 'default_processor': 'XlsxProcessor',
# 'actions': ['mtr.sync.lib.actions'],
# 'converters': ['mtr.sync.lib.converters'],
# 'processors': [
# 'mtr.sync.lib.processors.xlsx',
# 'mtr.sync.lib.processors.xls',
# 'mtr.sync.lib.processors.ods',
# 'mtr.sync.lib.processors.csv',
# ],
# 'broker': 'rq',
# 'include': {
# 'api': False,
# 'admin': True,
# }
# })
. Output only the next line. | msettings = model_settings(model, 'sync') |
Predict the next line for this snippet: <|code_start|>
def prepare_import_dataset(self, settings, processor, model, fields):
"""Get data from diferent source registered at dataset"""
if settings.dataset:
dataset = self.get('dataset', settings.dataset)
dataset = dataset(model, settings)
for index, row in enumerate(dataset):
yield index, row
else:
for index in processor.rows:
yield index, processor.read(index)
def model_data(self, settings, processor, model, fields):
dataset = self.prepare_import_dataset(
settings, processor, model, fields)
for index, row in dataset:
_model = {}
for index, field in enumerate(fields):
value = cell_value(row, field.name or index)
_model[field.attribute] = self.convert_value(value, field)
yield index, _model
manager = Manager()
manager.import_modules(
<|code_end|>
with the help of current file imports:
from django.utils.six.moves import filterfalse
from django.utils.translation import activate
from django.http import QueryDict
from django.contrib.admin.views.main import IGNORED_PARAMS
from mtr.utils.manager import BaseManager
from .helpers import make_model_class, process_attribute, \
model_fields, cell_value, model_settings
from ..settings import SETTINGS
and context from other files:
# Path: mtr/sync/lib/helpers.py
# def cell_value(row, cols, processor=None):
# def column_name(index):
# def column_index(value):
# def model_fields(model, settings=None):
# def model_attributes(settings, prefix=None, model=None, parent=None, level=0):
# def make_model_class(settings):
# def _process_fk_attribute(model, attribute):
# def _process_mtm_attribute(model, attribute):
# def process_attribute(model, attribute):
#
# Path: mtr/sync/settings.py
# SETTINGS = getattr_with_prefix('SYNC', 'SETTINGS', {
# 'path': get_buffer_file_path,
# 'default_processor': 'XlsxProcessor',
# 'actions': ['mtr.sync.lib.actions'],
# 'converters': ['mtr.sync.lib.converters'],
# 'processors': [
# 'mtr.sync.lib.processors.xlsx',
# 'mtr.sync.lib.processors.xls',
# 'mtr.sync.lib.processors.ods',
# 'mtr.sync.lib.processors.csv',
# ],
# 'broker': 'rq',
# 'include': {
# 'api': False,
# 'admin': True,
# }
# })
, which may contain function names, class names, or code. Output only the next line. | SETTINGS['actions'] + SETTINGS['processors'] + SETTINGS['converters']) |
Given snippet: <|code_start|>
class PersonAdmin(SyncAdminMixin, TabbedTranslationAdmin):
list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
actions = ['copy_100']
def copy_100(self, request, queryset):
for item in queryset.all():
item.populate()
copy_100.short_description = 'Copy 100 objects with random data'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from mtr.sync.admin import SyncAdminMixin, SyncTabularInlineMixin
from .models import Person, Office, Tag
and context:
# Path: mtr/sync/admin.py
# class SyncAdminMixin(object):
#
# """Mixin for changelist with export and import buttons"""
#
# change_list_template = themed('admin/change_list.html', True)
#
# show_quick_settings_menu = False
#
# class SyncTabularInlineMixin(object):
#
# """Mixin for tabular inline export and import buttons"""
#
# template = themed('admin/edit_inline/tabular.html', True)
#
# Path: tests/app/models.py
# class Person(models.Model):
# name = models.CharField('name', max_length=255)
# surname = models.CharField('surname', max_length=255)
# gender = models.CharField('gender', max_length=255, choices=(
# ('M', 'Male'),
# ('F', 'Female'),
# ))
# security_level = models.PositiveIntegerField('security level')
# some_excluded_field = models.DecimalField(
# 'some decimal', max_digits=10, decimal_places=3, null=True)
#
# office = models.ForeignKey(Office, null=True, blank=True)
# tags = models.ManyToManyField(Tag)
#
# class Settings:
# sync = {
# 'custom_fields': ['custom_method', 'none_param'],
# 'exclude': ['some_excluded_field']
# }
#
# class Meta:
# verbose_name = 'person'
# verbose_name_plural = 'persons'
#
# def populate(self, num=100):
# for i in range(num):
# name = list(self.name)
# random.shuffle(name)
# name = ''.join(name)
#
# surname = list(self.surname)
# random.shuffle(surname)
# surname = ''.join(surname)
#
# newobj = self.__class__(
# name=name,
# office=self.office,
# surname=surname,
# gender=random.choice(['M', 'F']),
# security_level=random.choice(range(100))
# )
# newobj.save()
# newobj.tags.add(*self.tags.all())
# newobj.save()
# self.save()
#
# @classmethod
# def populate_for_test(cls, count):
# instance = cls.objects.create(
# name=six.text_type('test instance éprouver'),
# surname='test surname',
# gender='M', security_level=10)
# r_instance = Office.objects.create(
# office='test', address='addr')
# tags = [Tag(name='test'), Tag(name='test1')]
#
# for tag in tags:
# tag.save()
# instance.tags.add(tag)
#
# instance.office = r_instance
# instance.save()
# instance.populate(count)
#
# return instance, r_instance, tags
#
# @property
# def custom_method(self):
# return six.text_type('{}-{}').format(self.name, self.surname)
#
# @custom_method.setter
# def custom_method(self, value):
# self.name, self.surname = value.split('-')
#
# @property
# def none_param(self):
# return None
#
# @none_param.setter
# def none_param(self, value):
# pass
#
# def __str__(self):
# return self.name
#
# class Office(models.Model):
# office = models.CharField('office', max_length=255)
# address = models.CharField('address', max_length=255)
#
# def __str__(self):
# return self.office
#
# class Meta:
# verbose_name = 'office'
# verbose_name_plural = 'offices'
#
# class Tag(models.Model):
# name = models.CharField('tag', max_length=255)
#
# def __str__(self):
# return self.name
#
# class Meta:
# verbose_name = 'tag'
# verbose_name_plural = 'tags'
which might include code, classes, or functions. Output only the next line. | class PersonStackedInline(SyncTabularInlineMixin, admin.TabularInline): |
Based on the snippet: <|code_start|>
class PersonAdmin(SyncAdminMixin, TabbedTranslationAdmin):
list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
actions = ['copy_100']
def copy_100(self, request, queryset):
for item in queryset.all():
item.populate()
copy_100.short_description = 'Copy 100 objects with random data'
class PersonStackedInline(SyncTabularInlineMixin, admin.TabularInline):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from mtr.sync.admin import SyncAdminMixin, SyncTabularInlineMixin
from .models import Person, Office, Tag
and context (classes, functions, sometimes code) from other files:
# Path: mtr/sync/admin.py
# class SyncAdminMixin(object):
#
# """Mixin for changelist with export and import buttons"""
#
# change_list_template = themed('admin/change_list.html', True)
#
# show_quick_settings_menu = False
#
# class SyncTabularInlineMixin(object):
#
# """Mixin for tabular inline export and import buttons"""
#
# template = themed('admin/edit_inline/tabular.html', True)
#
# Path: tests/app/models.py
# class Person(models.Model):
# name = models.CharField('name', max_length=255)
# surname = models.CharField('surname', max_length=255)
# gender = models.CharField('gender', max_length=255, choices=(
# ('M', 'Male'),
# ('F', 'Female'),
# ))
# security_level = models.PositiveIntegerField('security level')
# some_excluded_field = models.DecimalField(
# 'some decimal', max_digits=10, decimal_places=3, null=True)
#
# office = models.ForeignKey(Office, null=True, blank=True)
# tags = models.ManyToManyField(Tag)
#
# class Settings:
# sync = {
# 'custom_fields': ['custom_method', 'none_param'],
# 'exclude': ['some_excluded_field']
# }
#
# class Meta:
# verbose_name = 'person'
# verbose_name_plural = 'persons'
#
# def populate(self, num=100):
# for i in range(num):
# name = list(self.name)
# random.shuffle(name)
# name = ''.join(name)
#
# surname = list(self.surname)
# random.shuffle(surname)
# surname = ''.join(surname)
#
# newobj = self.__class__(
# name=name,
# office=self.office,
# surname=surname,
# gender=random.choice(['M', 'F']),
# security_level=random.choice(range(100))
# )
# newobj.save()
# newobj.tags.add(*self.tags.all())
# newobj.save()
# self.save()
#
# @classmethod
# def populate_for_test(cls, count):
# instance = cls.objects.create(
# name=six.text_type('test instance éprouver'),
# surname='test surname',
# gender='M', security_level=10)
# r_instance = Office.objects.create(
# office='test', address='addr')
# tags = [Tag(name='test'), Tag(name='test1')]
#
# for tag in tags:
# tag.save()
# instance.tags.add(tag)
#
# instance.office = r_instance
# instance.save()
# instance.populate(count)
#
# return instance, r_instance, tags
#
# @property
# def custom_method(self):
# return six.text_type('{}-{}').format(self.name, self.surname)
#
# @custom_method.setter
# def custom_method(self, value):
# self.name, self.surname = value.split('-')
#
# @property
# def none_param(self):
# return None
#
# @none_param.setter
# def none_param(self, value):
# pass
#
# def __str__(self):
# return self.name
#
# class Office(models.Model):
# office = models.CharField('office', max_length=255)
# address = models.CharField('address', max_length=255)
#
# def __str__(self):
# return self.office
#
# class Meta:
# verbose_name = 'office'
# verbose_name_plural = 'offices'
#
# class Tag(models.Model):
# name = models.CharField('tag', max_length=255)
#
# def __str__(self):
# return self.name
#
# class Meta:
# verbose_name = 'tag'
# verbose_name_plural = 'tags'
. Output only the next line. | model = Person |
Given the code snippet: <|code_start|>
class PersonAdmin(SyncAdminMixin, TabbedTranslationAdmin):
list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
actions = ['copy_100']
def copy_100(self, request, queryset):
for item in queryset.all():
item.populate()
copy_100.short_description = 'Copy 100 objects with random data'
class PersonStackedInline(SyncTabularInlineMixin, admin.TabularInline):
model = Person
extra = 0
class OfficeAdmin(admin.ModelAdmin):
inlines = (PersonStackedInline,)
list_display = ('office', 'address')
class TagAdmin(admin.ModelAdmin):
list_display = ('name',)
admin.site.register(Person, PersonAdmin)
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from mtr.sync.admin import SyncAdminMixin, SyncTabularInlineMixin
from .models import Person, Office, Tag
and context (functions, classes, or occasionally code) from other files:
# Path: mtr/sync/admin.py
# class SyncAdminMixin(object):
#
# """Mixin for changelist with export and import buttons"""
#
# change_list_template = themed('admin/change_list.html', True)
#
# show_quick_settings_menu = False
#
# class SyncTabularInlineMixin(object):
#
# """Mixin for tabular inline export and import buttons"""
#
# template = themed('admin/edit_inline/tabular.html', True)
#
# Path: tests/app/models.py
# class Person(models.Model):
# name = models.CharField('name', max_length=255)
# surname = models.CharField('surname', max_length=255)
# gender = models.CharField('gender', max_length=255, choices=(
# ('M', 'Male'),
# ('F', 'Female'),
# ))
# security_level = models.PositiveIntegerField('security level')
# some_excluded_field = models.DecimalField(
# 'some decimal', max_digits=10, decimal_places=3, null=True)
#
# office = models.ForeignKey(Office, null=True, blank=True)
# tags = models.ManyToManyField(Tag)
#
# class Settings:
# sync = {
# 'custom_fields': ['custom_method', 'none_param'],
# 'exclude': ['some_excluded_field']
# }
#
# class Meta:
# verbose_name = 'person'
# verbose_name_plural = 'persons'
#
# def populate(self, num=100):
# for i in range(num):
# name = list(self.name)
# random.shuffle(name)
# name = ''.join(name)
#
# surname = list(self.surname)
# random.shuffle(surname)
# surname = ''.join(surname)
#
# newobj = self.__class__(
# name=name,
# office=self.office,
# surname=surname,
# gender=random.choice(['M', 'F']),
# security_level=random.choice(range(100))
# )
# newobj.save()
# newobj.tags.add(*self.tags.all())
# newobj.save()
# self.save()
#
# @classmethod
# def populate_for_test(cls, count):
# instance = cls.objects.create(
# name=six.text_type('test instance éprouver'),
# surname='test surname',
# gender='M', security_level=10)
# r_instance = Office.objects.create(
# office='test', address='addr')
# tags = [Tag(name='test'), Tag(name='test1')]
#
# for tag in tags:
# tag.save()
# instance.tags.add(tag)
#
# instance.office = r_instance
# instance.save()
# instance.populate(count)
#
# return instance, r_instance, tags
#
# @property
# def custom_method(self):
# return six.text_type('{}-{}').format(self.name, self.surname)
#
# @custom_method.setter
# def custom_method(self, value):
# self.name, self.surname = value.split('-')
#
# @property
# def none_param(self):
# return None
#
# @none_param.setter
# def none_param(self, value):
# pass
#
# def __str__(self):
# return self.name
#
# class Office(models.Model):
# office = models.CharField('office', max_length=255)
# address = models.CharField('address', max_length=255)
#
# def __str__(self):
# return self.office
#
# class Meta:
# verbose_name = 'office'
# verbose_name_plural = 'offices'
#
# class Tag(models.Model):
# name = models.CharField('tag', max_length=255)
#
# def __str__(self):
# return self.name
#
# class Meta:
# verbose_name = 'tag'
# verbose_name_plural = 'tags'
. Output only the next line. | admin.site.register(Office, OfficeAdmin) |
Given snippet: <|code_start|>
class PersonAdmin(SyncAdminMixin, TabbedTranslationAdmin):
list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
actions = ['copy_100']
def copy_100(self, request, queryset):
for item in queryset.all():
item.populate()
copy_100.short_description = 'Copy 100 objects with random data'
class PersonStackedInline(SyncTabularInlineMixin, admin.TabularInline):
model = Person
extra = 0
class OfficeAdmin(admin.ModelAdmin):
inlines = (PersonStackedInline,)
list_display = ('office', 'address')
class TagAdmin(admin.ModelAdmin):
list_display = ('name',)
admin.site.register(Person, PersonAdmin)
admin.site.register(Office, OfficeAdmin)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from mtr.sync.admin import SyncAdminMixin, SyncTabularInlineMixin
from .models import Person, Office, Tag
and context:
# Path: mtr/sync/admin.py
# class SyncAdminMixin(object):
#
# """Mixin for changelist with export and import buttons"""
#
# change_list_template = themed('admin/change_list.html', True)
#
# show_quick_settings_menu = False
#
# class SyncTabularInlineMixin(object):
#
# """Mixin for tabular inline export and import buttons"""
#
# template = themed('admin/edit_inline/tabular.html', True)
#
# Path: tests/app/models.py
# class Person(models.Model):
# name = models.CharField('name', max_length=255)
# surname = models.CharField('surname', max_length=255)
# gender = models.CharField('gender', max_length=255, choices=(
# ('M', 'Male'),
# ('F', 'Female'),
# ))
# security_level = models.PositiveIntegerField('security level')
# some_excluded_field = models.DecimalField(
# 'some decimal', max_digits=10, decimal_places=3, null=True)
#
# office = models.ForeignKey(Office, null=True, blank=True)
# tags = models.ManyToManyField(Tag)
#
# class Settings:
# sync = {
# 'custom_fields': ['custom_method', 'none_param'],
# 'exclude': ['some_excluded_field']
# }
#
# class Meta:
# verbose_name = 'person'
# verbose_name_plural = 'persons'
#
# def populate(self, num=100):
# for i in range(num):
# name = list(self.name)
# random.shuffle(name)
# name = ''.join(name)
#
# surname = list(self.surname)
# random.shuffle(surname)
# surname = ''.join(surname)
#
# newobj = self.__class__(
# name=name,
# office=self.office,
# surname=surname,
# gender=random.choice(['M', 'F']),
# security_level=random.choice(range(100))
# )
# newobj.save()
# newobj.tags.add(*self.tags.all())
# newobj.save()
# self.save()
#
# @classmethod
# def populate_for_test(cls, count):
# instance = cls.objects.create(
# name=six.text_type('test instance éprouver'),
# surname='test surname',
# gender='M', security_level=10)
# r_instance = Office.objects.create(
# office='test', address='addr')
# tags = [Tag(name='test'), Tag(name='test1')]
#
# for tag in tags:
# tag.save()
# instance.tags.add(tag)
#
# instance.office = r_instance
# instance.save()
# instance.populate(count)
#
# return instance, r_instance, tags
#
# @property
# def custom_method(self):
# return six.text_type('{}-{}').format(self.name, self.surname)
#
# @custom_method.setter
# def custom_method(self, value):
# self.name, self.surname = value.split('-')
#
# @property
# def none_param(self):
# return None
#
# @none_param.setter
# def none_param(self, value):
# pass
#
# def __str__(self):
# return self.name
#
# class Office(models.Model):
# office = models.CharField('office', max_length=255)
# address = models.CharField('address', max_length=255)
#
# def __str__(self):
# return self.office
#
# class Meta:
# verbose_name = 'office'
# verbose_name_plural = 'offices'
#
# class Tag(models.Model):
# name = models.CharField('tag', max_length=255)
#
# def __str__(self):
# return self.name
#
# class Meta:
# verbose_name = 'tag'
# verbose_name_plural = 'tags'
which might include code, classes, or functions. Output only the next line. | admin.site.register(Tag, TagAdmin) |
Using the snippet: <|code_start|># ayrton is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ayrton is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ayrton. If not, see <http://www.gnu.org/licenses/>.
flow_stmt= [ Break, Continue, Return, Raise, Yield, ]
expr_stmt= [ ]
small_stmt= expr_stmt + [ Del, Pass ] + flow_stmt + [ Import, ImportFrom, Global,
Assert ]
def check_attrs (self, node):
for n in ast.walk (node):
if type (n) in small_stmt:
self.assertTrue (hasattr(node, 'lineno'), "%s.lineno not present" % ast.dump (node))
self.assertTrue (hasattr(node, 'col_offset'), "%s.col_offset not present" % ast.dump (node))
class TestBinding (unittest.TestCase):
def setUp (self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import ast
import ayrton
from ast import Attribute, Name, Load, Subscript, Index, Num, With, Str
from ast import Break, Continue, Return, Raise, Yield
from ast import Del, Pass, Import, ImportFrom, Global, Assert
from ayrton import castt
from ayrton.execute import o
from ayrton.functions import cd, define
and context (class names, function names, or code) available:
# Path: ayrton/castt.py
# class NameConstant (_ast.Name):
# class CrazyASTTransformer (ast.NodeTransformer):
# def __init__ (self, value, *args):
# def append_to_tuple (t, o):
# def pop_from_tuple (t, n=-1):
# def is_executable (node):
# def is_option (arg):
# def has_keyword (node, keyword):
# def update_keyword (node, keyword):
# def func_name2dotted_exec (node):
# def __init__ (self, environ, file_name=None):
# def modify (self, tree):
# def bind (self, o):
# def unbind (self, name, remove_from_stack=False):
# def visit_Import (self, node):
# def visit_ClassDef (self, node):
# def visit_FunctionDef (self, node):
# def visit_For (self, node):
# def visit_ExceptHandler (self, node):
# def visit_Assign (self, node):
# def visit_Delete (self, node):
# def visit_BinOp (self, node):
# def visit_Compare (self, node):
# def visit_Call (self, node):
# def visit_With (self, node):
#
# Path: ayrton/execute.py
# class o (object):
# def __init__ (self, **kwargs):
# option= list (kwargs.items ())[0]
# self.key= option[0]
# self.value= option[1]
#
# Path: ayrton/functions.py
# class cd (object):
# def __init__ (self, dir):
# self.old_dir= os.getcwd ()
# os.chdir (dir)
#
# def __enter__ (self):
# pass
#
# def __exit__ (self, *args):
# os.chdir (self.old_dir)
#
# def define(*varnames, **defaults):
# # defaults have priority over simple names (because they provide a value)
# for varname in varnames:
# if varname not in defaults:
# defaults[varname] = None
#
# for varname, value in defaults.items():
# if not isinstance(varname, str):
# raise ValueError('variable name cannot be non-string: %r' % varname)
#
# if varname not in ayrton.runner.globals:
# ayrton.runner.globals[varname] = value
. Output only the next line. | self.c= castt.CrazyASTTransformer ({}) |
Given the code snippet: <|code_start|> t= self.c.modify (t)
self.assertTrue ('x' in self.c.seen_names)
self.assertTrue ('y' in self.c.seen_names)
def testImport (self):
t= ast.parse ("""import os""")
t= self.c.modify (t)
self.assertTrue ('os' in self.c.seen_names)
def testTryExcept (self):
t= ast.parse ("""try:
foo()
except Exception as e:
pass""")
t= self.c.modify (t)
self.assertTrue ('e' in self.c.seen_names)
def parse_expression (s):
# Module(body=[Expr(value=...)])
return ast.parse (s).body[0].value
class TestVisits (unittest.TestCase):
check_attrs= check_attrs
def testFunctionKeywords (self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import ast
import ayrton
from ast import Attribute, Name, Load, Subscript, Index, Num, With, Str
from ast import Break, Continue, Return, Raise, Yield
from ast import Del, Pass, Import, ImportFrom, Global, Assert
from ayrton import castt
from ayrton.execute import o
from ayrton.functions import cd, define
and context (functions, classes, or occasionally code) from other files:
# Path: ayrton/castt.py
# class NameConstant (_ast.Name):
# class CrazyASTTransformer (ast.NodeTransformer):
# def __init__ (self, value, *args):
# def append_to_tuple (t, o):
# def pop_from_tuple (t, n=-1):
# def is_executable (node):
# def is_option (arg):
# def has_keyword (node, keyword):
# def update_keyword (node, keyword):
# def func_name2dotted_exec (node):
# def __init__ (self, environ, file_name=None):
# def modify (self, tree):
# def bind (self, o):
# def unbind (self, name, remove_from_stack=False):
# def visit_Import (self, node):
# def visit_ClassDef (self, node):
# def visit_FunctionDef (self, node):
# def visit_For (self, node):
# def visit_ExceptHandler (self, node):
# def visit_Assign (self, node):
# def visit_Delete (self, node):
# def visit_BinOp (self, node):
# def visit_Compare (self, node):
# def visit_Call (self, node):
# def visit_With (self, node):
#
# Path: ayrton/execute.py
# class o (object):
# def __init__ (self, **kwargs):
# option= list (kwargs.items ())[0]
# self.key= option[0]
# self.value= option[1]
#
# Path: ayrton/functions.py
# class cd (object):
# def __init__ (self, dir):
# self.old_dir= os.getcwd ()
# os.chdir (dir)
#
# def __enter__ (self):
# pass
#
# def __exit__ (self, *args):
# os.chdir (self.old_dir)
#
# def define(*varnames, **defaults):
# # defaults have priority over simple names (because they provide a value)
# for varname in varnames:
# if varname not in defaults:
# defaults[varname] = None
#
# for varname, value in defaults.items():
# if not isinstance(varname, str):
# raise ValueError('variable name cannot be non-string: %r' % varname)
#
# if varname not in ayrton.runner.globals:
# ayrton.runner.globals[varname] = value
. Output only the next line. | c= castt.CrazyASTTransformer ({ 'dict': dict, 'o': o}) |
Based on the snippet: <|code_start|> self.assertEqual (combined, 'argv[3].split')
def testDottedSubscriptComplex (self):
single, combined= castt.func_name2dotted_exec (parse_expression ('argv[3].split[:54]'))
self.assertEqual (single, 'argv')
# this is a very strange but possible executable name
self.assertEqual (combined, 'argv[3].split[:54]')
def testDottedCall (self):
single, combined= castt.func_name2dotted_exec (parse_expression ('str (foo).strip ()'))
self.assertEqual (single, 'str')
# this is a very strange but possible executable name
self.assertEqual (combined, 'str (foo).strip ()')
def testObjectMethod (self):
single, combined= castt.func_name2dotted_exec (parse_expression ('".".join ([])'))
self.assertEqual (single, None)
self.assertEqual (combined, None)
class TestWeirdErrors (unittest.TestCase):
check_attrs= check_attrs
def testWithCd (self):
code= """with cd() as e: pass"""
t= ast.parse (code)
self.check_attrs (t.body[0])
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import ast
import ayrton
from ast import Attribute, Name, Load, Subscript, Index, Num, With, Str
from ast import Break, Continue, Return, Raise, Yield
from ast import Del, Pass, Import, ImportFrom, Global, Assert
from ayrton import castt
from ayrton.execute import o
from ayrton.functions import cd, define
and context (classes, functions, sometimes code) from other files:
# Path: ayrton/castt.py
# class NameConstant (_ast.Name):
# class CrazyASTTransformer (ast.NodeTransformer):
# def __init__ (self, value, *args):
# def append_to_tuple (t, o):
# def pop_from_tuple (t, n=-1):
# def is_executable (node):
# def is_option (arg):
# def has_keyword (node, keyword):
# def update_keyword (node, keyword):
# def func_name2dotted_exec (node):
# def __init__ (self, environ, file_name=None):
# def modify (self, tree):
# def bind (self, o):
# def unbind (self, name, remove_from_stack=False):
# def visit_Import (self, node):
# def visit_ClassDef (self, node):
# def visit_FunctionDef (self, node):
# def visit_For (self, node):
# def visit_ExceptHandler (self, node):
# def visit_Assign (self, node):
# def visit_Delete (self, node):
# def visit_BinOp (self, node):
# def visit_Compare (self, node):
# def visit_Call (self, node):
# def visit_With (self, node):
#
# Path: ayrton/execute.py
# class o (object):
# def __init__ (self, **kwargs):
# option= list (kwargs.items ())[0]
# self.key= option[0]
# self.value= option[1]
#
# Path: ayrton/functions.py
# class cd (object):
# def __init__ (self, dir):
# self.old_dir= os.getcwd ()
# os.chdir (dir)
#
# def __enter__ (self):
# pass
#
# def __exit__ (self, *args):
# os.chdir (self.old_dir)
#
# def define(*varnames, **defaults):
# # defaults have priority over simple names (because they provide a value)
# for varname in varnames:
# if varname not in defaults:
# defaults[varname] = None
#
# for varname, value in defaults.items():
# if not isinstance(varname, str):
# raise ValueError('variable name cannot be non-string: %r' % varname)
#
# if varname not in ayrton.runner.globals:
# ayrton.runner.globals[varname] = value
. Output only the next line. | c= castt.CrazyASTTransformer ({ 'o': o, 'cd': cd}) |
Given the code snippet: <|code_start|> c= castt.CrazyASTTransformer ({ 'o': o, 'dict': dict})
t= ayrton.parse ("""dict (p=True, False)""")
self.assertRaises (SyntaxError, c.visit_Call, t.body[0].value)
def testMinusMinusFunction (self):
c= castt.CrazyASTTransformer ({ 'o': o, 'dict': dict})
t= ayrton.parse ("""dict (--p=True)""")
self.assertRaises (SyntaxError, c.visit_Call, t.body[0].value)
def testMinusMinusCommand (self):
c= castt.CrazyASTTransformer ({ 'o': o})
t= ayrton.parse ("""foo (--p=True)""")
node= c.visit_Call (t.body[0].value)
self.assertEqual (node.args[0].keywords[0].arg, '--p')
self.check_attrs (node)
def testLongOptionCommand (self):
c= castt.CrazyASTTransformer ({ 'o': o})
t= ayrton.parse ("""foo (--long-option=True)""")
node= c.visit_Call (t.body[0].value)
self.assertEqual (node.args[0].keywords[0].arg, '--long-option')
self.check_attrs (node)
def testDefine(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import ast
import ayrton
from ast import Attribute, Name, Load, Subscript, Index, Num, With, Str
from ast import Break, Continue, Return, Raise, Yield
from ast import Del, Pass, Import, ImportFrom, Global, Assert
from ayrton import castt
from ayrton.execute import o
from ayrton.functions import cd, define
and context (functions, classes, or occasionally code) from other files:
# Path: ayrton/castt.py
# class NameConstant (_ast.Name):
# class CrazyASTTransformer (ast.NodeTransformer):
# def __init__ (self, value, *args):
# def append_to_tuple (t, o):
# def pop_from_tuple (t, n=-1):
# def is_executable (node):
# def is_option (arg):
# def has_keyword (node, keyword):
# def update_keyword (node, keyword):
# def func_name2dotted_exec (node):
# def __init__ (self, environ, file_name=None):
# def modify (self, tree):
# def bind (self, o):
# def unbind (self, name, remove_from_stack=False):
# def visit_Import (self, node):
# def visit_ClassDef (self, node):
# def visit_FunctionDef (self, node):
# def visit_For (self, node):
# def visit_ExceptHandler (self, node):
# def visit_Assign (self, node):
# def visit_Delete (self, node):
# def visit_BinOp (self, node):
# def visit_Compare (self, node):
# def visit_Call (self, node):
# def visit_With (self, node):
#
# Path: ayrton/execute.py
# class o (object):
# def __init__ (self, **kwargs):
# option= list (kwargs.items ())[0]
# self.key= option[0]
# self.value= option[1]
#
# Path: ayrton/functions.py
# class cd (object):
# def __init__ (self, dir):
# self.old_dir= os.getcwd ()
# os.chdir (dir)
#
# def __enter__ (self):
# pass
#
# def __exit__ (self, *args):
# os.chdir (self.old_dir)
#
# def define(*varnames, **defaults):
# # defaults have priority over simple names (because they provide a value)
# for varname in varnames:
# if varname not in defaults:
# defaults[varname] = None
#
# for varname, value in defaults.items():
# if not isinstance(varname, str):
# raise ValueError('variable name cannot be non-string: %r' % varname)
#
# if varname not in ayrton.runner.globals:
# ayrton.runner.globals[varname] = value
. Output only the next line. | c= castt.CrazyASTTransformer ({ 'define': define }) |
Using the snippet: <|code_start|> # If ICANON is also set, the ERASE character erases the preceding input character, and WERASE erases the preceding word
# If ICANON is also set, the KILL character erases the current line
# If ICANON is also set, echo the NL character even if ECHO is not set
# implementation-defined input processing
lflag&= ~( ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHONL | IEXTEN )
# turn off:
# implementation-defined output processing
oflag&= ~OPOST
# NOTE: whatever
# Minimum number of characters for noncanonical read
cc[VMIN]= 1
# Timeout in deciseconds for noncanonical read
cc[VTIME]= 0
tcsetattr(self.pairs[0][0], TCSADRAIN, [ iflag, oflag, cflag, lflag,
ispeed, ospeed, cc ])
def fileno (self, f):
if isinstance (f, int):
return f
elif getattr (f, 'fileno', None) is not None:
return f.fileno ()
else:
raise TypeError (f)
def run (self):
logger.debug ('%s thread run' % self)
<|code_end|>
, determine the next line of code. You have imports:
import ayrton
import paramiko
import pickle
import types
import sys
import errno
import ctypes
import os
import traceback
import io
import shutil
import itertools
import paramiko.ssh_exception
import logging
from socket import socket, SO_REUSEADDR, SOL_SOCKET
from threading import Thread
from termios import tcgetattr, tcsetattr, TCSADRAIN
from termios import IGNPAR, ISTRIP, INLCR, IGNCR, ICRNL, IXON, IXANY, IXOFF
from termios import ISIG, ICANON, ECHO, ECHOE, ECHOK, ECHONL, IEXTEN, OPOST, VMIN, VTIME
from ayrton.utils import copy_loop, close
and context (class names, function names, or code) available:
# Path: ayrton/utils.py
# def copy_loop (copy_to, finished=None, buf_len=10240):
# """copy_to is a dict(in: out). When any in is ready to read, data is read
# from it and writen in its out. When any in is closed, it's removed from
# copy_to. finished is a pipe; when data comes from the read end, or when
# no more ins are present, the loop finishes."""
# if finished is not None:
# copy_to[finished]= None
#
# # NOTE:
# # os.sendfile (self.dst, self.src, None, 0)
# # OSError: [Errno 22] Invalid argument
# # and splice() is not available
# # so, copy by hand
# selector = DefaultSelector ()
# for src in copy_to.keys ():
# if ( not isinstance (src, int)
# and ( getattr (src, 'fileno', None) is None
# or not isinstance (src.fileno(), int)) ):
# logger.debug ('type mismatch: %s', src)
# else:
# logger.debug ("registering %s for read", src)
# # if finished is also one of the srcs, then register() complains
# try:
# selector.register (src, EVENT_READ)
# except KeyError:
# pass
#
# def close_file (f):
# if f in copy_to:
# del copy_to[f]
#
# try:
# selector.unregister (i)
# except KeyError:
# pass
#
# close (f)
#
# while len (copy_to)>0:
# logger.debug (copy_to)
#
# events= selector.select ()
# for key, _ in events:
# logger.debug ("%s is ready to read", key)
# i= key.fileobj
#
# # for error in e:
# # logger.debug ('%s error')
# # TODO: what?
#
# o= copy_to[i]
#
# try:
# data= read (i, buf_len)
# logger.debug2 ('%s -> %s: %s', i, o, data)
#
# # ValueError: read of closed file
# except (OSError, ValueError) as e:
# logger.debug ('stopping copying for %s', i)
# logger.debug (traceback.format_exc ())
# close_file (i)
# break
# else:
# if len (data)==0:
# logger.debug ('stopping copying for %s, no more data', i)
# close_file (i)
#
# if finished is not None and i==finished:
# logger.debug ('finishing')
# # quite a hack :)
# copy_to= {}
#
# break
# else:
# write (o, data)
#
# selector.close ()
# logger.debug ('over and out')
#
# def close (f):
# logger.debug ('closing %s', f, callers=1)
# try:
# if isinstance (f, int):
# os.close (f)
# else:
# if f is not None:
# f.close ()
# except OSError as e:
# logger.debug ('closing gave %s', e)
# if e.errno!=errno.EBADF:
# raise
. Output only the next line. | copy_loop(self.copy_to, self.finished[0]) |
Using the snippet: <|code_start|> # If ICANON is also set, the KILL character erases the current line
# If ICANON is also set, echo the NL character even if ECHO is not set
# implementation-defined input processing
lflag&= ~( ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHONL | IEXTEN )
# turn off:
# implementation-defined output processing
oflag&= ~OPOST
# NOTE: whatever
# Minimum number of characters for noncanonical read
cc[VMIN]= 1
# Timeout in deciseconds for noncanonical read
cc[VTIME]= 0
tcsetattr(self.pairs[0][0], TCSADRAIN, [ iflag, oflag, cflag, lflag,
ispeed, ospeed, cc ])
def fileno (self, f):
if isinstance (f, int):
return f
elif getattr (f, 'fileno', None) is not None:
return f.fileno ()
else:
raise TypeError (f)
def run (self):
logger.debug ('%s thread run' % self)
copy_loop(self.copy_to, self.finished[0])
<|code_end|>
, determine the next line of code. You have imports:
import ayrton
import paramiko
import pickle
import types
import sys
import errno
import ctypes
import os
import traceback
import io
import shutil
import itertools
import paramiko.ssh_exception
import logging
from socket import socket, SO_REUSEADDR, SOL_SOCKET
from threading import Thread
from termios import tcgetattr, tcsetattr, TCSADRAIN
from termios import IGNPAR, ISTRIP, INLCR, IGNCR, ICRNL, IXON, IXANY, IXOFF
from termios import ISIG, ICANON, ECHO, ECHOE, ECHOK, ECHONL, IEXTEN, OPOST, VMIN, VTIME
from ayrton.utils import copy_loop, close
and context (class names, function names, or code) available:
# Path: ayrton/utils.py
# def copy_loop (copy_to, finished=None, buf_len=10240):
# """copy_to is a dict(in: out). When any in is ready to read, data is read
# from it and writen in its out. When any in is closed, it's removed from
# copy_to. finished is a pipe; when data comes from the read end, or when
# no more ins are present, the loop finishes."""
# if finished is not None:
# copy_to[finished]= None
#
# # NOTE:
# # os.sendfile (self.dst, self.src, None, 0)
# # OSError: [Errno 22] Invalid argument
# # and splice() is not available
# # so, copy by hand
# selector = DefaultSelector ()
# for src in copy_to.keys ():
# if ( not isinstance (src, int)
# and ( getattr (src, 'fileno', None) is None
# or not isinstance (src.fileno(), int)) ):
# logger.debug ('type mismatch: %s', src)
# else:
# logger.debug ("registering %s for read", src)
# # if finished is also one of the srcs, then register() complains
# try:
# selector.register (src, EVENT_READ)
# except KeyError:
# pass
#
# def close_file (f):
# if f in copy_to:
# del copy_to[f]
#
# try:
# selector.unregister (i)
# except KeyError:
# pass
#
# close (f)
#
# while len (copy_to)>0:
# logger.debug (copy_to)
#
# events= selector.select ()
# for key, _ in events:
# logger.debug ("%s is ready to read", key)
# i= key.fileobj
#
# # for error in e:
# # logger.debug ('%s error')
# # TODO: what?
#
# o= copy_to[i]
#
# try:
# data= read (i, buf_len)
# logger.debug2 ('%s -> %s: %s', i, o, data)
#
# # ValueError: read of closed file
# except (OSError, ValueError) as e:
# logger.debug ('stopping copying for %s', i)
# logger.debug (traceback.format_exc ())
# close_file (i)
# break
# else:
# if len (data)==0:
# logger.debug ('stopping copying for %s, no more data', i)
# close_file (i)
#
# if finished is not None and i==finished:
# logger.debug ('finishing')
# # quite a hack :)
# copy_to= {}
#
# break
# else:
# write (o, data)
#
# selector.close ()
# logger.debug ('over and out')
#
# def close (f):
# logger.debug ('closing %s', f, callers=1)
# try:
# if isinstance (f, int):
# os.close (f)
# else:
# if f is not None:
# f.close ()
# except OSError as e:
# logger.debug ('closing gave %s', e)
# if e.errno!=errno.EBADF:
# raise
. Output only the next line. | self.close () |
Using the snippet: <|code_start|># ayrton is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ayrton. If not, see <http://www.gnu.org/licenses/>.
logger= logging.getLogger ('ayrton.tests.remote')
class OtherFunctions (unittest.TestCase):
def test_copy_loop_pipe (self):
data= 'yabadabadoo'
pipe= os.pipe ()
self.addCleanup (close, pipe[0])
self.addCleanup (close, pipe[1])
with open (pipe[1], 'w') as w:
w.write (data)
r= pipe[0]
w, dst= mkstemp (suffix='.ayrtmp', dir='.')
self.addCleanup (os.unlink, dst)
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import unittest.case
import sys
import io
import os
import tempfile
import os.path
import time
import signal
import traceback
import paramiko.ssh_exception
import ayrton
import logging
from socket import socket, AF_INET, SOCK_STREAM, SO_REUSEADDR, SOL_SOCKET
from tempfile import mkstemp
from ayrton.expansion import bash
from ayrton.execute import CommandNotFound
from ayrton.utils import copy_loop, close
and context (class names, function names, or code) available:
# Path: ayrton/expansion.py
# def bash (s, single=False):
# data= backslash_descape (glob_expand (tilde_expand (brace_expand (s))))
# if single and len(data)==1:
# data= data[0]
# return data
#
# Path: ayrton/execute.py
# class CommandNotFound (NameError):
# def __init__ (self, name):
# self.name= name
#
# def __str__ (self):
# return "CommandNotFound or NameError: command %(name)s not found or name %(name)s is not defined" % self.__dict__
#
# Path: ayrton/utils.py
# def copy_loop (copy_to, finished=None, buf_len=10240):
# """copy_to is a dict(in: out). When any in is ready to read, data is read
# from it and writen in its out. When any in is closed, it's removed from
# copy_to. finished is a pipe; when data comes from the read end, or when
# no more ins are present, the loop finishes."""
# if finished is not None:
# copy_to[finished]= None
#
# # NOTE:
# # os.sendfile (self.dst, self.src, None, 0)
# # OSError: [Errno 22] Invalid argument
# # and splice() is not available
# # so, copy by hand
# selector = DefaultSelector ()
# for src in copy_to.keys ():
# if ( not isinstance (src, int)
# and ( getattr (src, 'fileno', None) is None
# or not isinstance (src.fileno(), int)) ):
# logger.debug ('type mismatch: %s', src)
# else:
# logger.debug ("registering %s for read", src)
# # if finished is also one of the srcs, then register() complains
# try:
# selector.register (src, EVENT_READ)
# except KeyError:
# pass
#
# def close_file (f):
# if f in copy_to:
# del copy_to[f]
#
# try:
# selector.unregister (i)
# except KeyError:
# pass
#
# close (f)
#
# while len (copy_to)>0:
# logger.debug (copy_to)
#
# events= selector.select ()
# for key, _ in events:
# logger.debug ("%s is ready to read", key)
# i= key.fileobj
#
# # for error in e:
# # logger.debug ('%s error')
# # TODO: what?
#
# o= copy_to[i]
#
# try:
# data= read (i, buf_len)
# logger.debug2 ('%s -> %s: %s', i, o, data)
#
# # ValueError: read of closed file
# except (OSError, ValueError) as e:
# logger.debug ('stopping copying for %s', i)
# logger.debug (traceback.format_exc ())
# close_file (i)
# break
# else:
# if len (data)==0:
# logger.debug ('stopping copying for %s, no more data', i)
# close_file (i)
#
# if finished is not None and i==finished:
# logger.debug ('finishing')
# # quite a hack :)
# copy_to= {}
#
# break
# else:
# write (o, data)
#
# selector.close ()
# logger.debug ('over and out')
#
# def close (f):
# logger.debug ('closing %s', f, callers=1)
# try:
# if isinstance (f, int):
# os.close (f)
# else:
# if f is not None:
# f.close ()
# except OSError as e:
# logger.debug ('closing gave %s', e)
# if e.errno!=errno.EBADF:
# raise
. Output only the next line. | copy_loop ({ r: w }, buf_len=4) |
Given the following code snippet before the placeholder: <|code_start|># (c) 2015 Marcos Dione <mdione@grulic.org.ar>
# This file is part of ayrton.
#
# ayrton is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ayrton is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ayrton. If not, see <http://www.gnu.org/licenses/>.
logger= logging.getLogger ('ayrton.tests.remote')
class OtherFunctions (unittest.TestCase):
def test_copy_loop_pipe (self):
data= 'yabadabadoo'
pipe= os.pipe ()
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import unittest.case
import sys
import io
import os
import tempfile
import os.path
import time
import signal
import traceback
import paramiko.ssh_exception
import ayrton
import logging
from socket import socket, AF_INET, SOCK_STREAM, SO_REUSEADDR, SOL_SOCKET
from tempfile import mkstemp
from ayrton.expansion import bash
from ayrton.execute import CommandNotFound
from ayrton.utils import copy_loop, close
and context including class names, function names, and sometimes code from other files:
# Path: ayrton/expansion.py
# def bash (s, single=False):
# data= backslash_descape (glob_expand (tilde_expand (brace_expand (s))))
# if single and len(data)==1:
# data= data[0]
# return data
#
# Path: ayrton/execute.py
# class CommandNotFound (NameError):
# def __init__ (self, name):
# self.name= name
#
# def __str__ (self):
# return "CommandNotFound or NameError: command %(name)s not found or name %(name)s is not defined" % self.__dict__
#
# Path: ayrton/utils.py
# def copy_loop (copy_to, finished=None, buf_len=10240):
# """copy_to is a dict(in: out). When any in is ready to read, data is read
# from it and writen in its out. When any in is closed, it's removed from
# copy_to. finished is a pipe; when data comes from the read end, or when
# no more ins are present, the loop finishes."""
# if finished is not None:
# copy_to[finished]= None
#
# # NOTE:
# # os.sendfile (self.dst, self.src, None, 0)
# # OSError: [Errno 22] Invalid argument
# # and splice() is not available
# # so, copy by hand
# selector = DefaultSelector ()
# for src in copy_to.keys ():
# if ( not isinstance (src, int)
# and ( getattr (src, 'fileno', None) is None
# or not isinstance (src.fileno(), int)) ):
# logger.debug ('type mismatch: %s', src)
# else:
# logger.debug ("registering %s for read", src)
# # if finished is also one of the srcs, then register() complains
# try:
# selector.register (src, EVENT_READ)
# except KeyError:
# pass
#
# def close_file (f):
# if f in copy_to:
# del copy_to[f]
#
# try:
# selector.unregister (i)
# except KeyError:
# pass
#
# close (f)
#
# while len (copy_to)>0:
# logger.debug (copy_to)
#
# events= selector.select ()
# for key, _ in events:
# logger.debug ("%s is ready to read", key)
# i= key.fileobj
#
# # for error in e:
# # logger.debug ('%s error')
# # TODO: what?
#
# o= copy_to[i]
#
# try:
# data= read (i, buf_len)
# logger.debug2 ('%s -> %s: %s', i, o, data)
#
# # ValueError: read of closed file
# except (OSError, ValueError) as e:
# logger.debug ('stopping copying for %s', i)
# logger.debug (traceback.format_exc ())
# close_file (i)
# break
# else:
# if len (data)==0:
# logger.debug ('stopping copying for %s, no more data', i)
# close_file (i)
#
# if finished is not None and i==finished:
# logger.debug ('finishing')
# # quite a hack :)
# copy_to= {}
#
# break
# else:
# write (o, data)
#
# selector.close ()
# logger.debug ('over and out')
#
# def close (f):
# logger.debug ('closing %s', f, callers=1)
# try:
# if isinstance (f, int):
# os.close (f)
# else:
# if f is not None:
# f.close ()
# except OSError as e:
# logger.debug ('closing gave %s', e)
# if e.errno!=errno.EBADF:
# raise
. Output only the next line. | self.addCleanup (close, pipe[0]) |
Given the code snippet: <|code_start|> lnum = parenlev = continued = 0
namechars = NAMECHARS
numchars = NUMCHARS
contstr, needcont = '', 0
contline = None
indents = [0]
altindents = [0]
last_comment = ''
parenlevstart = (0, 0, "")
# make the annotator happy
endDFA = automata.DFA([], [])
# make the annotator happy
line = ''
pos = 0
lines.append("")
strstart = (0, 0, "")
for line in lines:
lnum = lnum + 1
pos, max = 0, len(line)
if contstr:
if not line:
raise TokenError(
"EOF while scanning triple-quoted string literal",
strstart[2], strstart[0], strstart[1]+1,
token_list, lnum-1)
endmatch = endDFA.recognize(line)
if endmatch >= 0:
pos = end = endmatch
<|code_end|>
, generate the next line using the imports in this file:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context (functions, classes, or occasionally code) from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | tok = (tokens.STRING, contstr + line[:end], strstart[0], |
Given the code snippet: <|code_start|> if token[-1] == '\n': # continued string
strstart = (lnum, start, line)
endDFA = (endDFAs[initial] or endDFAs[token[1]] or
endDFAs[token[2]])
contstr, needcont = line[start:], 1
contline = line
break
else: # ordinary string
tok = (tokens.STRING, token, lnum, start, line)
token_list.append(tok)
last_comment = ''
elif (initial in namechars or # ordinary name
ord(initial) >= 0x80): # unicode identifier
if not verify_identifier(token):
raise TokenError("invalid character in identifier",
line, lnum, start + 1, token_list)
token_list.append((tokens.NAME, token, lnum, start, line))
last_comment = ''
elif initial == '\\': # continued stmt
continued = 1
else:
if initial in '([{':
if parenlev == 0:
parenlevstart = (lnum, start, line)
parenlev = parenlev + 1
elif initial in ')]}':
parenlev = parenlev - 1
if parenlev < 0:
raise TokenError("unmatched '%s'" % initial, line,
lnum, start + 1, token_list)
<|code_end|>
, generate the next line using the imports in this file:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context (functions, classes, or occasionally code) from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | if token in python_opmap: |
Given the code snippet: <|code_start|> token string; a 2-tuple (srow, scol) of ints specifying the row and
column where the token begins in the source; a 2-tuple (erow, ecol) of
ints specifying the row and column where the token ends in the source;
and the line on which the token was found. The line passed is the
logical line; continuation lines are included.
"""
token_list = []
lnum = parenlev = continued = 0
namechars = NAMECHARS
numchars = NUMCHARS
contstr, needcont = '', 0
contline = None
indents = [0]
altindents = [0]
last_comment = ''
parenlevstart = (0, 0, "")
# make the annotator happy
endDFA = automata.DFA([], [])
# make the annotator happy
line = ''
pos = 0
lines.append("")
strstart = (0, 0, "")
for line in lines:
lnum = lnum + 1
pos, max = 0, len(line)
if contstr:
if not line:
<|code_end|>
, generate the next line using the imports in this file:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context (functions, classes, or occasionally code) from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | raise TokenError( |
Given the code snippet: <|code_start|> altcolumn = (altcolumn/alttabsize + 1)*alttabsize
elif line[pos] == '\f':
column = 0
else:
break
pos = pos + 1
if pos == max: break
if line[pos] in '#\r\n':
# skip comments or blank lines
continue
if column == indents[-1]:
if altcolumn != altindents[-1]:
raise TabError(lnum, pos, line)
elif column > indents[-1]: # count indents or dedents
if altcolumn <= altindents[-1]:
raise TabError(lnum, pos, line)
indents.append(column)
altindents.append(altcolumn)
token_list.append((tokens.INDENT, line[:pos], lnum, 0, line))
last_comment = ''
else:
while column < indents[-1]:
indents = indents[:-1]
altindents = altindents[:-1]
token_list.append((tokens.DEDENT, '', lnum, pos, line))
last_comment = ''
if column != indents[-1]:
err = "unindent does not match any outer indentation level"
<|code_end|>
, generate the next line using the imports in this file:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context (functions, classes, or occasionally code) from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | raise TokenIndentationError(err, line, lnum, 0, token_list) |
Given snippet: <|code_start|> continue
else:
contstr = contstr + line
contline = contline + line
continue
elif parenlev == 0 and not continued: # new statement
if not line: break
column = 0
altcolumn = 0
while pos < max: # measure leading whitespace
if line[pos] == ' ':
column = column + 1
altcolumn = altcolumn + 1
elif line[pos] == '\t':
column = (column/tabsize + 1)*tabsize
altcolumn = (altcolumn/alttabsize + 1)*alttabsize
elif line[pos] == '\f':
column = 0
else:
break
pos = pos + 1
if pos == max: break
if line[pos] in '#\r\n':
# skip comments or blank lines
continue
if column == indents[-1]:
if altcolumn != altindents[-1]:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
which might include code, classes, or functions. Output only the next line. | raise TabError(lnum, pos, line) |
Predict the next line after this snippet: <|code_start|> pos = end = endmatch
tok = (tokens.STRING, contstr + line[:end], strstart[0],
strstart[1], line)
token_list.append(tok)
last_comment = ''
contstr, needcont = '', 0
contline = None
elif (needcont and not line.endswith('\\\n') and
not line.endswith('\\\r\n')):
tok = (tokens.ERRORTOKEN, contstr + line, strstart[0],
strstart[1], line)
token_list.append(tok)
last_comment = ''
contstr = ''
contline = None
continue
else:
contstr = contstr + line
contline = contline + line
continue
elif parenlev == 0 and not continued: # new statement
if not line: break
column = 0
altcolumn = 0
while pos < max: # measure leading whitespace
if line[pos] == ' ':
column = column + 1
altcolumn = altcolumn + 1
elif line[pos] == '\t':
<|code_end|>
using the current file's imports:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and any relevant context from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | column = (column/tabsize + 1)*tabsize |
Given the following code snippet before the placeholder: <|code_start|> tok = (tokens.STRING, contstr + line[:end], strstart[0],
strstart[1], line)
token_list.append(tok)
last_comment = ''
contstr, needcont = '', 0
contline = None
elif (needcont and not line.endswith('\\\n') and
not line.endswith('\\\r\n')):
tok = (tokens.ERRORTOKEN, contstr + line, strstart[0],
strstart[1], line)
token_list.append(tok)
last_comment = ''
contstr = ''
contline = None
continue
else:
contstr = contstr + line
contline = contline + line
continue
elif parenlev == 0 and not continued: # new statement
if not line: break
column = 0
altcolumn = 0
while pos < max: # measure leading whitespace
if line[pos] == ' ':
column = column + 1
altcolumn = altcolumn + 1
elif line[pos] == '\t':
column = (column/tabsize + 1)*tabsize
<|code_end|>
, predict the next line using imports from the current file:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context including class names, function names, and sometimes code from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | altcolumn = (altcolumn/alttabsize + 1)*alttabsize |
Next line prediction: <|code_start|> indents.append(column)
altindents.append(altcolumn)
token_list.append((tokens.INDENT, line[:pos], lnum, 0, line))
last_comment = ''
else:
while column < indents[-1]:
indents = indents[:-1]
altindents = altindents[:-1]
token_list.append((tokens.DEDENT, '', lnum, pos, line))
last_comment = ''
if column != indents[-1]:
err = "unindent does not match any outer indentation level"
raise TokenIndentationError(err, line, lnum, 0, token_list)
if altcolumn != altindents[-1]:
raise TabError(lnum, pos, line)
else: # continued statement
if not line:
if parenlev > 0:
lnum1, start1, line1 = parenlevstart
raise TokenError("parenthesis is never closed", line1,
lnum1, start1 + 1, token_list, lnum)
raise TokenError("EOF in multi-line statement", line,
lnum, 0, token_list)
continued = 0
while pos < max:
pseudomatch = pseudoDFA.recognize(line, pos)
if pseudomatch >= 0: # scan for tokens
# JDR: Modified
<|code_end|>
. Use current file imports:
(from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier)
and context including class names, function names, or small code snippets from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | start = whiteSpaceDFA.recognize(line, pos) |
Predict the next line after this snippet: <|code_start|> continued = 0
while pos < max:
pseudomatch = pseudoDFA.recognize(line, pos)
if pseudomatch >= 0: # scan for tokens
# JDR: Modified
start = whiteSpaceDFA.recognize(line, pos)
if start < 0:
start = pos
end = pseudomatch
if start == end:
raise TokenError("Unknown character", line,
lnum, start + 1, token_list)
pos = end
token, initial = line[start:end], line[start]
if (initial in numchars or \
(initial == '.' and token != '.' and token != '...')):
# ordinary number
token_list.append((tokens.NUMBER, token, lnum, start, line))
last_comment = ''
elif initial in '\r\n':
if parenlev <= 0:
tok = (tokens.NEWLINE, last_comment, lnum, start, line)
token_list.append(tok)
last_comment = ''
elif initial == '#':
# skip comment
last_comment = token
<|code_end|>
using the current file's imports:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and any relevant context from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | elif token in triple_quoted: |
Given snippet: <|code_start|>
while pos < max:
pseudomatch = pseudoDFA.recognize(line, pos)
if pseudomatch >= 0: # scan for tokens
# JDR: Modified
start = whiteSpaceDFA.recognize(line, pos)
if start < 0:
start = pos
end = pseudomatch
if start == end:
raise TokenError("Unknown character", line,
lnum, start + 1, token_list)
pos = end
token, initial = line[start:end], line[start]
if (initial in numchars or \
(initial == '.' and token != '.' and token != '...')):
# ordinary number
token_list.append((tokens.NUMBER, token, lnum, start, line))
last_comment = ''
elif initial in '\r\n':
if parenlev <= 0:
tok = (tokens.NEWLINE, last_comment, lnum, start, line)
token_list.append(tok)
last_comment = ''
elif initial == '#':
# skip comment
last_comment = token
elif token in triple_quoted:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
which might include code, classes, or functions. Output only the next line. | endDFA = endDFAs[token] |
Given the code snippet: <|code_start|>
pos = end
token, initial = line[start:end], line[start]
if (initial in numchars or \
(initial == '.' and token != '.' and token != '...')):
# ordinary number
token_list.append((tokens.NUMBER, token, lnum, start, line))
last_comment = ''
elif initial in '\r\n':
if parenlev <= 0:
tok = (tokens.NEWLINE, last_comment, lnum, start, line)
token_list.append(tok)
last_comment = ''
elif initial == '#':
# skip comment
last_comment = token
elif token in triple_quoted:
endDFA = endDFAs[token]
endmatch = endDFA.recognize(line, pos)
if endmatch >= 0: # all on one line
pos = endmatch
token = line[start:pos]
tok = (tokens.STRING, token, lnum, start, line)
token_list.append(tok)
last_comment = ''
else:
strstart = (lnum, start, line)
contstr = line[start:]
contline = line
break
<|code_end|>
, generate the next line using the imports in this file:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context (functions, classes, or occasionally code) from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | elif initial in single_quoted or \ |
Next line prediction: <|code_start|> elif column > indents[-1]: # count indents or dedents
if altcolumn <= altindents[-1]:
raise TabError(lnum, pos, line)
indents.append(column)
altindents.append(altcolumn)
token_list.append((tokens.INDENT, line[:pos], lnum, 0, line))
last_comment = ''
else:
while column < indents[-1]:
indents = indents[:-1]
altindents = altindents[:-1]
token_list.append((tokens.DEDENT, '', lnum, pos, line))
last_comment = ''
if column != indents[-1]:
err = "unindent does not match any outer indentation level"
raise TokenIndentationError(err, line, lnum, 0, token_list)
if altcolumn != altindents[-1]:
raise TabError(lnum, pos, line)
else: # continued statement
if not line:
if parenlev > 0:
lnum1, start1, line1 = parenlevstart
raise TokenError("parenthesis is never closed", line1,
lnum1, start1 + 1, token_list, lnum)
raise TokenError("EOF in multi-line statement", line,
lnum, 0, token_list)
continued = 0
while pos < max:
<|code_end|>
. Use current file imports:
(from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier)
and context including class names, function names, or small code snippets from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | pseudomatch = pseudoDFA.recognize(line, pos) |
Predict the next line for this snippet: <|code_start|> continued = 1
else:
if initial in '([{':
if parenlev == 0:
parenlevstart = (lnum, start, line)
parenlev = parenlev + 1
elif initial in ')]}':
parenlev = parenlev - 1
if parenlev < 0:
raise TokenError("unmatched '%s'" % initial, line,
lnum, start + 1, token_list)
if token in python_opmap:
punct = python_opmap[token]
else:
punct = tokens.OP
token_list.append((punct, token, lnum, start, line))
last_comment = ''
else:
start = whiteSpaceDFA.recognize(line, pos)
if start < 0:
start = pos
if start<max and line[start] in single_quoted:
raise TokenError("EOL while scanning string literal",
line, lnum, start+1, token_list)
tok = (tokens.ERRORTOKEN, line[pos], lnum, pos, line)
token_list.append(tok)
last_comment = ''
pos = pos + 1
lnum -= 1
<|code_end|>
with the help of current file imports:
from ayrton.parser.pyparser import automata
from ayrton.parser.pyparser.pygram import tokens
from ayrton.parser.pyparser.pytoken import python_opmap
from ayrton.parser.pyparser.error import TokenError, TokenIndentationError, TabError
from ayrton.parser.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
triple_quoted, endDFAs, single_quoted, pseudoDFA
from ayrton.parser.astcompiler import consts
from pypy.objspace.std.unicodeobject import _isidentifier
and context from other files:
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/pytoken.py
# def _add_tok(name, *values):
#
# Path: ayrton/parser/pyparser/error.py
# class TokenError(SyntaxError):
#
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# SyntaxError.__init__(self, msg, lineno, column, line,
# lastlineno=lastlineno)
# self.tokens = tokens
#
# class TokenIndentationError(IndentationError):
#
# def __init__(self, msg, line, lineno, column, tokens):
# SyntaxError.__init__(self, msg, lineno, column, line)
# self.tokens = tokens
#
# class TabError(IndentationError):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# msg = "inconsistent use of tabs and spaces in indentation"
# IndentationError.__init__(self, msg, lineno, offset, text, filename, lastlineno)
#
# Path: ayrton/parser/pyparser/pytokenize.py
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
, which may contain function names, class names, or code. Output only the next line. | if not (flags & consts.PyCF_DONT_IMPLY_DEDENT): |
Given the following code snippet before the placeholder: <|code_start|> self.doTest('testZEmptyString.ay', True)
def testZNone(self):
self.doTest('testZNone.ay', True)
def testZString(self):
self.doTest('testZString.ay', False)
def testZInt(self):
self.doTest('testZInt.ay', False)
def testZEnvVar(self):
self.doTest('testZEnvVar.ay', False)
def testDefine(self):
self.doTest('testDefine.ay', None)
def testDefine(self):
self.doTest('testDefineValue.ay', 6)
def testDefineAgain(self):
self.doTest('testDefineAgain.ay', False)
class CommandDetection (ScriptExecution):
def testSimpleCase (self):
self.doTest ('testSimpleCase.ay')
def testSimpleCaseFails (self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import sys
import io
import os
import tempfile
import os.path
import ayrton
import logging
from ayrton.expansion import bash, default
from ayrton.execute import CommandNotFound
and context including class names, function names, and sometimes code from other files:
# Path: ayrton/expansion.py
# def bash (s, single=False):
# data= backslash_descape (glob_expand (tilde_expand (brace_expand (s))))
# if single and len(data)==1:
# data= data[0]
# return data
#
# def default (parameter, word):
# ans= get_var (parameter)
#
# if is_null (ans):
# ans= word
#
# # according to bash's manpage, default's second parameter should be expanded
# # but tests have shown that it is not so
# return ans
#
# Path: ayrton/execute.py
# class CommandNotFound (NameError):
# def __init__ (self, name):
# self.name= name
#
# def __str__ (self):
# return "CommandNotFound or NameError: command %(name)s not found or name %(name)s is not defined" % self.__dict__
. Output only the next line. | self.assertRaises (CommandNotFound, self.doTest, |
Next line prediction: <|code_start|> node = ast.Str if is_unicode else ast.Bytes
new_node = node(w_string)
new_node.lineno = atom_node.lineno
new_node.col_offset = atom_node.col_offset
joined_pieces.append(new_node)
def f_constant_string(astbuilder, joined_pieces, u, atom_node):
add_constant_string(astbuilder, joined_pieces, u, atom_node)
def f_string_compile(astbuilder, source, atom_node):
# Note: a f-string is kept as a single literal up to here.
# At this point only, we recursively call the AST compiler
# on all the '{expr}' parts. The 'expr' part is not parsed
# or even tokenized together with the rest of the source code!
# complain if 'source' is only whitespace or an empty string
for c in source:
if c not in ' \t\n\r\v\f':
break
else:
astbuilder.error("f-string: empty expression not allowed", atom_node)
if astbuilder.recursive_parser is None:
astbuilder.error("internal error: parser not available for parsing "
"the expressions inside the f-string", atom_node)
assert isinstance(source, str) # utf-8 encoded
source = '(%s)' % source
info = pyparse.CompileInfo("<fstring>", "eval",
<|code_end|>
. Use current file imports:
(from ayrton.parser.astcompiler import consts
from ayrton.parser.pyparser import parsestring
from ayrton.parser import error
from ayrton.parser.pyparser import pyparse
from ayrton.parser.astcompiler.astbuilder import ast_from_node
import ast)
and context including class names, function names, or small code snippets from other files:
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | consts.PyCF_SOURCE_IS_UTF8 | |
Using the snippet: <|code_start|> import.
* hidden_applevel: Will this code unit and sub units be hidden at the
applevel?
* optimize: optimization level:
-1 = same as interpreter,
0 = no optmiziation,
1 = remove asserts,
2 = remove docstrings.
"""
def __init__(self, filename, mode="exec", flags=0, future_pos=(0, 0),
hidden_applevel=False, optimize=-1):
check_str0(filename)
self.filename = filename
self.mode = mode
self.encoding = None
self.flags = flags
self.optimize = optimize
self.last_future_import = future_pos
self.hidden_applevel = hidden_applevel
_targets = {
'eval' : pygram.syms.eval_input,
'single' : pygram.syms.single_input,
'exec' : pygram.syms.file_input,
}
class PythonParser(parser.Parser):
<|code_end|>
, determine the next line of code. You have imports:
from ayrton.parser.error import OperationError
from ayrton.parser.pyparser import future, parser, pytokenizer, pygram, error
from ayrton.parser.astcompiler import consts
and context (class names, function names, or code) available:
# Path: ayrton/parser/pyparser/future.py
# class FutureFlags(object):
# class TokenIterator:
# def __init__(self, version):
# def get_flag_names(self, space, flags):
# def get_compiler_feature(self, name):
# def __init__(self, tokens):
# def next(self):
# def skip(self, n):
# def skip_name(self, name):
# def next_feature_name(self):
# def skip_newlines(self):
# def add_future_flags(future_flags, tokens):
#
# Path: ayrton/parser/pyparser/parser.py
# class Grammar(object):
# class Node(object):
# class ParseError(Exception):
# class Parser(object):
# def __init__(self):
# def shared_copy(self):
# def _freeze_(self):
# def __init__(self, type, value, children, lineno, column):
# def __eq__(self, other):
# def __repr__(self):
# def __init__(self, msg, token_type, value, lineno, column, line,
# expected=-1):
# def __str__(self):
# def __init__(self, grammar):
# def prepare(self, start=-1):
# def add_token(self, token_type, value, lineno, column, line):
# def classify(self, token_type, value, lineno, column, line):
# def shift(self, next_state, token_type, value, lineno, column):
# def push(self, next_dfa, next_state, node_type, lineno, column):
# def pop(self):
#
# Path: ayrton/parser/pyparser/pytokenizer.py
# NAMECHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
# NUMCHARS = '0123456789'
# ALNUMCHARS = NAMECHARS + NUMCHARS
# EXTENDED_ALNUMCHARS = ALNUMCHARS + '-.'
# WHITESPACES = ' \t\n\r\v\f'
# def match_encoding_declaration(comment):
# def verify_identifier(token):
# def generate_tokens(lines, flags):
#
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/error.py
# class SyntaxError(Exception):
# class IndentationError(SyntaxError):
# class TabError(IndentationError):
# class ASTError(Exception):
# class TokenError(SyntaxError):
# class TokenIndentationError(IndentationError):
# def __init__(self, msg, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def wrap_info(self, space):
# def __str__(self):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def __init__(self, msg, ast_node ):
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# def __init__(self, msg, line, lineno, column, tokens):
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | def __init__(self, space, future_flags=future.futureFlags_3_5, |
Based on the snippet: <|code_start|> * encoding: The source encoding.
* last_future_import: The line number and offset of the last __future__
import.
* hidden_applevel: Will this code unit and sub units be hidden at the
applevel?
* optimize: optimization level:
-1 = same as interpreter,
0 = no optmiziation,
1 = remove asserts,
2 = remove docstrings.
"""
def __init__(self, filename, mode="exec", flags=0, future_pos=(0, 0),
hidden_applevel=False, optimize=-1):
check_str0(filename)
self.filename = filename
self.mode = mode
self.encoding = None
self.flags = flags
self.optimize = optimize
self.last_future_import = future_pos
self.hidden_applevel = hidden_applevel
_targets = {
'eval' : pygram.syms.eval_input,
'single' : pygram.syms.single_input,
'exec' : pygram.syms.file_input,
}
<|code_end|>
, predict the immediate next line with the help of imports:
from ayrton.parser.error import OperationError
from ayrton.parser.pyparser import future, parser, pytokenizer, pygram, error
from ayrton.parser.astcompiler import consts
and context (classes, functions, sometimes code) from other files:
# Path: ayrton/parser/pyparser/future.py
# class FutureFlags(object):
# class TokenIterator:
# def __init__(self, version):
# def get_flag_names(self, space, flags):
# def get_compiler_feature(self, name):
# def __init__(self, tokens):
# def next(self):
# def skip(self, n):
# def skip_name(self, name):
# def next_feature_name(self):
# def skip_newlines(self):
# def add_future_flags(future_flags, tokens):
#
# Path: ayrton/parser/pyparser/parser.py
# class Grammar(object):
# class Node(object):
# class ParseError(Exception):
# class Parser(object):
# def __init__(self):
# def shared_copy(self):
# def _freeze_(self):
# def __init__(self, type, value, children, lineno, column):
# def __eq__(self, other):
# def __repr__(self):
# def __init__(self, msg, token_type, value, lineno, column, line,
# expected=-1):
# def __str__(self):
# def __init__(self, grammar):
# def prepare(self, start=-1):
# def add_token(self, token_type, value, lineno, column, line):
# def classify(self, token_type, value, lineno, column, line):
# def shift(self, next_state, token_type, value, lineno, column):
# def push(self, next_dfa, next_state, node_type, lineno, column):
# def pop(self):
#
# Path: ayrton/parser/pyparser/pytokenizer.py
# NAMECHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
# NUMCHARS = '0123456789'
# ALNUMCHARS = NAMECHARS + NUMCHARS
# EXTENDED_ALNUMCHARS = ALNUMCHARS + '-.'
# WHITESPACES = ' \t\n\r\v\f'
# def match_encoding_declaration(comment):
# def verify_identifier(token):
# def generate_tokens(lines, flags):
#
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/error.py
# class SyntaxError(Exception):
# class IndentationError(SyntaxError):
# class TabError(IndentationError):
# class ASTError(Exception):
# class TokenError(SyntaxError):
# class TokenIndentationError(IndentationError):
# def __init__(self, msg, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def wrap_info(self, space):
# def __str__(self):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def __init__(self, msg, ast_node ):
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# def __init__(self, msg, line, lineno, column, tokens):
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | class PythonParser(parser.Parser): |
Using the snippet: <|code_start|> return 'utf-8'
for variant in ['latin-1', 'iso-latin-1', 'iso-8859-1']:
if (encoding == variant or
encoding.startswith(variant + '-')):
return 'iso-8859-1'
return encoding
def _check_for_encoding(b):
"""You can use a different encoding from UTF-8 by putting a specially-formatted
comment as the first or second line of the source code."""
eol = b.find(b'\n')
if eol < 0:
return _check_line_for_encoding(b)[0]
enc, again = _check_line_for_encoding(b[:eol])
if enc or not again:
return enc
eol2 = b.find(b'\n', eol + 1)
if eol2 < 0:
return _check_line_for_encoding(b[eol + 1:])[0]
return _check_line_for_encoding(b[eol + 1:eol2])[0]
def _check_line_for_encoding(line):
"""returns the declared encoding or None"""
i = 0
for i in range(len(line)):
if line[i] == b'#':
break
if line[i] not in b' \t\014':
return None, False # Not a comment, don't read the second line.
<|code_end|>
, determine the next line of code. You have imports:
from ayrton.parser.error import OperationError
from ayrton.parser.pyparser import future, parser, pytokenizer, pygram, error
from ayrton.parser.astcompiler import consts
and context (class names, function names, or code) available:
# Path: ayrton/parser/pyparser/future.py
# class FutureFlags(object):
# class TokenIterator:
# def __init__(self, version):
# def get_flag_names(self, space, flags):
# def get_compiler_feature(self, name):
# def __init__(self, tokens):
# def next(self):
# def skip(self, n):
# def skip_name(self, name):
# def next_feature_name(self):
# def skip_newlines(self):
# def add_future_flags(future_flags, tokens):
#
# Path: ayrton/parser/pyparser/parser.py
# class Grammar(object):
# class Node(object):
# class ParseError(Exception):
# class Parser(object):
# def __init__(self):
# def shared_copy(self):
# def _freeze_(self):
# def __init__(self, type, value, children, lineno, column):
# def __eq__(self, other):
# def __repr__(self):
# def __init__(self, msg, token_type, value, lineno, column, line,
# expected=-1):
# def __str__(self):
# def __init__(self, grammar):
# def prepare(self, start=-1):
# def add_token(self, token_type, value, lineno, column, line):
# def classify(self, token_type, value, lineno, column, line):
# def shift(self, next_state, token_type, value, lineno, column):
# def push(self, next_dfa, next_state, node_type, lineno, column):
# def pop(self):
#
# Path: ayrton/parser/pyparser/pytokenizer.py
# NAMECHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
# NUMCHARS = '0123456789'
# ALNUMCHARS = NAMECHARS + NUMCHARS
# EXTENDED_ALNUMCHARS = ALNUMCHARS + '-.'
# WHITESPACES = ' \t\n\r\v\f'
# def match_encoding_declaration(comment):
# def verify_identifier(token):
# def generate_tokens(lines, flags):
#
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/error.py
# class SyntaxError(Exception):
# class IndentationError(SyntaxError):
# class TabError(IndentationError):
# class ASTError(Exception):
# class TokenError(SyntaxError):
# class TokenIndentationError(IndentationError):
# def __init__(self, msg, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def wrap_info(self, space):
# def __str__(self):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def __init__(self, msg, ast_node ):
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# def __init__(self, msg, line, lineno, column, tokens):
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | return pytokenizer.match_encoding_declaration(line[i:]), True |
Next line prediction: <|code_start|> """Stores information about the source being compiled.
* filename: The filename of the source.
* mode: The parse mode to use. ('exec', 'eval', or 'single')
* flags: Parser and compiler flags.
* encoding: The source encoding.
* last_future_import: The line number and offset of the last __future__
import.
* hidden_applevel: Will this code unit and sub units be hidden at the
applevel?
* optimize: optimization level:
-1 = same as interpreter,
0 = no optmiziation,
1 = remove asserts,
2 = remove docstrings.
"""
def __init__(self, filename, mode="exec", flags=0, future_pos=(0, 0),
hidden_applevel=False, optimize=-1):
check_str0(filename)
self.filename = filename
self.mode = mode
self.encoding = None
self.flags = flags
self.optimize = optimize
self.last_future_import = future_pos
self.hidden_applevel = hidden_applevel
_targets = {
<|code_end|>
. Use current file imports:
(from ayrton.parser.error import OperationError
from ayrton.parser.pyparser import future, parser, pytokenizer, pygram, error
from ayrton.parser.astcompiler import consts)
and context including class names, function names, or small code snippets from other files:
# Path: ayrton/parser/pyparser/future.py
# class FutureFlags(object):
# class TokenIterator:
# def __init__(self, version):
# def get_flag_names(self, space, flags):
# def get_compiler_feature(self, name):
# def __init__(self, tokens):
# def next(self):
# def skip(self, n):
# def skip_name(self, name):
# def next_feature_name(self):
# def skip_newlines(self):
# def add_future_flags(future_flags, tokens):
#
# Path: ayrton/parser/pyparser/parser.py
# class Grammar(object):
# class Node(object):
# class ParseError(Exception):
# class Parser(object):
# def __init__(self):
# def shared_copy(self):
# def _freeze_(self):
# def __init__(self, type, value, children, lineno, column):
# def __eq__(self, other):
# def __repr__(self):
# def __init__(self, msg, token_type, value, lineno, column, line,
# expected=-1):
# def __str__(self):
# def __init__(self, grammar):
# def prepare(self, start=-1):
# def add_token(self, token_type, value, lineno, column, line):
# def classify(self, token_type, value, lineno, column, line):
# def shift(self, next_state, token_type, value, lineno, column):
# def push(self, next_dfa, next_state, node_type, lineno, column):
# def pop(self):
#
# Path: ayrton/parser/pyparser/pytokenizer.py
# NAMECHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
# NUMCHARS = '0123456789'
# ALNUMCHARS = NAMECHARS + NUMCHARS
# EXTENDED_ALNUMCHARS = ALNUMCHARS + '-.'
# WHITESPACES = ' \t\n\r\v\f'
# def match_encoding_declaration(comment):
# def verify_identifier(token):
# def generate_tokens(lines, flags):
#
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/error.py
# class SyntaxError(Exception):
# class IndentationError(SyntaxError):
# class TabError(IndentationError):
# class ASTError(Exception):
# class TokenError(SyntaxError):
# class TokenIndentationError(IndentationError):
# def __init__(self, msg, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def wrap_info(self, space):
# def __str__(self):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def __init__(self, msg, ast_node ):
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# def __init__(self, msg, line, lineno, column, tokens):
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | 'eval' : pygram.syms.eval_input, |
Given the code snippet: <|code_start|>'exec' : pygram.syms.file_input,
}
class PythonParser(parser.Parser):
def __init__(self, space, future_flags=future.futureFlags_3_5,
grammar=pygram.python_grammar):
parser.Parser.__init__(self, grammar)
self.space = space
self.future_flags = future_flags
def parse_source(self, bytessrc, compile_info):
"""Main entry point for parsing Python source.
Everything from decoding the source to tokenizing to building the parse
tree is handled here.
"""
# Detect source encoding.
enc = None
if compile_info.flags & consts.PyCF_SOURCE_IS_UTF8:
enc = 'utf-8'
if compile_info.flags & consts.PyCF_IGNORE_COOKIE:
textsrc = bytessrc
elif bytessrc.startswith(b"\xEF\xBB\xBF"):
bytessrc = bytessrc[3:]
enc = 'utf-8'
# If an encoding is explicitly given check that it is utf-8.
decl_enc = _check_for_encoding(bytessrc)
if decl_enc and decl_enc != "utf-8":
<|code_end|>
, generate the next line using the imports in this file:
from ayrton.parser.error import OperationError
from ayrton.parser.pyparser import future, parser, pytokenizer, pygram, error
from ayrton.parser.astcompiler import consts
and context (functions, classes, or occasionally code) from other files:
# Path: ayrton/parser/pyparser/future.py
# class FutureFlags(object):
# class TokenIterator:
# def __init__(self, version):
# def get_flag_names(self, space, flags):
# def get_compiler_feature(self, name):
# def __init__(self, tokens):
# def next(self):
# def skip(self, n):
# def skip_name(self, name):
# def next_feature_name(self):
# def skip_newlines(self):
# def add_future_flags(future_flags, tokens):
#
# Path: ayrton/parser/pyparser/parser.py
# class Grammar(object):
# class Node(object):
# class ParseError(Exception):
# class Parser(object):
# def __init__(self):
# def shared_copy(self):
# def _freeze_(self):
# def __init__(self, type, value, children, lineno, column):
# def __eq__(self, other):
# def __repr__(self):
# def __init__(self, msg, token_type, value, lineno, column, line,
# expected=-1):
# def __str__(self):
# def __init__(self, grammar):
# def prepare(self, start=-1):
# def add_token(self, token_type, value, lineno, column, line):
# def classify(self, token_type, value, lineno, column, line):
# def shift(self, next_state, token_type, value, lineno, column):
# def push(self, next_dfa, next_state, node_type, lineno, column):
# def pop(self):
#
# Path: ayrton/parser/pyparser/pytokenizer.py
# NAMECHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
# NUMCHARS = '0123456789'
# ALNUMCHARS = NAMECHARS + NUMCHARS
# EXTENDED_ALNUMCHARS = ALNUMCHARS + '-.'
# WHITESPACES = ' \t\n\r\v\f'
# def match_encoding_declaration(comment):
# def verify_identifier(token):
# def generate_tokens(lines, flags):
#
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/error.py
# class SyntaxError(Exception):
# class IndentationError(SyntaxError):
# class TabError(IndentationError):
# class ASTError(Exception):
# class TokenError(SyntaxError):
# class TokenIndentationError(IndentationError):
# def __init__(self, msg, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def wrap_info(self, space):
# def __str__(self):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def __init__(self, msg, ast_node ):
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# def __init__(self, msg, line, lineno, column, tokens):
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
. Output only the next line. | raise error.SyntaxError("UTF-8 BOM with %s coding cookie" % decl_enc, |
Predict the next line for this snippet: <|code_start|> self.mode = mode
self.encoding = None
self.flags = flags
self.optimize = optimize
self.last_future_import = future_pos
self.hidden_applevel = hidden_applevel
_targets = {
'eval' : pygram.syms.eval_input,
'single' : pygram.syms.single_input,
'exec' : pygram.syms.file_input,
}
class PythonParser(parser.Parser):
def __init__(self, space, future_flags=future.futureFlags_3_5,
grammar=pygram.python_grammar):
parser.Parser.__init__(self, grammar)
self.space = space
self.future_flags = future_flags
def parse_source(self, bytessrc, compile_info):
"""Main entry point for parsing Python source.
Everything from decoding the source to tokenizing to building the parse
tree is handled here.
"""
# Detect source encoding.
enc = None
<|code_end|>
with the help of current file imports:
from ayrton.parser.error import OperationError
from ayrton.parser.pyparser import future, parser, pytokenizer, pygram, error
from ayrton.parser.astcompiler import consts
and context from other files:
# Path: ayrton/parser/pyparser/future.py
# class FutureFlags(object):
# class TokenIterator:
# def __init__(self, version):
# def get_flag_names(self, space, flags):
# def get_compiler_feature(self, name):
# def __init__(self, tokens):
# def next(self):
# def skip(self, n):
# def skip_name(self, name):
# def next_feature_name(self):
# def skip_newlines(self):
# def add_future_flags(future_flags, tokens):
#
# Path: ayrton/parser/pyparser/parser.py
# class Grammar(object):
# class Node(object):
# class ParseError(Exception):
# class Parser(object):
# def __init__(self):
# def shared_copy(self):
# def _freeze_(self):
# def __init__(self, type, value, children, lineno, column):
# def __eq__(self, other):
# def __repr__(self):
# def __init__(self, msg, token_type, value, lineno, column, line,
# expected=-1):
# def __str__(self):
# def __init__(self, grammar):
# def prepare(self, start=-1):
# def add_token(self, token_type, value, lineno, column, line):
# def classify(self, token_type, value, lineno, column, line):
# def shift(self, next_state, token_type, value, lineno, column):
# def push(self, next_dfa, next_state, node_type, lineno, column):
# def pop(self):
#
# Path: ayrton/parser/pyparser/pytokenizer.py
# NAMECHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
# NUMCHARS = '0123456789'
# ALNUMCHARS = NAMECHARS + NUMCHARS
# EXTENDED_ALNUMCHARS = ALNUMCHARS + '-.'
# WHITESPACES = ' \t\n\r\v\f'
# def match_encoding_declaration(comment):
# def verify_identifier(token):
# def generate_tokens(lines, flags):
#
# Path: ayrton/parser/pyparser/pygram.py
# class PythonGrammar(parser.Grammar):
# class _Tokens(object):
# class _Symbols(object):
# KEYWORD_TOKEN = pytoken.python_tokens["NAME"]
# TOKENS = pytoken.python_tokens
# OPERATOR_MAP = pytoken.python_opmap
# def _get_python_grammar():
#
# Path: ayrton/parser/pyparser/error.py
# class SyntaxError(Exception):
# class IndentationError(SyntaxError):
# class TabError(IndentationError):
# class ASTError(Exception):
# class TokenError(SyntaxError):
# class TokenIndentationError(IndentationError):
# def __init__(self, msg, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def wrap_info(self, space):
# def __str__(self):
# def __init__(self, lineno=0, offset=0, text=None, filename=None,
# lastlineno=0):
# def __init__(self, msg, ast_node ):
# def __init__(self, msg, line, lineno, column, tokens, lastlineno=0):
# def __init__(self, msg, line, lineno, column, tokens):
#
# Path: ayrton/parser/astcompiler/consts.py
# CO_OPTIMIZED = 0x0001
# CO_NEWLOCALS = 0x0002
# CO_VARARGS = 0x0004
# CO_VARKEYWORDS = 0x0008
# CO_NESTED = 0x0010
# CO_GENERATOR = 0x0020
# CO_NOFREE = 0x0040
# CO_COROUTINE = 0x0080
# CO_ITERABLE_COROUTINE = 0x0100 # set by @types.coroutine
# CO_GENERATOR_ALLOWED = 0x1000
# CO_FUTURE_DIVISION = 0x2000
# CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
# CO_FUTURE_WITH_STATEMENT = 0x8000
# CO_FUTURE_PRINT_FUNCTION = 0x10000
# CO_FUTURE_UNICODE_LITERALS = 0x20000
# CO_FUTURE_BARRY_AS_BDFL = 0x40000
# CO_FUTURE_GENERATOR_STOP = 0x80000
# CO_KILL_DOCSTRING = 0x100000
# CO_YIELD_INSIDE_TRY = 0x200000
# FVC_MASK = 0x3
# FVC_NONE = 0x0
# FVC_STR = 0x1
# FVC_REPR = 0x2
# FVC_ASCII = 0x3
# FVS_MASK = 0x4
# FVS_HAVE_SPEC = 0x4
, which may contain function names, class names, or code. Output only the next line. | if compile_info.flags & consts.PyCF_SOURCE_IS_UTF8: |
Here is a snippet: <|code_start|>
register = template.Library()
@register.simple_tag
def bounty_total():
<|code_end|>
. Write the next line using the current file imports:
from django import template
from website.models import Payment
from django.db.models import Sum
and context from other files:
# Path: website/models.py
# class Payment(models.Model):
# issue = models.ForeignKey(Issue, on_delete=models.CASCADE)
# solution = models.ForeignKey(Solution, on_delete=models.CASCADE)
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# amount = models.DecimalField(max_digits=10, decimal_places=0)
# txn_id = models.CharField(max_length=255, blank=True, null=True)
# created = models.DateTimeField()
# updated = models.DateTimeField()
, which may include functions, classes, or code. Output only the next line. | _total = Payment.objects.aggregate(Sum('amount'))['amount__sum'] |
Given the following code snippet before the placeholder: <|code_start|> if not getattr(self.generator, 'doxy_tar', None):
self.generator.add_install_files(install_to=self.generator.install_path,
install_from=self.outputs,
postpone=False,
cwd=self.output_dir,
relative_trick=True)
class tar(Task.Task):
"quick tar creation"
run_str = '${TAR} ${TAROPTS} ${TGT} ${SRC}'
color = 'RED'
after = ['doxygen']
def runnable_status(self):
for x in getattr(self, 'input_tasks', []):
if not x.hasrun:
return Task.ASK_LATER
if not getattr(self, 'tar_done_adding', None):
# execute this only once
self.tar_done_adding = True
for x in getattr(self, 'input_tasks', []):
self.set_inputs(x.outputs)
if not self.inputs:
return Task.SKIP_ME
return Task.Task.runnable_status(self)
def __str__(self):
tgt_str = ' '.join([a.path_from(a.ctx.launch_node()) for a in self.outputs])
return '%s: %s\n' % (self.__class__.__name__, tgt_str)
<|code_end|>
, predict the next line using imports from the current file:
import os, os.path, re
from collections import OrderedDict
from waflib import Task, Utils, Node
from waflib.TaskGen import feature
and context including class names, function names, and sometimes code from other files:
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
. Output only the next line. | @feature('doxygen') |
Next line prediction: <|code_start|> ltask = self.generator.link_task
except AttributeError:
pass
else:
ltask.set_run_after(c_tsk)
# setting input nodes does not declare the build order
# because the build already started, but it sets
# the dependency to enable rebuilds
ltask.inputs.append(c_tsk.outputs[0])
self.outputs.append(out_node)
if not '-o' in self.env['SWIGFLAGS']:
self.env.append_value('SWIGFLAGS', ['-o', self.outputs[0].abspath()])
@swigf
def swig_python(tsk):
node = tsk.inputs[0].parent
if tsk.outdir:
node = tsk.outdir
tsk.set_outputs(node.find_or_declare(tsk.module+'.py'))
@swigf
def swig_ocaml(tsk):
node = tsk.inputs[0].parent
if tsk.outdir:
node = tsk.outdir
tsk.set_outputs(node.find_or_declare(tsk.module+'.ml'))
tsk.set_outputs(node.find_or_declare(tsk.module+'.mli'))
<|code_end|>
. Use current file imports:
(import re
from waflib import Task, Logs
from waflib.TaskGen import extension, feature, after_method
from waflib.Configure import conf
from waflib.Tools import c_preproc)
and context including class names, function names, or small code snippets from other files:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/Tools/c_preproc.py
# class PreprocError(Errors.WafError):
# class c_parser(object):
# FILE_CACHE_SIZE = 100000
# LINE_CACHE_SIZE = 100000
# POPFILE = '-'
# NUM = 'i'
# OP = 'O'
# IDENT = 'T'
# STR = 's'
# CHAR = 'c'
# def repl(m):
# def reduce_nums(val_1, val_2, val_op):
# def get_num(lst):
# def get_term(lst):
# def reduce_eval(lst):
# def stringize(lst):
# def paste_tokens(t1, t2):
# def reduce_tokens(lst, defs, ban=[]):
# def eval_macro(lst, defs):
# def extract_macro(txt):
# def extract_include(txt, defs):
# def parse_char(txt):
# def tokenize(s):
# def tokenize_private(s):
# def format_defines(lst):
# def __init__(self, nodepaths=None, defines=None):
# def cached_find_resource(self, node, filename):
# def tryfind(self, filename, kind='"', env=None):
# def filter_comments(self, node):
# def parse_lines(self, node):
# def addlines(self, node):
# def start(self, node, env):
# def define_name(self, line):
# def scan(task):
. Output only the next line. | @extension(*SWIG_EXTS) |
Given the code snippet: <|code_start|> node = tsk.inputs[0].parent
if tsk.outdir:
node = tsk.outdir
tsk.set_outputs(node.find_or_declare(tsk.module+'.py'))
@swigf
def swig_ocaml(tsk):
node = tsk.inputs[0].parent
if tsk.outdir:
node = tsk.outdir
tsk.set_outputs(node.find_or_declare(tsk.module+'.ml'))
tsk.set_outputs(node.find_or_declare(tsk.module+'.mli'))
@extension(*SWIG_EXTS)
def i_file(self, node):
# the task instance
tsk = self.create_task('swig')
tsk.set_inputs(node)
tsk.module = getattr(self, 'swig_module', None)
flags = self.to_list(getattr(self, 'swig_flags', []))
tsk.env.append_value('SWIGFLAGS', flags)
tsk.outdir = None
if '-outdir' in flags:
outdir = flags[flags.index('-outdir')+1]
outdir = tsk.generator.bld.bldnode.make_node(outdir)
outdir.mkdir()
tsk.outdir = outdir
<|code_end|>
, generate the next line using the imports in this file:
import re
from waflib import Task, Logs
from waflib.TaskGen import extension, feature, after_method
from waflib.Configure import conf
from waflib.Tools import c_preproc
and context (functions, classes, or occasionally code) from other files:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/Tools/c_preproc.py
# class PreprocError(Errors.WafError):
# class c_parser(object):
# FILE_CACHE_SIZE = 100000
# LINE_CACHE_SIZE = 100000
# POPFILE = '-'
# NUM = 'i'
# OP = 'O'
# IDENT = 'T'
# STR = 's'
# CHAR = 'c'
# def repl(m):
# def reduce_nums(val_1, val_2, val_op):
# def get_num(lst):
# def get_term(lst):
# def reduce_eval(lst):
# def stringize(lst):
# def paste_tokens(t1, t2):
# def reduce_tokens(lst, defs, ban=[]):
# def eval_macro(lst, defs):
# def extract_macro(txt):
# def extract_include(txt, defs):
# def parse_char(txt):
# def tokenize(s):
# def tokenize_private(s):
# def format_defines(lst):
# def __init__(self, nodepaths=None, defines=None):
# def cached_find_resource(self, node, filename):
# def tryfind(self, filename, kind='"', env=None):
# def filter_comments(self, node):
# def parse_lines(self, node):
# def addlines(self, node):
# def start(self, node, env):
# def define_name(self, line):
# def scan(task):
. Output only the next line. | @feature('c', 'cxx', 'd', 'fc', 'asm') |
Based on the snippet: <|code_start|> if tsk.outdir:
node = tsk.outdir
tsk.set_outputs(node.find_or_declare(tsk.module+'.py'))
@swigf
def swig_ocaml(tsk):
node = tsk.inputs[0].parent
if tsk.outdir:
node = tsk.outdir
tsk.set_outputs(node.find_or_declare(tsk.module+'.ml'))
tsk.set_outputs(node.find_or_declare(tsk.module+'.mli'))
@extension(*SWIG_EXTS)
def i_file(self, node):
# the task instance
tsk = self.create_task('swig')
tsk.set_inputs(node)
tsk.module = getattr(self, 'swig_module', None)
flags = self.to_list(getattr(self, 'swig_flags', []))
tsk.env.append_value('SWIGFLAGS', flags)
tsk.outdir = None
if '-outdir' in flags:
outdir = flags[flags.index('-outdir')+1]
outdir = tsk.generator.bld.bldnode.make_node(outdir)
outdir.mkdir()
tsk.outdir = outdir
@feature('c', 'cxx', 'd', 'fc', 'asm')
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from waflib import Task, Logs
from waflib.TaskGen import extension, feature, after_method
from waflib.Configure import conf
from waflib.Tools import c_preproc
and context (classes, functions, sometimes code) from other files:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/Tools/c_preproc.py
# class PreprocError(Errors.WafError):
# class c_parser(object):
# FILE_CACHE_SIZE = 100000
# LINE_CACHE_SIZE = 100000
# POPFILE = '-'
# NUM = 'i'
# OP = 'O'
# IDENT = 'T'
# STR = 's'
# CHAR = 'c'
# def repl(m):
# def reduce_nums(val_1, val_2, val_op):
# def get_num(lst):
# def get_term(lst):
# def reduce_eval(lst):
# def stringize(lst):
# def paste_tokens(t1, t2):
# def reduce_tokens(lst, defs, ban=[]):
# def eval_macro(lst, defs):
# def extract_macro(txt):
# def extract_include(txt, defs):
# def parse_char(txt):
# def tokenize(s):
# def tokenize_private(s):
# def format_defines(lst):
# def __init__(self, nodepaths=None, defines=None):
# def cached_find_resource(self, node, filename):
# def tryfind(self, filename, kind='"', env=None):
# def filter_comments(self, node):
# def parse_lines(self, node):
# def addlines(self, node):
# def start(self, node, env):
# def define_name(self, line):
# def scan(task):
. Output only the next line. | @after_method('apply_link', 'process_source') |
Here is a snippet: <|code_start|>
@extension(*SWIG_EXTS)
def i_file(self, node):
# the task instance
tsk = self.create_task('swig')
tsk.set_inputs(node)
tsk.module = getattr(self, 'swig_module', None)
flags = self.to_list(getattr(self, 'swig_flags', []))
tsk.env.append_value('SWIGFLAGS', flags)
tsk.outdir = None
if '-outdir' in flags:
outdir = flags[flags.index('-outdir')+1]
outdir = tsk.generator.bld.bldnode.make_node(outdir)
outdir.mkdir()
tsk.outdir = outdir
@feature('c', 'cxx', 'd', 'fc', 'asm')
@after_method('apply_link', 'process_source')
def enforce_swig_before_link(self):
try:
link_task = self.link_task
except AttributeError:
pass
else:
for x in self.tasks:
if x.__class__.__name__ == 'swig':
link_task.run_after.add(x)
<|code_end|>
. Write the next line using the current file imports:
import re
from waflib import Task, Logs
from waflib.TaskGen import extension, feature, after_method
from waflib.Configure import conf
from waflib.Tools import c_preproc
and context from other files:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/Tools/c_preproc.py
# class PreprocError(Errors.WafError):
# class c_parser(object):
# FILE_CACHE_SIZE = 100000
# LINE_CACHE_SIZE = 100000
# POPFILE = '-'
# NUM = 'i'
# OP = 'O'
# IDENT = 'T'
# STR = 's'
# CHAR = 'c'
# def repl(m):
# def reduce_nums(val_1, val_2, val_op):
# def get_num(lst):
# def get_term(lst):
# def reduce_eval(lst):
# def stringize(lst):
# def paste_tokens(t1, t2):
# def reduce_tokens(lst, defs, ban=[]):
# def eval_macro(lst, defs):
# def extract_macro(txt):
# def extract_include(txt, defs):
# def parse_char(txt):
# def tokenize(s):
# def tokenize_private(s):
# def format_defines(lst):
# def __init__(self, nodepaths=None, defines=None):
# def cached_find_resource(self, node, filename):
# def tryfind(self, filename, kind='"', env=None):
# def filter_comments(self, node):
# def parse_lines(self, node):
# def addlines(self, node):
# def start(self, node, env):
# def define_name(self, line):
# def scan(task):
, which may include functions, classes, or code. Output only the next line. | @conf |
Using the snippet: <|code_start|> # call funs in the dict swig_langs
for x in self.env['SWIGFLAGS']:
# obtain the language
x = x[1:]
try:
fun = swig_langs[x]
except KeyError:
pass
else:
fun(self)
return super(swig, self).runnable_status()
def scan(self):
"scan for swig dependencies, climb the .i files"
lst_src = []
seen = []
missing = []
to_see = [self.inputs[0]]
while to_see:
node = to_see.pop(0)
if node in seen:
continue
seen.append(node)
lst_src.append(node)
# read the file
code = node.read()
<|code_end|>
, determine the next line of code. You have imports:
import re
from waflib import Task, Logs
from waflib.TaskGen import extension, feature, after_method
from waflib.Configure import conf
from waflib.Tools import c_preproc
and context (class names, function names, or code) available:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/Tools/c_preproc.py
# class PreprocError(Errors.WafError):
# class c_parser(object):
# FILE_CACHE_SIZE = 100000
# LINE_CACHE_SIZE = 100000
# POPFILE = '-'
# NUM = 'i'
# OP = 'O'
# IDENT = 'T'
# STR = 's'
# CHAR = 'c'
# def repl(m):
# def reduce_nums(val_1, val_2, val_op):
# def get_num(lst):
# def get_term(lst):
# def reduce_eval(lst):
# def stringize(lst):
# def paste_tokens(t1, t2):
# def reduce_tokens(lst, defs, ban=[]):
# def eval_macro(lst, defs):
# def extract_macro(txt):
# def extract_include(txt, defs):
# def parse_char(txt):
# def tokenize(s):
# def tokenize_private(s):
# def format_defines(lst):
# def __init__(self, nodepaths=None, defines=None):
# def cached_find_resource(self, node, filename):
# def tryfind(self, filename, kind='"', env=None):
# def filter_comments(self, node):
# def parse_lines(self, node):
# def addlines(self, node):
# def start(self, node, env):
# def define_name(self, line):
# def scan(task):
. Output only the next line. | code = c_preproc.re_nl.sub('', code) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
# DragoonX6 2018
"""
Common routines for cross_clang.py and cross_clangxx.py
"""
def normalize_target_triple(target_triple):
target_triple = target_triple[:-1]
normalized_triple = target_triple.replace('--', '-unknown-')
if normalized_triple.startswith('-'):
normalized_triple = 'unknown' + normalized_triple
if normalized_triple.endswith('-'):
normalized_triple += 'unknown'
# Normalize MinGW builds to *arch*-w64-mingw32
if normalized_triple.endswith('windows-gnu'):
normalized_triple = normalized_triple[:normalized_triple.index('-')] + '-w64-mingw32'
# Strip the vendor when doing msvc builds, since it's unused anyway.
if normalized_triple.endswith('windows-msvc'):
normalized_triple = normalized_triple[:normalized_triple.index('-')] + '-windows-msvc'
return normalized_triple.replace('-', '_')
<|code_end|>
, predict the next line using imports from the current file:
from waflib.Configure import conf
import waflib.Context
import os
and context including class names, function names, and sometimes code from other files:
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
. Output only the next line. | @conf |
Predict the next line after this snippet: <|code_start|>
"""
This tool supports the export_symbols_regex to export the symbols in a shared library.
by default, all symbols are exported by gcc, and nothing by msvc.
to use the tool, do something like:
def build(ctx):
ctx(features='c cshlib syms', source='a.c b.c', export_symbols_regex='mylib_.*', target='testlib')
only the symbols starting with 'mylib_' will be exported.
"""
class gen_sym(Task):
def run(self):
obj = self.inputs[0]
kw = {}
reg = getattr(self.generator, 'export_symbols_regex', '.+?')
if 'msvc' in (self.env.CC_NAME, self.env.CXX_NAME):
re_nm = re.compile(r'External\s+\|\s+_(?P<symbol>%s)\b' % reg)
cmd = (self.env.DUMPBIN or ['dumpbin']) + ['/symbols', obj.abspath()]
else:
if self.env.DEST_BINFMT == 'pe': #gcc uses nm, and has a preceding _ on windows
re_nm = re.compile(r'(T|D)\s+_(?P<symbol>%s)\b' % reg)
elif self.env.DEST_BINFMT=='mac-o':
re_nm=re.compile(r'(T|D)\s+(?P<symbol>_?(%s))\b' % reg)
else:
re_nm = re.compile(r'(T|D)\s+(?P<symbol>%s)\b' % reg)
cmd = (self.env.NM or ['nm']) + ['-g', obj.abspath()]
<|code_end|>
using the current file's imports:
import re
from waflib.Context import STDOUT
from waflib.Task import Task
from waflib.Errors import WafError
from waflib.TaskGen import feature, after_method
and any relevant context from other files:
# Path: waflib/Context.py
# STDOUT = 1
#
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
. Output only the next line. | syms = [m.group('symbol') for m in re_nm.finditer(self.generator.bld.cmd_and_log(cmd, quiet=STDOUT, **kw))] |
Based on the snippet: <|code_start|> cmd = (self.env.DUMPBIN or ['dumpbin']) + ['/symbols', obj.abspath()]
else:
if self.env.DEST_BINFMT == 'pe': #gcc uses nm, and has a preceding _ on windows
re_nm = re.compile(r'(T|D)\s+_(?P<symbol>%s)\b' % reg)
elif self.env.DEST_BINFMT=='mac-o':
re_nm=re.compile(r'(T|D)\s+(?P<symbol>_?(%s))\b' % reg)
else:
re_nm = re.compile(r'(T|D)\s+(?P<symbol>%s)\b' % reg)
cmd = (self.env.NM or ['nm']) + ['-g', obj.abspath()]
syms = [m.group('symbol') for m in re_nm.finditer(self.generator.bld.cmd_and_log(cmd, quiet=STDOUT, **kw))]
self.outputs[0].write('%r' % syms)
class compile_sym(Task):
def run(self):
syms = {}
for x in self.inputs:
slist = eval(x.read())
for s in slist:
syms[s] = 1
lsyms = list(syms.keys())
lsyms.sort()
if self.env.DEST_BINFMT == 'pe':
self.outputs[0].write('EXPORTS\n' + '\n'.join(lsyms))
elif self.env.DEST_BINFMT == 'elf':
self.outputs[0].write('{ global:\n' + ';\n'.join(lsyms) + ";\nlocal: *; };\n")
elif self.env.DEST_BINFMT=='mac-o':
self.outputs[0].write('\n'.join(lsyms) + '\n')
else:
raise WafError('NotImplemented')
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from waflib.Context import STDOUT
from waflib.Task import Task
from waflib.Errors import WafError
from waflib.TaskGen import feature, after_method
and context (classes, functions, sometimes code) from other files:
# Path: waflib/Context.py
# STDOUT = 1
#
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
. Output only the next line. | @feature('syms') |
Next line prediction: <|code_start|> else:
if self.env.DEST_BINFMT == 'pe': #gcc uses nm, and has a preceding _ on windows
re_nm = re.compile(r'(T|D)\s+_(?P<symbol>%s)\b' % reg)
elif self.env.DEST_BINFMT=='mac-o':
re_nm=re.compile(r'(T|D)\s+(?P<symbol>_?(%s))\b' % reg)
else:
re_nm = re.compile(r'(T|D)\s+(?P<symbol>%s)\b' % reg)
cmd = (self.env.NM or ['nm']) + ['-g', obj.abspath()]
syms = [m.group('symbol') for m in re_nm.finditer(self.generator.bld.cmd_and_log(cmd, quiet=STDOUT, **kw))]
self.outputs[0].write('%r' % syms)
class compile_sym(Task):
def run(self):
syms = {}
for x in self.inputs:
slist = eval(x.read())
for s in slist:
syms[s] = 1
lsyms = list(syms.keys())
lsyms.sort()
if self.env.DEST_BINFMT == 'pe':
self.outputs[0].write('EXPORTS\n' + '\n'.join(lsyms))
elif self.env.DEST_BINFMT == 'elf':
self.outputs[0].write('{ global:\n' + ';\n'.join(lsyms) + ";\nlocal: *; };\n")
elif self.env.DEST_BINFMT=='mac-o':
self.outputs[0].write('\n'.join(lsyms) + '\n')
else:
raise WafError('NotImplemented')
@feature('syms')
<|code_end|>
. Use current file imports:
(import re
from waflib.Context import STDOUT
from waflib.Task import Task
from waflib.Errors import WafError
from waflib.TaskGen import feature, after_method)
and context including class names, function names, or small code snippets from other files:
# Path: waflib/Context.py
# STDOUT = 1
#
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
. Output only the next line. | @after_method('process_source', 'process_use', 'apply_link', 'process_uselib_local', 'propagate_uselib_vars') |
Based on the snippet: <|code_start|>
INST = '''
import sys, py_compile
py_compile.compile(sys.argv[1], sys.argv[2], sys.argv[3], True)
'''
"""
Piece of Python code used in :py:class:`waflib.Tools.python.pyo` and :py:class:`waflib.Tools.python.pyc` for byte-compiling python files
"""
DISTUTILS_IMP = ['from distutils.sysconfig import get_config_var, get_python_lib']
@before_method('process_source')
@feature('py')
def feature_py(self):
"""
Create tasks to byte-compile .py files and install them, if requested
"""
self.install_path = getattr(self, 'install_path', '${PYTHONDIR}')
install_from = getattr(self, 'install_from', None)
if install_from and not isinstance(install_from, Node.Node):
install_from = self.path.find_dir(install_from)
self.install_from = install_from
ver = self.env.PYTHON_VERSION
if not ver:
self.bld.fatal('Installing python files requires PYTHON_VERSION, try conf.check_python_version')
if int(ver.replace('.', '')) > 31:
self.install_32 = True
<|code_end|>
, predict the immediate next line with the help of imports:
import os, sys
from waflib import Errors, Logs, Node, Options, Task, Utils
from waflib.TaskGen import extension, before_method, after_method, feature
from waflib.Configure import conf
from distutils.msvccompiler import MSVCCompiler
from distutils.version import LooseVersion
and context (classes, functions, sometimes code) from other files:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
. Output only the next line. | @extension('.py') |
Continue the code snippet: <|code_start|>#ifdef __cplusplus
extern "C" {
#endif
void Py_Initialize(void);
void Py_Finalize(void);
#ifdef __cplusplus
}
#endif
int main(int argc, char **argv)
{
(void)argc; (void)argv;
Py_Initialize();
Py_Finalize();
return 0;
}
'''
"""
Piece of C/C++ code used in :py:func:`waflib.Tools.python.check_python_headers`
"""
INST = '''
import sys, py_compile
py_compile.compile(sys.argv[1], sys.argv[2], sys.argv[3], True)
'''
"""
Piece of Python code used in :py:class:`waflib.Tools.python.pyo` and :py:class:`waflib.Tools.python.pyc` for byte-compiling python files
"""
DISTUTILS_IMP = ['from distutils.sysconfig import get_config_var, get_python_lib']
<|code_end|>
. Use current file imports:
import os, sys
from waflib import Errors, Logs, Node, Options, Task, Utils
from waflib.TaskGen import extension, before_method, after_method, feature
from waflib.Configure import conf
from distutils.msvccompiler import MSVCCompiler
from distutils.version import LooseVersion
and context (classes, functions, or code) from other files:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
. Output only the next line. | @before_method('process_source') |
Given snippet: <|code_start|> self.add_install_files(install_to=os.path.dirname(pyd), install_from=pyobj, cwd=node.parent.get_bld(), relative_trick=relative_trick)
class pyc(Task.Task):
"""
Byte-compiling python files
"""
color = 'PINK'
def __str__(self):
node = self.outputs[0]
return node.path_from(node.ctx.launch_node())
def run(self):
cmd = [Utils.subst_vars('${PYTHON}', self.env), '-c', INST, self.inputs[0].abspath(), self.outputs[0].abspath(), self.pyd]
ret = self.generator.bld.exec_command(cmd)
return ret
class pyo(Task.Task):
"""
Byte-compiling python files
"""
color = 'PINK'
def __str__(self):
node = self.outputs[0]
return node.path_from(node.ctx.launch_node())
def run(self):
cmd = [Utils.subst_vars('${PYTHON}', self.env), Utils.subst_vars('${PYFLAGS_OPT}', self.env), '-c', INST, self.inputs[0].abspath(), self.outputs[0].abspath(), self.pyd]
ret = self.generator.bld.exec_command(cmd)
return ret
@feature('pyext')
@before_method('propagate_uselib_vars', 'apply_link')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, sys
from waflib import Errors, Logs, Node, Options, Task, Utils
from waflib.TaskGen import extension, before_method, after_method, feature
from waflib.Configure import conf
from distutils.msvccompiler import MSVCCompiler
from distutils.version import LooseVersion
and context:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
which might include code, classes, or functions. Output only the next line. | @after_method('apply_bundle') |
Given the following code snippet before the placeholder: <|code_start|>extern "C" {
#endif
void Py_Initialize(void);
void Py_Finalize(void);
#ifdef __cplusplus
}
#endif
int main(int argc, char **argv)
{
(void)argc; (void)argv;
Py_Initialize();
Py_Finalize();
return 0;
}
'''
"""
Piece of C/C++ code used in :py:func:`waflib.Tools.python.check_python_headers`
"""
INST = '''
import sys, py_compile
py_compile.compile(sys.argv[1], sys.argv[2], sys.argv[3], True)
'''
"""
Piece of Python code used in :py:class:`waflib.Tools.python.pyo` and :py:class:`waflib.Tools.python.pyc` for byte-compiling python files
"""
DISTUTILS_IMP = ['from distutils.sysconfig import get_config_var, get_python_lib']
@before_method('process_source')
<|code_end|>
, predict the next line using imports from the current file:
import os, sys
from waflib import Errors, Logs, Node, Options, Task, Utils
from waflib.TaskGen import extension, before_method, after_method, feature
from waflib.Configure import conf
from distutils.msvccompiler import MSVCCompiler
from distutils.version import LooseVersion
and context including class names, function names, and sometimes code from other files:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
. Output only the next line. | @feature('py') |
Given snippet: <|code_start|> self.uselib = self.to_list(getattr(self, 'uselib', []))
if not 'PYEXT' in self.uselib:
self.uselib.append('PYEXT')
# override shlib_PATTERN set by the osx module
self.env.cshlib_PATTERN = self.env.cxxshlib_PATTERN = self.env.macbundle_PATTERN = self.env.pyext_PATTERN
self.env.fcshlib_PATTERN = self.env.dshlib_PATTERN = self.env.pyext_PATTERN
try:
if not self.install_path:
return
except AttributeError:
self.install_path = '${PYTHONARCHDIR}'
@feature('pyext')
@before_method('apply_link', 'apply_bundle')
def set_bundle(self):
"""Mac-specific pyext extension that enables bundles from c_osx.py"""
if Utils.unversioned_sys_platform() == 'darwin':
self.mac_bundle = True
@before_method('propagate_uselib_vars')
@feature('pyembed')
def init_pyembed(self):
"""
Add the PYEMBED variable.
"""
self.uselib = self.to_list(getattr(self, 'uselib', []))
if not 'PYEMBED' in self.uselib:
self.uselib.append('PYEMBED')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, sys
from waflib import Errors, Logs, Node, Options, Task, Utils
from waflib.TaskGen import extension, before_method, after_method, feature
from waflib.Configure import conf
from distutils.msvccompiler import MSVCCompiler
from distutils.version import LooseVersion
and context:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
which might include code, classes, or functions. Output only the next line. | @conf |
Here is a snippet: <|code_start|>#! /usr/bin/env python
# encoding: utf-8
# Calle Rosenquist, 2017 (xbreak)
"""
Create task that copies source files to the associated build node.
This is useful to e.g. construct a complete Python package so it can be unit tested
without installation.
Source files to be copied can be specified either in `buildcopy_source` attribute, or
`source` attribute. If both are specified `buildcopy_source` has priority.
Examples::
def build(bld):
bld(name = 'bar',
features = 'py buildcopy',
source = bld.path.ant_glob('src/bar/*.py'))
bld(name = 'py baz',
features = 'buildcopy',
buildcopy_source = bld.path.ant_glob('src/bar/*.py') + ['src/bar/resource.txt'])
"""
<|code_end|>
. Write the next line using the current file imports:
import os, shutil
from waflib import Errors, Task, TaskGen, Utils, Node, Logs
and context from other files:
# Path: waflib/TaskGen.py
# HEADER_EXTS = ['.h', '.hpp', '.hxx', '.hh']
# class task_gen(object):
# class subst_pc(Task.Task):
# class subst(subst_pc):
# def __init__(self, *k, **kw):
# def __str__(self):
# def __repr__(self):
# def get_cwd(self):
# def get_name(self):
# def set_name(self, name):
# def to_list(self, val):
# def post(self):
# def get_hook(self, node):
# def create_task(self, name, src=None, tgt=None, **kw):
# def clone(self, env):
# def declare_chain(name='', rule=None, reentrant=None, color='BLUE',
# ext_in=[], ext_out=[], before=[], after=[], decider=None, scan=None, install_path=None, shell=False):
# def x_file(self, node):
# def taskgen_method(func):
# def feature(*k):
# def deco(func):
# def before_method(*k):
# def deco(func):
# def after_method(*k):
# def deco(func):
# def extension(*k):
# def deco(func):
# def to_nodes(self, lst, path=None):
# def process_source(self):
# def process_rule(self):
# def chmod_fun(tsk):
# def scan(self):
# def sequence_order(self):
# def force_permissions(self):
# def run(self):
# def repl(match):
# def sig_vars(self):
# def add_pcfile(self, node):
# def process_subst(self):
, which may include functions, classes, or code. Output only the next line. | @TaskGen.before_method('process_source') |
Given snippet: <|code_start|>
v.CFLAGS_CRT_MULTITHREADED_DBG = v.CXXFLAGS_CRT_MULTITHREADED_DBG = ['/MTd']
v.CFLAGS_CRT_MULTITHREADED_DLL_DBG = v.CXXFLAGS_CRT_MULTITHREADED_DLL_DBG = ['/MDd']
v.LIB_ST = '%s.lib'
v.LIBPATH_ST = '/LIBPATH:%s'
v.STLIB_ST = '%s.lib'
v.STLIBPATH_ST = '/LIBPATH:%s'
if v.MSVC_MANIFEST:
v.append_value('LINKFLAGS', ['/MANIFEST'])
v.CFLAGS_cshlib = []
v.CXXFLAGS_cxxshlib = []
v.LINKFLAGS_cshlib = v.LINKFLAGS_cxxshlib = ['/DLL']
v.cshlib_PATTERN = v.cxxshlib_PATTERN = '%s.dll'
v.implib_PATTERN = '%s.lib'
v.IMPLIB_ST = '/IMPLIB:%s'
v.LINKFLAGS_cstlib = []
v.cstlib_PATTERN = v.cxxstlib_PATTERN = '%s.lib'
v.cprogram_PATTERN = v.cxxprogram_PATTERN = '%s.exe'
v.def_PATTERN = '/def:%s'
#######################################################################################################
##### conf above, build below
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, sys, re, traceback
import json
from waflib import Utils, Logs, Options, Errors
from waflib.TaskGen import after_method, feature
from waflib.Configure import conf
from waflib.Tools import ccroot, c, cxx, ar
and context:
# Path: waflib/TaskGen.py
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
which might include code, classes, or functions. Output only the next line. | @after_method('apply_link') |
Given snippet: <|code_start|> v.CFLAGS_CRT_MULTITHREADED_DBG = v.CXXFLAGS_CRT_MULTITHREADED_DBG = ['/MTd']
v.CFLAGS_CRT_MULTITHREADED_DLL_DBG = v.CXXFLAGS_CRT_MULTITHREADED_DLL_DBG = ['/MDd']
v.LIB_ST = '%s.lib'
v.LIBPATH_ST = '/LIBPATH:%s'
v.STLIB_ST = '%s.lib'
v.STLIBPATH_ST = '/LIBPATH:%s'
if v.MSVC_MANIFEST:
v.append_value('LINKFLAGS', ['/MANIFEST'])
v.CFLAGS_cshlib = []
v.CXXFLAGS_cxxshlib = []
v.LINKFLAGS_cshlib = v.LINKFLAGS_cxxshlib = ['/DLL']
v.cshlib_PATTERN = v.cxxshlib_PATTERN = '%s.dll'
v.implib_PATTERN = '%s.lib'
v.IMPLIB_ST = '/IMPLIB:%s'
v.LINKFLAGS_cstlib = []
v.cstlib_PATTERN = v.cxxstlib_PATTERN = '%s.lib'
v.cprogram_PATTERN = v.cxxprogram_PATTERN = '%s.exe'
v.def_PATTERN = '/def:%s'
#######################################################################################################
##### conf above, build below
@after_method('apply_link')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, sys, re, traceback
import json
from waflib import Utils, Logs, Options, Errors
from waflib.TaskGen import after_method, feature
from waflib.Configure import conf
from waflib.Tools import ccroot, c, cxx, ar
and context:
# Path: waflib/TaskGen.py
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
which might include code, classes, or functions. Output only the next line. | @feature('c', 'cxx') |
Predict the next line for this snippet: <|code_start|> v.CFLAGS_cshlib = []
v.CXXFLAGS_cxxshlib = []
v.LINKFLAGS_cshlib = v.LINKFLAGS_cxxshlib = ['/DLL']
v.cshlib_PATTERN = v.cxxshlib_PATTERN = '%s.dll'
v.implib_PATTERN = '%s.lib'
v.IMPLIB_ST = '/IMPLIB:%s'
v.LINKFLAGS_cstlib = []
v.cstlib_PATTERN = v.cxxstlib_PATTERN = '%s.lib'
v.cprogram_PATTERN = v.cxxprogram_PATTERN = '%s.exe'
v.def_PATTERN = '/def:%s'
#######################################################################################################
##### conf above, build below
@after_method('apply_link')
@feature('c', 'cxx')
def apply_flags_msvc(self):
"""
Add additional flags implied by msvc, such as subsystems and pdb files::
def build(bld):
bld.stlib(source='main.c', target='bar', subsystem='gruik')
"""
if self.env.CC_NAME != 'msvc' or not getattr(self, 'link_task', None):
return
<|code_end|>
with the help of current file imports:
import os, sys, re, traceback
import json
from waflib import Utils, Logs, Options, Errors
from waflib.TaskGen import after_method, feature
from waflib.Configure import conf
from waflib.Tools import ccroot, c, cxx, ar
and context from other files:
# Path: waflib/TaskGen.py
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
, which may contain function names, class names, or code. Output only the next line. | is_static = isinstance(self.link_task, ccroot.stlink_task) |
Next line prediction: <|code_start|>(with extension _run.py) that are useful for debugging purposes.
"""
testlock = Utils.threading.Lock()
SCRIPT_TEMPLATE = """#! %(python)s
import subprocess, sys
cmd = %(cmd)r
# if you want to debug with gdb:
#cmd = ['gdb', '-args'] + cmd
env = %(env)r
status = subprocess.call(cmd, env=env, cwd=%(cwd)r, shell=isinstance(cmd, str))
sys.exit(status)
"""
@taskgen_method
def handle_ut_cwd(self, key):
"""
Task generator method, used internally to limit code duplication.
This method may disappear anytime.
"""
cwd = getattr(self, key, None)
if cwd:
if isinstance(cwd, str):
# we want a Node instance
if os.path.isabs(cwd):
self.ut_cwd = self.bld.root.make_node(cwd)
else:
self.ut_cwd = self.path.make_node(cwd)
<|code_end|>
. Use current file imports:
(import os, shlex, sys
from waflib.TaskGen import feature, after_method, taskgen_method
from waflib import Utils, Task, Logs, Options
from waflib.Tools import ccroot)
and context including class names, function names, or small code snippets from other files:
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def taskgen_method(func):
# """
# Decorator that registers method as a task generator method.
# The function must accept a task generator as first parameter::
#
# from waflib.TaskGen import taskgen_method
# @taskgen_method
# def mymethod(self):
# pass
#
# :param func: task generator method to add
# :type func: function
# :rtype: function
# """
# setattr(task_gen, func.__name__, func)
# return func
#
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
. Output only the next line. | @feature('test_scripts') |
Predict the next line for this snippet: <|code_start|> """Create interpreted unit tests."""
for x in ['test_scripts_source', 'test_scripts_template']:
if not hasattr(self, x):
Logs.warn('a test_scripts taskgen i missing %s' % x)
return
self.ut_run, lst = Task.compile_fun(self.test_scripts_template, shell=getattr(self, 'test_scripts_shell', False))
script_nodes = self.to_nodes(self.test_scripts_source)
for script_node in script_nodes:
tsk = self.create_task('utest', [script_node])
tsk.vars = lst + tsk.vars
tsk.env['SCRIPT'] = script_node.path_from(tsk.get_cwd())
self.handle_ut_cwd('test_scripts_cwd')
env = getattr(self, 'test_scripts_env', None)
if env:
self.ut_env = env
else:
self.ut_env = dict(os.environ)
paths = getattr(self, 'test_scripts_paths', {})
for (k,v) in paths.items():
p = self.ut_env.get(k, '').split(os.pathsep)
if isinstance(v, str):
v = v.split(os.pathsep)
self.ut_env[k] = os.pathsep.join(p + v)
@feature('test')
<|code_end|>
with the help of current file imports:
import os, shlex, sys
from waflib.TaskGen import feature, after_method, taskgen_method
from waflib import Utils, Task, Logs, Options
from waflib.Tools import ccroot
and context from other files:
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def taskgen_method(func):
# """
# Decorator that registers method as a task generator method.
# The function must accept a task generator as first parameter::
#
# from waflib.TaskGen import taskgen_method
# @taskgen_method
# def mymethod(self):
# pass
#
# :param func: task generator method to add
# :type func: function
# :rtype: function
# """
# setattr(task_gen, func.__name__, func)
# return func
#
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
, which may contain function names, class names, or code. Output only the next line. | @after_method('apply_link', 'process_use') |
Given snippet: <|code_start|> bld.program(features='test', source='main2.cpp', target='app2')
When the build is executed, the program 'test' will be built and executed without arguments.
The success/failure is detected by looking at the return code. The status and the standard output/error
are stored on the build context.
The results can be displayed by registering a callback function. Here is how to call
the predefined callback::
def build(bld):
bld(features='cxx cxxprogram test', source='main.c', target='app')
from waflib.Tools import waf_unit_test
bld.add_post_fun(waf_unit_test.summary)
By passing --dump-test-scripts the build outputs corresponding python files
(with extension _run.py) that are useful for debugging purposes.
"""
testlock = Utils.threading.Lock()
SCRIPT_TEMPLATE = """#! %(python)s
import subprocess, sys
cmd = %(cmd)r
# if you want to debug with gdb:
#cmd = ['gdb', '-args'] + cmd
env = %(env)r
status = subprocess.call(cmd, env=env, cwd=%(cwd)r, shell=isinstance(cmd, str))
sys.exit(status)
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, shlex, sys
from waflib.TaskGen import feature, after_method, taskgen_method
from waflib import Utils, Task, Logs, Options
from waflib.Tools import ccroot
and context:
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def taskgen_method(func):
# """
# Decorator that registers method as a task generator method.
# The function must accept a task generator as first parameter::
#
# from waflib.TaskGen import taskgen_method
# @taskgen_method
# def mymethod(self):
# pass
#
# :param func: task generator method to add
# :type func: function
# :rtype: function
# """
# setattr(task_gen, func.__name__, func)
# return func
#
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
which might include code, classes, or functions. Output only the next line. | @taskgen_method |
Predict the next line for this snippet: <|code_start|>
paths = getattr(self, 'test_scripts_paths', {})
for (k,v) in paths.items():
p = self.ut_env.get(k, '').split(os.pathsep)
if isinstance(v, str):
v = v.split(os.pathsep)
self.ut_env[k] = os.pathsep.join(p + v)
@feature('test')
@after_method('apply_link', 'process_use')
def make_test(self):
"""Create the unit test task. There can be only one unit test task by task generator."""
if not getattr(self, 'link_task', None):
return
tsk = self.create_task('utest', self.link_task.outputs)
if getattr(self, 'ut_str', None):
self.ut_run, lst = Task.compile_fun(self.ut_str, shell=getattr(self, 'ut_shell', False))
tsk.vars = lst + tsk.vars
self.handle_ut_cwd('ut_cwd')
if not hasattr(self, 'ut_paths'):
paths = []
for x in self.tmp_use_sorted:
try:
y = self.bld.get_tgen_by_name(x).link_task
except AttributeError:
pass
else:
<|code_end|>
with the help of current file imports:
import os, shlex, sys
from waflib.TaskGen import feature, after_method, taskgen_method
from waflib import Utils, Task, Logs, Options
from waflib.Tools import ccroot
and context from other files:
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
#
# def taskgen_method(func):
# """
# Decorator that registers method as a task generator method.
# The function must accept a task generator as first parameter::
#
# from waflib.TaskGen import taskgen_method
# @taskgen_method
# def mymethod(self):
# pass
#
# :param func: task generator method to add
# :type func: function
# :rtype: function
# """
# setattr(task_gen, func.__name__, func)
# return func
#
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
, which may contain function names, class names, or code. Output only the next line. | if not isinstance(y, ccroot.stlink_task): |
Predict the next line after this snippet: <|code_start|> if 'd' in exts:
feats.append('d')
if 'java' in exts:
feats.append('java')
return 'java'
if typ in ('program', 'shlib', 'stlib'):
will_link = False
for x in feats:
if x in ('cxx', 'd', 'fc', 'c', 'asm'):
feats.append(x + typ)
will_link = True
if not will_link and not kw.get('features', []):
raise Errors.WafError('Cannot link from %r, try passing eg: features="c cprogram"?' % kw)
return feats
def set_features(kw, typ):
"""
Inserts data in the input dict *kw* based on existing data and on the type of target
required (typ).
:param kw: task generator parameters
:type kw: dict
:param typ: type of target
:type typ: string
"""
kw['typ'] = typ
kw['features'] = Utils.to_list(kw.get('features', [])) + Utils.to_list(sniff_features(**kw))
<|code_end|>
using the current file's imports:
from waflib import Utils, Errors
from waflib.Configure import conf
and any relevant context from other files:
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
. Output only the next line. | @conf |
Predict the next line after this snippet: <|code_start|>#! /usr/bin/env python
# encoding: utf-8
# DC 2008
# Thomas Nagy 2016-2018 (ita)
"""
Fortran support
"""
ccroot.USELIB_VARS['fc'] = set(['FCFLAGS', 'DEFINES', 'INCLUDES', 'FCPPFLAGS'])
ccroot.USELIB_VARS['fcprogram_test'] = ccroot.USELIB_VARS['fcprogram'] = set(['LIB', 'STLIB', 'LIBPATH', 'STLIBPATH', 'LINKFLAGS', 'RPATH', 'LINKDEPS'])
ccroot.USELIB_VARS['fcshlib'] = set(['LIB', 'STLIB', 'LIBPATH', 'STLIBPATH', 'LINKFLAGS', 'RPATH', 'LINKDEPS'])
ccroot.USELIB_VARS['fcstlib'] = set(['ARFLAGS', 'LINKDEPS'])
<|code_end|>
using the current file's imports:
from waflib import Utils, Task, Errors
from waflib.Tools import ccroot, fc_config, fc_scan
from waflib.TaskGen import extension
from waflib.Configure import conf
and any relevant context from other files:
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
#
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
. Output only the next line. | @extension('.f','.F','.f90','.F90','.for','.FOR','.f95','.F95','.f03','.F03','.f08','.F08') |
Given snippet: <|code_start|>#! /usr/bin/env python
# encoding: utf-8
# DC 2008
# Thomas Nagy 2016-2018 (ita)
"""
Fortran support
"""
ccroot.USELIB_VARS['fc'] = set(['FCFLAGS', 'DEFINES', 'INCLUDES', 'FCPPFLAGS'])
ccroot.USELIB_VARS['fcprogram_test'] = ccroot.USELIB_VARS['fcprogram'] = set(['LIB', 'STLIB', 'LIBPATH', 'STLIBPATH', 'LINKFLAGS', 'RPATH', 'LINKDEPS'])
ccroot.USELIB_VARS['fcshlib'] = set(['LIB', 'STLIB', 'LIBPATH', 'STLIBPATH', 'LINKFLAGS', 'RPATH', 'LINKDEPS'])
ccroot.USELIB_VARS['fcstlib'] = set(['ARFLAGS', 'LINKDEPS'])
@extension('.f','.F','.f90','.F90','.for','.FOR','.f95','.F95','.f03','.F03','.f08','.F08')
def fc_hook(self, node):
"Binds the Fortran file extensions create :py:class:`waflib.Tools.fc.fc` instances"
return self.create_compiled_task('fc', node)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from waflib import Utils, Task, Errors
from waflib.Tools import ccroot, fc_config, fc_scan
from waflib.TaskGen import extension
from waflib.Configure import conf
and context:
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
#
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
which might include code, classes, or functions. Output only the next line. | @conf |
Given the following code snippet before the placeholder: <|code_start|> If yours has a different name, please report to hmgaudecker [at] gmail\n
Else:\n
Do not load the 'run_r_script' tool in the main wscript.\n\n""" % R_COMMANDS)
ctx.env.RFLAGS = 'CMD BATCH --slave'
class run_r_script_base(Task.Task):
"""Run a R script."""
run_str = '"${RCMD}" ${RFLAGS} "${SRC[0].abspath()}" "${LOGFILEPATH}"'
shell = True
class run_r_script(run_r_script_base):
"""Erase the R overall log file if everything went okay, else raise an
error and print its 10 last lines.
"""
def run(self):
ret = run_r_script_base.run(self)
logfile = self.env.LOGFILEPATH
if ret:
mode = 'r'
if sys.version_info.major >= 3:
mode = 'rb'
with open(logfile, mode=mode) as f:
tail = f.readlines()[-10:]
Logs.error("""Running R on %r returned the error %r\n\nCheck the log file %s, last 10 lines\n\n%s\n\n\n""",
self.inputs[0], ret, logfile, '\n'.join(tail))
else:
os.remove(logfile)
return ret
<|code_end|>
, predict the next line using imports from the current file:
import os, sys
from waflib import Task, TaskGen, Logs
and context including class names, function names, and sometimes code from other files:
# Path: waflib/TaskGen.py
# HEADER_EXTS = ['.h', '.hpp', '.hxx', '.hh']
# class task_gen(object):
# class subst_pc(Task.Task):
# class subst(subst_pc):
# def __init__(self, *k, **kw):
# def __str__(self):
# def __repr__(self):
# def get_cwd(self):
# def get_name(self):
# def set_name(self, name):
# def to_list(self, val):
# def post(self):
# def get_hook(self, node):
# def create_task(self, name, src=None, tgt=None, **kw):
# def clone(self, env):
# def declare_chain(name='', rule=None, reentrant=None, color='BLUE',
# ext_in=[], ext_out=[], before=[], after=[], decider=None, scan=None, install_path=None, shell=False):
# def x_file(self, node):
# def taskgen_method(func):
# def feature(*k):
# def deco(func):
# def before_method(*k):
# def deco(func):
# def after_method(*k):
# def deco(func):
# def extension(*k):
# def deco(func):
# def to_nodes(self, lst, path=None):
# def process_source(self):
# def process_rule(self):
# def chmod_fun(tsk):
# def scan(self):
# def sequence_order(self):
# def force_permissions(self):
# def run(self):
# def repl(match):
# def sig_vars(self):
# def add_pcfile(self, node):
# def process_subst(self):
. Output only the next line. | @TaskGen.feature('run_r_script') |
Predict the next line for this snippet: <|code_start|>testEXPORT int lib_func(void);
int main(int argc, char **argv) {
(void)argc; (void)argv;
return !(lib_func() == 9);
}
'''
@feature('link_lib_test')
@before_method('process_source')
def link_lib_test_fun(self):
"""
The configuration test :py:func:`waflib.Configure.run_build` declares a unique task generator,
so we need to create other task generators from here to check if the linker is able to link libraries.
"""
def write_test_file(task):
task.outputs[0].write(task.generator.code)
rpath = []
if getattr(self, 'add_rpath', False):
rpath = [self.bld.path.get_bld().abspath()]
mode = self.mode
m = '%s %s' % (mode, mode)
ex = self.test_exec and 'test_exec' or ''
bld = self.bld
bld(rule=write_test_file, target='test.' + mode, code=LIB_CODE)
bld(rule=write_test_file, target='main.' + mode, code=MAIN_CODE)
bld(features='%sshlib' % m, source='test.' + mode, target='test')
bld(features='%sprogram %s' % (m, ex), source='main.' + mode, target='app', use='test', rpath=rpath)
<|code_end|>
with the help of current file imports:
from waflib import Task
from waflib.Configure import conf
from waflib.TaskGen import feature, before_method, after_method
and context from other files:
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
, which may contain function names, class names, or code. Output only the next line. | @conf |
Using the snippet: <|code_start|># encoding: utf-8
# Thomas Nagy, 2016-2018 (ita)
"""
Various configuration tests.
"""
LIB_CODE = '''
#ifdef _MSC_VER
#define testEXPORT __declspec(dllexport)
#else
#define testEXPORT
#endif
testEXPORT int lib_func(void) { return 9; }
'''
MAIN_CODE = '''
#ifdef _MSC_VER
#define testEXPORT __declspec(dllimport)
#else
#define testEXPORT
#endif
testEXPORT int lib_func(void);
int main(int argc, char **argv) {
(void)argc; (void)argv;
return !(lib_func() == 9);
}
'''
<|code_end|>
, determine the next line of code. You have imports:
from waflib import Task
from waflib.Configure import conf
from waflib.TaskGen import feature, before_method, after_method
and context (class names, function names, or code) available:
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
. Output only the next line. | @feature('link_lib_test') |
Given the code snippet: <|code_start|># Thomas Nagy, 2016-2018 (ita)
"""
Various configuration tests.
"""
LIB_CODE = '''
#ifdef _MSC_VER
#define testEXPORT __declspec(dllexport)
#else
#define testEXPORT
#endif
testEXPORT int lib_func(void) { return 9; }
'''
MAIN_CODE = '''
#ifdef _MSC_VER
#define testEXPORT __declspec(dllimport)
#else
#define testEXPORT
#endif
testEXPORT int lib_func(void);
int main(int argc, char **argv) {
(void)argc; (void)argv;
return !(lib_func() == 9);
}
'''
@feature('link_lib_test')
<|code_end|>
, generate the next line using the imports in this file:
from waflib import Task
from waflib.Configure import conf
from waflib.TaskGen import feature, before_method, after_method
and context (functions, classes, or occasionally code) from other files:
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
. Output only the next line. | @before_method('process_source') |
Here is a snippet: <|code_start|>
ENDIAN_FRAGMENT = '''
short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
int use_ascii (int i) {
return ascii_mm[i] + ascii_ii[i];
}
short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
int use_ebcdic (int i) {
return ebcdic_mm[i] + ebcdic_ii[i];
}
extern int foo;
'''
class grep_for_endianness(Task.Task):
"""
Task that reads a binary and tries to determine the endianness
"""
color = 'PINK'
def run(self):
txt = self.inputs[0].read(flags='rb').decode('latin-1')
if txt.find('LiTTleEnDian') > -1:
self.generator.tmp.append('little')
elif txt.find('BIGenDianSyS') > -1:
self.generator.tmp.append('big')
else:
return -1
@feature('grep_for_endianness')
<|code_end|>
. Write the next line using the current file imports:
from waflib import Task
from waflib.Configure import conf
from waflib.TaskGen import feature, before_method, after_method
and context from other files:
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
#
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def before_method(*k):
# """
# Decorator that registera task generator method which will be executed
# before the functions of given name(s)::
#
# from waflib.TaskGen import feature, before
# @feature('myfeature')
# @before_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[func.__name__].add(fun_name)
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
, which may include functions, classes, or code. Output only the next line. | @after_method('process_source') |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy 2009-2018 (ita)
# DragoonX6 2018
"""
Detect the Clang++ C++ compiler
This version is an attempt at supporting the -target and -sysroot flag of Clang++.
"""
def options(opt):
"""
Target triplet for clang++::
$ waf configure --clangxx-target-triple=x86_64-pc-linux-gnu
"""
cxx_compiler_opts = opt.add_option_group('Configuration options')
cxx_compiler_opts.add_option('--clangxx-target-triple', default=None,
help='Target triple for clang++',
dest='clangxx_target_triple')
cxx_compiler_opts.add_option('--clangxx-sysroot', default=None,
help='Sysroot for clang++',
dest='clangxx_sysroot')
<|code_end|>
. Write the next line using the current file imports:
from waflib.Tools import ccroot, ar, gxx
from waflib.Configure import conf
import waflib.extras.clang_cross_common
import os
and context from other files:
# Path: waflib/Tools/ccroot.py
# SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
# USELIB_VARS = Utils.defaultdict(set)
# def create_compiled_task(self, name, node):
# def to_incnodes(self, inlst):
# def apply_incpaths(self):
# def add_target(self, target):
# def exec_command(self, *k, **kw):
# def exec_mf(self):
# def rm_tgt(cls):
# def wrap(self):
# def apply_skip_stlib_link_deps(self):
# def apply_link(self):
# def use_rec(self, name, **kw):
# def process_use(self):
# def accept_node_to_link(self, node):
# def add_objects_from_tgen(self, tg):
# def get_uselib_vars(self):
# def propagate_uselib_vars(self):
# def apply_implib(self):
# def apply_vnum(self):
# def keyword(self):
# def run(self):
# def runnable_status(self):
# def runnable_status(self):
# def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
# def process_lib(self):
# def runnable_status(self):
# def add_those_o_files(self, node):
# def process_objs(self):
# def read_object(self, obj):
# def set_full_paths_hpux(self):
# class link_task(Task.Task):
# class stlink_task(link_task):
# class vnum(Task.Task):
# class fake_shlib(link_task):
# class fake_stlib(stlink_task):
# class fake_o(Task.Task):
#
# Path: waflib/Configure.py
# def conf(f):
# """
# Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
# :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
# named 'mandatory' to disable the configuration errors::
#
# def configure(conf):
# conf.find_program('abc', mandatory=False)
#
# :param f: method to bind
# :type f: function
# """
# def fun(*k, **kw):
# mandatory = kw.pop('mandatory', True)
# try:
# return f(*k, **kw)
# except Errors.ConfigurationError:
# if mandatory:
# raise
#
# fun.__name__ = f.__name__
# setattr(ConfigurationContext, f.__name__, fun)
# setattr(Build.BuildContext, f.__name__, fun)
# return f
, which may include functions, classes, or code. Output only the next line. | @conf |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
# Brant Young, 2007
"Process *.rc* files for C/C++: X{.rc -> [.res|.rc.o]}"
@extension('.rc')
def rc_file(self, node):
"""
Binds the .rc extension to a winrc task
"""
obj_ext = '.rc.o'
if self.env.WINRC_TGT_F == '/fo':
obj_ext = '.res'
rctask = self.create_task('winrc', node, node.change_ext(obj_ext))
try:
self.compiled_tasks.append(rctask)
except AttributeError:
self.compiled_tasks = [rctask]
re_lines = re.compile(
r'(?:^[ \t]*(#|%:)[ \t]*(ifdef|ifndef|if|else|elif|endif|include|import|define|undef|pragma)[ \t]*(.*?)\s*$)|'\
r'(?:^\w+[ \t]*(ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)[ \t]*(.*?)\s*$)',
re.IGNORECASE | re.MULTILINE)
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from waflib import Task
from waflib.TaskGen import extension
from waflib.Tools import c_preproc
and context (classes, functions, sometimes code) from other files:
# Path: waflib/TaskGen.py
# def extension(*k):
# """
# Decorator that registers a task generator method which will be invoked during
# the processing of source files for the extension given::
#
# from waflib import Task
# class mytask(Task):
# run_str = 'cp ${SRC} ${TGT}'
# @extension('.moo')
# def create_maa_file(self, node):
# self.create_task('mytask', node, node.change_ext('.maa'))
# def build(bld):
# bld(source='foo.moo')
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for x in k:
# task_gen.mappings[x] = func
# return func
# return deco
#
# Path: waflib/Tools/c_preproc.py
# class PreprocError(Errors.WafError):
# class c_parser(object):
# FILE_CACHE_SIZE = 100000
# LINE_CACHE_SIZE = 100000
# POPFILE = '-'
# NUM = 'i'
# OP = 'O'
# IDENT = 'T'
# STR = 's'
# CHAR = 'c'
# def repl(m):
# def reduce_nums(val_1, val_2, val_op):
# def get_num(lst):
# def get_term(lst):
# def reduce_eval(lst):
# def stringize(lst):
# def paste_tokens(t1, t2):
# def reduce_tokens(lst, defs, ban=[]):
# def eval_macro(lst, defs):
# def extract_macro(txt):
# def extract_include(txt, defs):
# def parse_char(txt):
# def tokenize(s):
# def tokenize_private(s):
# def format_defines(lst):
# def __init__(self, nodepaths=None, defines=None):
# def cached_find_resource(self, node, filename):
# def tryfind(self, filename, kind='"', env=None):
# def filter_comments(self, node):
# def parse_lines(self, node):
# def addlines(self, node):
# def start(self, node, env):
# def define_name(self, line):
# def scan(task):
. Output only the next line. | class rc_parser(c_preproc.c_parser): |
Next line prediction: <|code_start|>"""Support for Sphinx documentation
This is a wrapper for sphinx-build program. Please note that sphinx-build supports only one output format which can
passed to build via sphinx_output_format attribute. The default output format is html.
Example wscript:
def configure(cnf):
conf.load('sphinx')
def build(bld):
bld(
features='sphinx',
sphinx_source='sources', # path to source directory
sphinx_options='-a -v', # sphinx-build program additional options
sphinx_output_format='man' # output format of sphinx documentation
)
"""
def configure(cnf):
"""Check if sphinx-build program is available and loads gnu_dirs tool."""
cnf.find_program('sphinx-build', var='SPHINX_BUILD', mandatory=False)
cnf.load('gnu_dirs')
<|code_end|>
. Use current file imports:
(from waflib.Node import Node
from waflib import Utils
from waflib.Task import Task
from waflib.TaskGen import feature, after_method)
and context including class names, function names, or small code snippets from other files:
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
. Output only the next line. | @feature('sphinx') |
Given the code snippet: <|code_start|>#!/usr/bin/python
# Grygoriy Fuchedzhy 2010
"""
Support for converting linked targets to ihex, srec or binary files using
objcopy. Use the 'objcopy' feature in conjunction with the 'cc' or 'cxx'
feature. The 'objcopy' feature uses the following attributes:
objcopy_bfdname Target object format name (eg. ihex, srec, binary).
Defaults to ihex.
objcopy_target File name used for objcopy output. This defaults to the
target name with objcopy_bfdname as extension.
objcopy_install_path Install path for objcopy_target file. Defaults to ${PREFIX}/fw.
objcopy_flags Additional flags passed to objcopy.
"""
class objcopy(Task.Task):
run_str = '${OBJCOPY} -O ${TARGET_BFDNAME} ${OBJCOPYFLAGS} ${SRC} ${TGT}'
color = 'CYAN'
<|code_end|>
, generate the next line using the imports in this file:
from waflib.Utils import def_attrs
from waflib import Task, Options
from waflib.TaskGen import feature, after_method
and context (functions, classes, or occasionally code) from other files:
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
. Output only the next line. | @feature('objcopy') |
Using the snippet: <|code_start|>#!/usr/bin/python
# Grygoriy Fuchedzhy 2010
"""
Support for converting linked targets to ihex, srec or binary files using
objcopy. Use the 'objcopy' feature in conjunction with the 'cc' or 'cxx'
feature. The 'objcopy' feature uses the following attributes:
objcopy_bfdname Target object format name (eg. ihex, srec, binary).
Defaults to ihex.
objcopy_target File name used for objcopy output. This defaults to the
target name with objcopy_bfdname as extension.
objcopy_install_path Install path for objcopy_target file. Defaults to ${PREFIX}/fw.
objcopy_flags Additional flags passed to objcopy.
"""
class objcopy(Task.Task):
run_str = '${OBJCOPY} -O ${TARGET_BFDNAME} ${OBJCOPYFLAGS} ${SRC} ${TGT}'
color = 'CYAN'
@feature('objcopy')
<|code_end|>
, determine the next line of code. You have imports:
from waflib.Utils import def_attrs
from waflib import Task, Options
from waflib.TaskGen import feature, after_method
and context (class names, function names, or code) available:
# Path: waflib/TaskGen.py
# def feature(*k):
# """
# Decorator that registers a task generator method that will be executed when the
# object attribute ``feature`` contains the corresponding key(s)::
#
# from waflib.Task import feature
# @feature('myfeature')
# def myfunction(self):
# print('that is my feature!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: feature names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for name in k:
# feats[name].update([func.__name__])
# return func
# return deco
#
# def after_method(*k):
# """
# Decorator that registers a task generator method which will be executed
# after the functions of given name(s)::
#
# from waflib.TaskGen import feature, after
# @feature('myfeature')
# @after_method('fun2')
# def fun1(self):
# print('feature 1!')
# @feature('myfeature')
# def fun2(self):
# print('feature 2!')
# def build(bld):
# bld(features='myfeature')
#
# :param k: method names
# :type k: list of string
# """
# def deco(func):
# setattr(task_gen, func.__name__, func)
# for fun_name in k:
# task_gen.prec[fun_name].add(func.__name__)
# return func
# return deco
. Output only the next line. | @after_method('apply_link') |
Predict the next line after this snippet: <|code_start|># flake8: noqa
# ensure that the containing module is on sys.path
# this is a hack for using alembic in our built virtualenv.
mod_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")
if mod_dir not in sys.path:
sys.path.append(mod_dir)
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
<|code_end|>
using the current file's imports:
import os
import sys
from alembic import context
from logging.config import fileConfig
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
from tokenserver.util import find_config_file
from mozsvc.config import load_into_settings
and any relevant context from other files:
# Path: tokenserver/util.py
# def find_config_file(*paths):
# ini_files = []
# ini_files.append(os.environ.get('TOKEN_INI'))
# ini_files.extend(paths)
# ini_files.extend((
# '/data/tokenserver/token-prod.ini',
# '/etc/mozilla-services/token/production.ini',
# ))
# for ini_file in ini_files:
# if ini_file is not None:
# ini_file = os.path.abspath(ini_file)
# if os.path.exists(ini_file):
# return ini_file
# raise RuntimeError("Could not locate tokenserver ini file")
. Output only the next line. | ini_file = find_config_file(config.get_main_option("token_ini")) |
Here is a snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Table schema for Sqlite
"""
__all__ = (get_cls,)
class _SQLITENodesBase(_NodesBase):
id = Column(Integer, primary_key=True)
@declared_attr
def __table_args__(cls):
return ()
_add('nodes', _SQLITENodesBase)
<|code_end|>
. Write the next line using the current file imports:
from tokenserver.assignment.sqlnode.schemas import (_UsersBase,
_NodesBase,
_SettingsBase,
Integer,
Column,
String,
_add,
declared_attr)
from tokenserver.assignment.sqlnode.schemas import get_cls # NOQA
and context from other files:
# Path: tokenserver/assignment/sqlnode/schemas.py
# def _add(name, base):
# def get_cls(name, base_cls):
# def __table_args__(cls):
# def __table_args__(cls):
# class _UsersBase(object):
# class _ServicesBase(object):
# class _NodesBase(object):
# class _SettingsBase(object):
#
# Path: tokenserver/assignment/sqlnode/schemas.py
# def get_cls(name, base_cls):
# if name in base_cls.metadata.tables:
# return base_cls.metadata.tables[name]
#
# args = {'__tablename__': name}
# base = bases[name]
# return type(name, (base, base_cls), args).__table__
, which may include functions, classes, or code. Output only the next line. | class _SQLITEUsersBase(_UsersBase): |
Based on the snippet: <|code_start|> Table schema for Sqlite
"""
__all__ = (get_cls,)
class _SQLITENodesBase(_NodesBase):
id = Column(Integer, primary_key=True)
@declared_attr
def __table_args__(cls):
return ()
_add('nodes', _SQLITENodesBase)
class _SQLITEUsersBase(_UsersBase):
uid = Column(Integer, primary_key=True)
@declared_attr
def __table_args__(cls):
return ()
_add('users', _SQLITEUsersBase)
<|code_end|>
, predict the immediate next line with the help of imports:
from tokenserver.assignment.sqlnode.schemas import (_UsersBase,
_NodesBase,
_SettingsBase,
Integer,
Column,
String,
_add,
declared_attr)
from tokenserver.assignment.sqlnode.schemas import get_cls # NOQA
and context (classes, functions, sometimes code) from other files:
# Path: tokenserver/assignment/sqlnode/schemas.py
# def _add(name, base):
# def get_cls(name, base_cls):
# def __table_args__(cls):
# def __table_args__(cls):
# class _UsersBase(object):
# class _ServicesBase(object):
# class _NodesBase(object):
# class _SettingsBase(object):
#
# Path: tokenserver/assignment/sqlnode/schemas.py
# def get_cls(name, base_cls):
# if name in base_cls.metadata.tables:
# return base_cls.metadata.tables[name]
#
# args = {'__tablename__': name}
# base = bases[name]
# return type(name, (base, base_cls), args).__table__
. Output only the next line. | class _SQLITESettingsBase(_SettingsBase): |
Continue the code snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Table schema for Sqlite
"""
__all__ = (get_cls,)
class _SQLITENodesBase(_NodesBase):
<|code_end|>
. Use current file imports:
from tokenserver.assignment.sqlnode.schemas import (_UsersBase,
_NodesBase,
_SettingsBase,
Integer,
Column,
String,
_add,
declared_attr)
from tokenserver.assignment.sqlnode.schemas import get_cls # NOQA
and context (classes, functions, or code) from other files:
# Path: tokenserver/assignment/sqlnode/schemas.py
# def _add(name, base):
# def get_cls(name, base_cls):
# def __table_args__(cls):
# def __table_args__(cls):
# class _UsersBase(object):
# class _ServicesBase(object):
# class _NodesBase(object):
# class _SettingsBase(object):
#
# Path: tokenserver/assignment/sqlnode/schemas.py
# def get_cls(name, base_cls):
# if name in base_cls.metadata.tables:
# return base_cls.metadata.tables[name]
#
# args = {'__tablename__': name}
# base = bases[name]
# return type(name, (base, base_cls), args).__table__
. Output only the next line. | id = Column(Integer, primary_key=True) |
Based on the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Table schema for Sqlite
"""
__all__ = (get_cls,)
class _SQLITENodesBase(_NodesBase):
<|code_end|>
, predict the immediate next line with the help of imports:
from tokenserver.assignment.sqlnode.schemas import (_UsersBase,
_NodesBase,
_SettingsBase,
Integer,
Column,
String,
_add,
declared_attr)
from tokenserver.assignment.sqlnode.schemas import get_cls # NOQA
and context (classes, functions, sometimes code) from other files:
# Path: tokenserver/assignment/sqlnode/schemas.py
# def _add(name, base):
# def get_cls(name, base_cls):
# def __table_args__(cls):
# def __table_args__(cls):
# class _UsersBase(object):
# class _ServicesBase(object):
# class _NodesBase(object):
# class _SettingsBase(object):
#
# Path: tokenserver/assignment/sqlnode/schemas.py
# def get_cls(name, base_cls):
# if name in base_cls.metadata.tables:
# return base_cls.metadata.tables[name]
#
# args = {'__tablename__': name}
# base = bases[name]
# return type(name, (base, base_cls), args).__table__
. Output only the next line. | id = Column(Integer, primary_key=True) |
Given snippet: <|code_start|>"""
__all__ = (get_cls,)
class _SQLITENodesBase(_NodesBase):
id = Column(Integer, primary_key=True)
@declared_attr
def __table_args__(cls):
return ()
_add('nodes', _SQLITENodesBase)
class _SQLITEUsersBase(_UsersBase):
uid = Column(Integer, primary_key=True)
@declared_attr
def __table_args__(cls):
return ()
_add('users', _SQLITEUsersBase)
class _SQLITESettingsBase(_SettingsBase):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tokenserver.assignment.sqlnode.schemas import (_UsersBase,
_NodesBase,
_SettingsBase,
Integer,
Column,
String,
_add,
declared_attr)
from tokenserver.assignment.sqlnode.schemas import get_cls # NOQA
and context:
# Path: tokenserver/assignment/sqlnode/schemas.py
# def _add(name, base):
# def get_cls(name, base_cls):
# def __table_args__(cls):
# def __table_args__(cls):
# class _UsersBase(object):
# class _ServicesBase(object):
# class _NodesBase(object):
# class _SettingsBase(object):
#
# Path: tokenserver/assignment/sqlnode/schemas.py
# def get_cls(name, base_cls):
# if name in base_cls.metadata.tables:
# return base_cls.metadata.tables[name]
#
# args = {'__tablename__': name}
# base = bases[name]
# return type(name, (base, base_cls), args).__table__
which might include code, classes, or functions. Output only the next line. | setting = Column(String(100), primary_key=True) |
Given snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Table schema for Sqlite
"""
__all__ = (get_cls,)
class _SQLITENodesBase(_NodesBase):
id = Column(Integer, primary_key=True)
@declared_attr
def __table_args__(cls):
return ()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tokenserver.assignment.sqlnode.schemas import (_UsersBase,
_NodesBase,
_SettingsBase,
Integer,
Column,
String,
_add,
declared_attr)
from tokenserver.assignment.sqlnode.schemas import get_cls # NOQA
and context:
# Path: tokenserver/assignment/sqlnode/schemas.py
# def _add(name, base):
# def get_cls(name, base_cls):
# def __table_args__(cls):
# def __table_args__(cls):
# class _UsersBase(object):
# class _ServicesBase(object):
# class _NodesBase(object):
# class _SettingsBase(object):
#
# Path: tokenserver/assignment/sqlnode/schemas.py
# def get_cls(name, base_cls):
# if name in base_cls.metadata.tables:
# return base_cls.metadata.tables[name]
#
# args = {'__tablename__': name}
# base = bases[name]
# return type(name, (base, base_cls), args).__table__
which might include code, classes, or functions. Output only the next line. | _add('nodes', _SQLITENodesBase) |
Using the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Table schema for Sqlite
"""
__all__ = (get_cls,)
class _SQLITENodesBase(_NodesBase):
id = Column(Integer, primary_key=True)
<|code_end|>
, determine the next line of code. You have imports:
from tokenserver.assignment.sqlnode.schemas import (_UsersBase,
_NodesBase,
_SettingsBase,
Integer,
Column,
String,
_add,
declared_attr)
from tokenserver.assignment.sqlnode.schemas import get_cls # NOQA
and context (class names, function names, or code) available:
# Path: tokenserver/assignment/sqlnode/schemas.py
# def _add(name, base):
# def get_cls(name, base_cls):
# def __table_args__(cls):
# def __table_args__(cls):
# class _UsersBase(object):
# class _ServicesBase(object):
# class _NodesBase(object):
# class _SettingsBase(object):
#
# Path: tokenserver/assignment/sqlnode/schemas.py
# def get_cls(name, base_cls):
# if name in base_cls.metadata.tables:
# return base_cls.metadata.tables[name]
#
# args = {'__tablename__': name}
# base = bases[name]
# return type(name, (base, base_cls), args).__table__
. Output only the next line. | @declared_attr |
Given the following code snippet before the placeholder: <|code_start|># flake8: noqa
# -*- coding: utf8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Runs the Application. This script can be called by any wsgi runner that looks
for an 'application' variable
"""
# setting up the egg cache to a place where apache can write
os.environ['PYTHON_EGG_CACHE'] = '/tmp/python-eggs'
# setting up logging
<|code_end|>
, predict the next line using imports from the current file:
import os
from logging.config import fileConfig
from ConfigParser import NoSectionError
from tokenserver.util import find_config_file
from paste.deploy import loadapp
and context including class names, function names, and sometimes code from other files:
# Path: tokenserver/util.py
# def find_config_file(*paths):
# ini_files = []
# ini_files.append(os.environ.get('TOKEN_INI'))
# ini_files.extend(paths)
# ini_files.extend((
# '/data/tokenserver/token-prod.ini',
# '/etc/mozilla-services/token/production.ini',
# ))
# for ini_file in ini_files:
# if ini_file is not None:
# ini_file = os.path.abspath(ini_file)
# if os.path.exists(ini_file):
# return ini_file
# raise RuntimeError("Could not locate tokenserver ini file")
. Output only the next line. | ini_file = find_config_file() |
Continue the code snippet: <|code_start|>
class mockobj(object):
pass
class TestLocalBrowserIdVerifier(unittest.TestCase):
DEFAULT_SETTINGS = { # noqa; identation below is non-standard
"tokenserver.backend":
"tokenserver.assignment.memorynode.MemoryNodeAssignmentBackend",
"browserid.backend":
"tokenserver.verifiers.LocalBrowserIdVerifier",
"tokenserver.secrets.backend":
"mozsvc.secrets.FixedSecrets",
"tokenserver.secrets.secrets":
"bruce-let-the-dogs-out",
}
def _make_config(self, settings={}):
all_settings = self.DEFAULT_SETTINGS.copy()
all_settings.update(settings)
config = Configurator(settings=all_settings)
config.include("tokenserver")
config.commit()
return config
def test_verifier_config_loading_defaults(self):
config = self._make_config()
verifier = config.registry.getUtility(IBrowserIdVerifier)
<|code_end|>
. Use current file imports:
import unittest
import browserid.errors
from pyramid.config import Configurator
from tokenserver.verifiers import LocalBrowserIdVerifier, IBrowserIdVerifier
from browserid.tests.support import (make_assertion,
patched_supportdoc_fetching)
and context (classes, functions, or code) from other files:
# Path: tokenserver/verifiers.py
# class LocalBrowserIdVerifier(browserid.verifiers.local.LocalVerifier):
# implements(IBrowserIdVerifier)
#
# def __init__(self, trusted_issuers=None, allowed_issuers=None, **kwargs):
# """LocalVerifier constructor, with the following extra config options:
#
# :param ssl_certificate: The path to an optional ssl certificate to
# use when doing SSL requests with the BrowserID server.
# Set to True (the default) to use default certificate authorities.
# Set to False to disable SSL verification.
# """
# if isinstance(trusted_issuers, basestring):
# trusted_issuers = trusted_issuers.split()
# self.trusted_issuers = trusted_issuers
# if trusted_issuers is not None:
# kwargs["trusted_secondaries"] = trusted_issuers
# if isinstance(allowed_issuers, basestring):
# allowed_issuers = allowed_issuers.split()
# self.allowed_issuers = allowed_issuers
# if "ssl_certificate" in kwargs:
# verify = kwargs["ssl_certificate"]
# kwargs.pop("ssl_certificate")
# if not verify:
# self._emit_warning()
# else:
# verify = None
# kwargs["supportdocs"] = SupportDocumentManager(verify=verify)
# # Disable warning about evolving data formats, it's out of date.
# kwargs.setdefault("warning", False)
# super(LocalBrowserIdVerifier, self).__init__(**kwargs)
#
# def _emit_warning():
# """Emit a scary warning to discourage unverified SSL access."""
# msg = "browserid.ssl_certificate=False disables server's certificate"\
# "validation and poses a security risk. You should pass the path"\
# "to your self-signed certificate(s) instead. "\
# "For more information on the ssl_certificate parameter, see "\
# "http://docs.python-requests.org/en/latest/user/advanced/"\
# "#ssl-cert-verification"
# warnings.warn(msg, RuntimeWarning, stacklevel=2)
#
# def verify(self, assertion, audience=None):
# data = super(LocalBrowserIdVerifier, self).verify(assertion, audience)
# if self.allowed_issuers is not None:
# issuer = data.get('issuer')
# if issuer not in self.allowed_issuers:
# raise InvalidIssuerError("Issuer not allowed: %s" % (issuer,))
# return data
#
# class IBrowserIdVerifier(Interface):
# pass
. Output only the next line. | self.assertTrue(isinstance(verifier, LocalBrowserIdVerifier)) |
Using the snippet: <|code_start|>
class mockobj(object):
pass
class TestLocalBrowserIdVerifier(unittest.TestCase):
DEFAULT_SETTINGS = { # noqa; identation below is non-standard
"tokenserver.backend":
"tokenserver.assignment.memorynode.MemoryNodeAssignmentBackend",
"browserid.backend":
"tokenserver.verifiers.LocalBrowserIdVerifier",
"tokenserver.secrets.backend":
"mozsvc.secrets.FixedSecrets",
"tokenserver.secrets.secrets":
"bruce-let-the-dogs-out",
}
def _make_config(self, settings={}):
all_settings = self.DEFAULT_SETTINGS.copy()
all_settings.update(settings)
config = Configurator(settings=all_settings)
config.include("tokenserver")
config.commit()
return config
def test_verifier_config_loading_defaults(self):
config = self._make_config()
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import browserid.errors
from pyramid.config import Configurator
from tokenserver.verifiers import LocalBrowserIdVerifier, IBrowserIdVerifier
from browserid.tests.support import (make_assertion,
patched_supportdoc_fetching)
and context (class names, function names, or code) available:
# Path: tokenserver/verifiers.py
# class LocalBrowserIdVerifier(browserid.verifiers.local.LocalVerifier):
# implements(IBrowserIdVerifier)
#
# def __init__(self, trusted_issuers=None, allowed_issuers=None, **kwargs):
# """LocalVerifier constructor, with the following extra config options:
#
# :param ssl_certificate: The path to an optional ssl certificate to
# use when doing SSL requests with the BrowserID server.
# Set to True (the default) to use default certificate authorities.
# Set to False to disable SSL verification.
# """
# if isinstance(trusted_issuers, basestring):
# trusted_issuers = trusted_issuers.split()
# self.trusted_issuers = trusted_issuers
# if trusted_issuers is not None:
# kwargs["trusted_secondaries"] = trusted_issuers
# if isinstance(allowed_issuers, basestring):
# allowed_issuers = allowed_issuers.split()
# self.allowed_issuers = allowed_issuers
# if "ssl_certificate" in kwargs:
# verify = kwargs["ssl_certificate"]
# kwargs.pop("ssl_certificate")
# if not verify:
# self._emit_warning()
# else:
# verify = None
# kwargs["supportdocs"] = SupportDocumentManager(verify=verify)
# # Disable warning about evolving data formats, it's out of date.
# kwargs.setdefault("warning", False)
# super(LocalBrowserIdVerifier, self).__init__(**kwargs)
#
# def _emit_warning():
# """Emit a scary warning to discourage unverified SSL access."""
# msg = "browserid.ssl_certificate=False disables server's certificate"\
# "validation and poses a security risk. You should pass the path"\
# "to your self-signed certificate(s) instead. "\
# "For more information on the ssl_certificate parameter, see "\
# "http://docs.python-requests.org/en/latest/user/advanced/"\
# "#ssl-cert-verification"
# warnings.warn(msg, RuntimeWarning, stacklevel=2)
#
# def verify(self, assertion, audience=None):
# data = super(LocalBrowserIdVerifier, self).verify(assertion, audience)
# if self.allowed_issuers is not None:
# issuer = data.get('issuer')
# if issuer not in self.allowed_issuers:
# raise InvalidIssuerError("Issuer not allowed: %s" % (issuer,))
# return data
#
# class IBrowserIdVerifier(Interface):
# pass
. Output only the next line. | verifier = config.registry.getUtility(IBrowserIdVerifier) |
Given the following code snippet before the placeholder: <|code_start|> }
def _make_config(self, settings={}):
all_settings = self.DEFAULT_SETTINGS.copy()
all_settings.update(settings)
config = Configurator(settings=all_settings)
config.include("tokenserver")
config.commit()
return config
@contextlib.contextmanager
def _mock_verifier(self, verifier, exc=None, **response_attrs):
def replacement_post_method(*args, **kwds):
if exc is not None:
raise exc
response = mockobj()
response.status_code = 200
response.text = ""
response.__dict__.update(response_attrs)
return response
orig_post_method = verifier.session.post
verifier.session.post = replacement_post_method
try:
yield None
finally:
verifier.session.post = orig_post_method
def test_verifier_config_loading_defaults(self):
config = self._make_config()
verifier = config.registry.getUtility(IBrowserIdVerifier)
<|code_end|>
, predict the next line using imports from the current file:
import json
import contextlib
import unittest
import browserid.errors
from pyramid.config import Configurator
from tokenserver.verifiers import RemoteBrowserIdVerifier, IBrowserIdVerifier
from browserid.tests.support import make_assertion
and context including class names, function names, and sometimes code from other files:
# Path: tokenserver/verifiers.py
# class RemoteBrowserIdVerifier(object):
# implements(IBrowserIdVerifier)
#
# def __init__(self, audiences=None, trusted_issuers=None,
# allowed_issuers=None, verifier_url=None, timeout=None):
# # Since we don't parse the assertion locally, we cannot support
# # list- or pattern-based audience strings.
# if audiences is not None:
# assert isinstance(audiences, basestring)
# self.audiences = audiences
# if isinstance(trusted_issuers, basestring):
# trusted_issuers = trusted_issuers.split()
# self.trusted_issuers = trusted_issuers
# if isinstance(allowed_issuers, basestring):
# allowed_issuers = allowed_issuers.split()
# self.allowed_issuers = allowed_issuers
# if verifier_url is None:
# verifier_url = "https://verifier.accounts.firefox.com/v2"
# self.verifier_url = verifier_url
# if timeout is None:
# timeout = 30
# self.timeout = timeout
# self.session = requests.Session()
# self.session.verify = True
#
# def verify(self, assertion, audience=None):
# if audience is None:
# audience = self.audiences
#
# body = {'assertion': assertion, 'audience': audience}
# if self.trusted_issuers is not None:
# body['trustedIssuers'] = self.trusted_issuers
# headers = {'content-type': 'application/json'}
# try:
# response = self.session.post(self.verifier_url,
# data=json.dumps(body),
# headers=headers,
# timeout=self.timeout)
# except (socket.error, requests.RequestException), e:
# msg = "Failed to POST %s. Reason: %s" % (self.verifier_url, str(e))
# raise ConnectionError(msg)
#
# if response.status_code != 200:
# raise ConnectionError('server returned invalid response code')
# try:
# data = json.loads(response.text)
# except ValueError:
# raise ConnectionError("server returned invalid response body")
#
# if data.get('status') != "okay":
# reason = data.get('reason', 'unknown error')
# if "audience mismatch" in reason:
# raise AudienceMismatchError(data.get("audience"), audience)
# if "expired" in reason or "issued later than" in reason:
# raise ExpiredSignatureError(reason)
# raise InvalidSignatureError(reason)
# if self.allowed_issuers is not None:
# issuer = data.get('issuer')
# if issuer not in self.allowed_issuers:
# raise InvalidIssuerError("Issuer not allowed: %s" % (issuer,))
# return data
#
# class IBrowserIdVerifier(Interface):
# pass
. Output only the next line. | self.assertTrue(isinstance(verifier, RemoteBrowserIdVerifier)) |
Based on the snippet: <|code_start|> "tokenserver.verifiers.RemoteBrowserIdVerifier",
}
def _make_config(self, settings={}):
all_settings = self.DEFAULT_SETTINGS.copy()
all_settings.update(settings)
config = Configurator(settings=all_settings)
config.include("tokenserver")
config.commit()
return config
@contextlib.contextmanager
def _mock_verifier(self, verifier, exc=None, **response_attrs):
def replacement_post_method(*args, **kwds):
if exc is not None:
raise exc
response = mockobj()
response.status_code = 200
response.text = ""
response.__dict__.update(response_attrs)
return response
orig_post_method = verifier.session.post
verifier.session.post = replacement_post_method
try:
yield None
finally:
verifier.session.post = orig_post_method
def test_verifier_config_loading_defaults(self):
config = self._make_config()
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import contextlib
import unittest
import browserid.errors
from pyramid.config import Configurator
from tokenserver.verifiers import RemoteBrowserIdVerifier, IBrowserIdVerifier
from browserid.tests.support import make_assertion
and context (classes, functions, sometimes code) from other files:
# Path: tokenserver/verifiers.py
# class RemoteBrowserIdVerifier(object):
# implements(IBrowserIdVerifier)
#
# def __init__(self, audiences=None, trusted_issuers=None,
# allowed_issuers=None, verifier_url=None, timeout=None):
# # Since we don't parse the assertion locally, we cannot support
# # list- or pattern-based audience strings.
# if audiences is not None:
# assert isinstance(audiences, basestring)
# self.audiences = audiences
# if isinstance(trusted_issuers, basestring):
# trusted_issuers = trusted_issuers.split()
# self.trusted_issuers = trusted_issuers
# if isinstance(allowed_issuers, basestring):
# allowed_issuers = allowed_issuers.split()
# self.allowed_issuers = allowed_issuers
# if verifier_url is None:
# verifier_url = "https://verifier.accounts.firefox.com/v2"
# self.verifier_url = verifier_url
# if timeout is None:
# timeout = 30
# self.timeout = timeout
# self.session = requests.Session()
# self.session.verify = True
#
# def verify(self, assertion, audience=None):
# if audience is None:
# audience = self.audiences
#
# body = {'assertion': assertion, 'audience': audience}
# if self.trusted_issuers is not None:
# body['trustedIssuers'] = self.trusted_issuers
# headers = {'content-type': 'application/json'}
# try:
# response = self.session.post(self.verifier_url,
# data=json.dumps(body),
# headers=headers,
# timeout=self.timeout)
# except (socket.error, requests.RequestException), e:
# msg = "Failed to POST %s. Reason: %s" % (self.verifier_url, str(e))
# raise ConnectionError(msg)
#
# if response.status_code != 200:
# raise ConnectionError('server returned invalid response code')
# try:
# data = json.loads(response.text)
# except ValueError:
# raise ConnectionError("server returned invalid response body")
#
# if data.get('status') != "okay":
# reason = data.get('reason', 'unknown error')
# if "audience mismatch" in reason:
# raise AudienceMismatchError(data.get("audience"), audience)
# if "expired" in reason or "issued later than" in reason:
# raise ExpiredSignatureError(reason)
# raise InvalidSignatureError(reason)
# if self.allowed_issuers is not None:
# issuer = data.get('issuer')
# if issuer not in self.allowed_issuers:
# raise InvalidIssuerError("Issuer not allowed: %s" % (issuer,))
# return data
#
# class IBrowserIdVerifier(Interface):
# pass
. Output only the next line. | verifier = config.registry.getUtility(IBrowserIdVerifier) |
Using the snippet: <|code_start|> "mozsvc.secrets.FixedSecrets",
"tokenserver.secrets.secrets":
"steve-let-the-dogs-out",
}
def _make_config(self, settings={}):
all_settings = self.DEFAULT_SETTINGS.copy()
all_settings.update(settings)
config = Configurator(settings=all_settings)
config.include("tokenserver")
config.commit()
return config
@contextlib.contextmanager
def _mock_verifier(self, verifier, response=None, exc=None):
def replacement_verify_token_method(*args, **kwds):
if exc is not None:
raise exc
if response is not None:
return response
raise RuntimeError("incomplete mock")
orig_verify_token_method = verifier._client.verify_token
verifier._client.verify_token = replacement_verify_token_method
try:
yield None
finally:
verifier._client.verify_token = orig_verify_token_method
def test_verifier_config_loading_defaults(self):
config = self._make_config()
<|code_end|>
, determine the next line of code. You have imports:
import socket
import unittest
import responses
import contextlib
import fxa.errors
from pyramid.config import Configurator
from tokenserver.verifiers import (
IOAuthVerifier,
ConnectionError,
RemoteOAuthVerifier,
)
and context (class names, function names, or code) available:
# Path: tokenserver/verifiers.py
# DEFAULT_OAUTH_SCOPE = 'https://identity.mozilla.com/apps/oldsync'
# def get_browserid_verifier(registry=None):
# def get_oauth_verifier(registry=None):
# def __init__(self, trusted_issuers=None, allowed_issuers=None, **kwargs):
# def _emit_warning():
# def verify(self, assertion, audience=None):
# def __init__(self, audiences=None, trusted_issuers=None,
# allowed_issuers=None, verifier_url=None, timeout=None):
# def verify(self, assertion, audience=None):
# def __init__(self, server_url=None, default_issuer=None, timeout=30,
# scope=DEFAULT_OAUTH_SCOPE, jwks=None):
# def server_url(self):
# def timeout(self):
# def verify(self, token):
# class IBrowserIdVerifier(Interface):
# class IOAuthVerifier(Interface):
# class LocalBrowserIdVerifier(browserid.verifiers.local.LocalVerifier):
# class RemoteBrowserIdVerifier(object):
# class RemoteOAuthVerifier(object):
. Output only the next line. | verifier = config.registry.getUtility(IOAuthVerifier) |
Predict the next line after this snippet: <|code_start|> responses.add(
responses.GET,
"https://oauth-server.my-self-hosted-setup.com/config",
json={
"browserid": {
"oh no": "the issuer is not configured here"
},
}
)
config = self._make_config({ # noqa; indentation below is non-standard
"oauth.server_url":
"https://oauth-server.my-self-hosted-setup.com/",
})
verifier = config.registry.getUtility(IOAuthVerifier)
self.assertEqual(len(responses.calls), 1)
self.assertTrue(isinstance(verifier, RemoteOAuthVerifier))
self.assertEquals(verifier.server_url,
"https://oauth-server.my-self-hosted-setup.com/v1")
self.assertEquals(verifier.default_issuer, None)
def test_verifier_config_rejects_empty_scope(self):
with self.assertRaises(ValueError):
self._make_config({
"oauth.scope": ""
})
def test_verifier_failure_cases(self):
config = self._make_config()
verifier = config.registry.getUtility(IOAuthVerifier)
with self._mock_verifier(verifier, exc=socket.error):
<|code_end|>
using the current file's imports:
import socket
import unittest
import responses
import contextlib
import fxa.errors
from pyramid.config import Configurator
from tokenserver.verifiers import (
IOAuthVerifier,
ConnectionError,
RemoteOAuthVerifier,
)
and any relevant context from other files:
# Path: tokenserver/verifiers.py
# DEFAULT_OAUTH_SCOPE = 'https://identity.mozilla.com/apps/oldsync'
# def get_browserid_verifier(registry=None):
# def get_oauth_verifier(registry=None):
# def __init__(self, trusted_issuers=None, allowed_issuers=None, **kwargs):
# def _emit_warning():
# def verify(self, assertion, audience=None):
# def __init__(self, audiences=None, trusted_issuers=None,
# allowed_issuers=None, verifier_url=None, timeout=None):
# def verify(self, assertion, audience=None):
# def __init__(self, server_url=None, default_issuer=None, timeout=30,
# scope=DEFAULT_OAUTH_SCOPE, jwks=None):
# def server_url(self):
# def timeout(self):
# def verify(self, token):
# class IBrowserIdVerifier(Interface):
# class IOAuthVerifier(Interface):
# class LocalBrowserIdVerifier(browserid.verifiers.local.LocalVerifier):
# class RemoteBrowserIdVerifier(object):
# class RemoteOAuthVerifier(object):
. Output only the next line. | with self.assertRaises(ConnectionError): |
Next line prediction: <|code_start|> "tokenserver.secrets.secrets":
"steve-let-the-dogs-out",
}
def _make_config(self, settings={}):
all_settings = self.DEFAULT_SETTINGS.copy()
all_settings.update(settings)
config = Configurator(settings=all_settings)
config.include("tokenserver")
config.commit()
return config
@contextlib.contextmanager
def _mock_verifier(self, verifier, response=None, exc=None):
def replacement_verify_token_method(*args, **kwds):
if exc is not None:
raise exc
if response is not None:
return response
raise RuntimeError("incomplete mock")
orig_verify_token_method = verifier._client.verify_token
verifier._client.verify_token = replacement_verify_token_method
try:
yield None
finally:
verifier._client.verify_token = orig_verify_token_method
def test_verifier_config_loading_defaults(self):
config = self._make_config()
verifier = config.registry.getUtility(IOAuthVerifier)
<|code_end|>
. Use current file imports:
(import socket
import unittest
import responses
import contextlib
import fxa.errors
from pyramid.config import Configurator
from tokenserver.verifiers import (
IOAuthVerifier,
ConnectionError,
RemoteOAuthVerifier,
))
and context including class names, function names, or small code snippets from other files:
# Path: tokenserver/verifiers.py
# DEFAULT_OAUTH_SCOPE = 'https://identity.mozilla.com/apps/oldsync'
# def get_browserid_verifier(registry=None):
# def get_oauth_verifier(registry=None):
# def __init__(self, trusted_issuers=None, allowed_issuers=None, **kwargs):
# def _emit_warning():
# def verify(self, assertion, audience=None):
# def __init__(self, audiences=None, trusted_issuers=None,
# allowed_issuers=None, verifier_url=None, timeout=None):
# def verify(self, assertion, audience=None):
# def __init__(self, server_url=None, default_issuer=None, timeout=30,
# scope=DEFAULT_OAUTH_SCOPE, jwks=None):
# def server_url(self):
# def timeout(self):
# def verify(self, token):
# class IBrowserIdVerifier(Interface):
# class IOAuthVerifier(Interface):
# class LocalBrowserIdVerifier(browserid.verifiers.local.LocalVerifier):
# class RemoteBrowserIdVerifier(object):
# class RemoteOAuthVerifier(object):
. Output only the next line. | self.assertTrue(isinstance(verifier, RemoteOAuthVerifier)) |
Predict the next line for this snippet: <|code_start|> requests and does some basic sanity-checking on the results.
"""
server_url = 'https://token.stage.mozaws.net'
def setUp(self):
self.endpoint = urlparse.urljoin(self.server_url, '/1.0/sync/1.5')
self.audience = self.server_url.rstrip('/')
def test_server_config(self):
"""Sanity-check server config against local settings.
This is a quick test that fetches config from the target server
and checks it against our local settings. It will fail if there's
a mis-match that would cause our loatests to fail.
"""
res = self.session.get(self.server_url + '/')
self.assertEquals(res.status_code, 200)
server_config = res.json()
try:
allowed_issuers = server_config['browserid']['allowed_issuers']
if allowed_issuers is not None:
if MOCKMYID_DOMAIN not in allowed_issuers:
msg = 'Server does not allow browserid assertions from {}'
raise AssertionError(msg.format(MOCKMYID_DOMAIN))
except KeyError:
pass
if server_config['oauth']['default_issuer'] != MOCKMYID_DOMAIN:
msg = 'OAuth default_issuer does not match {}'
raise AssertionError(msg.format(MOCKMYID_DOMAIN))
<|code_end|>
with the help of current file imports:
import os
import json
import time
import uuid
import random
import urlparse
import browserid
import browserid.jwt
from browserid.tests.support import make_assertion
from tokenserver.verifiers import DEFAULT_OAUTH_SCOPE
from loads import TestCase
and context from other files:
# Path: tokenserver/verifiers.py
# DEFAULT_OAUTH_SCOPE = 'https://identity.mozilla.com/apps/oldsync'
, which may contain function names, class names, or code. Output only the next line. | if server_config['oauth']['scope'] != DEFAULT_OAUTH_SCOPE: |
Given snippet: <|code_start|># Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class SaharaTempestPlugin(plugins.TempestPlugin):
def load_tests(self):
base_path = os.path.split(os.path.dirname(
os.path.abspath(__file__)))[0]
test_dir = "sahara_tempest_plugin/tests"
full_test_dir = os.path.join(base_path, test_dir)
return full_test_dir, base_path
def register_opts(self, conf):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from tempest import config
from tempest.test_discover import plugins
from sahara_tempest_plugin import config as sahara_config
and context:
# Path: sahara_tempest_plugin/config.py
which might include code, classes, or functions. Output only the next line. | conf.register_opt(sahara_config.service_option, |
Here is a snippet: <|code_start|>
class FakeResponse(object):
def __init__(self, set_id=None, set_status=None, status_description=None,
node_groups=None, url=None, job_id=None, name=None,
job_type=None, verification=None):
self.id = set_id
self.status = set_status
self.status_description = status_description
self.node_groups = node_groups
self.url = url
self.job_id = job_id
self.name = name
self.type = job_type
self.verification = verification
class FakeFlavor(object):
def __init__(self, flavor_id=None, name=None):
self.id = flavor_id
self.name = name
class TestBase(testtools.TestCase):
def setUp(self):
super(TestBase, self).setUp()
with mock.patch(
'sahara_tests.scenario.base.BaseTestCase.__init__'
) as mock_init:
mock_init.return_value = None
<|code_end|>
. Write the next line using the current file imports:
from unittest import mock
from saharaclient.api import cluster_templates
from saharaclient.api import clusters
from saharaclient.api import data_sources
from saharaclient.api import images
from saharaclient.api import job_binaries
from saharaclient.api import job_binary_internals
from saharaclient.api import job_executions
from saharaclient.api import jobs
from saharaclient.api import node_group_templates
from saharaclient.api import plugins
from tempest.lib import exceptions as exc
from sahara_tests.scenario import base
from sahara_tests.scenario import timeouts
import testtools
and context from other files:
# Path: sahara_tests/scenario/base.py
# CHECK_OK_STATUS = "OK"
# CHECK_FAILED_STATUS = "FAILED"
# CLUSTER_STATUS_ACTIVE = "Active"
# CLUSTER_STATUS_ERROR = "Error"
# HEALTH_CHECKS = ["RED", "YELLOW", "GREEN"]
# def track_result(check_name, exit_with_error=True):
# def decorator(fct):
# def wrapper(self, *args, **kwargs):
# def setUpClass(cls):
# def setUp(self):
# def _init_clients(self):
# def create_cluster(self):
# def _get_proxy(self, cluster):
# def check_transient(self):
# def _inject_datasources_data(self, arg, input_url, output_url):
# def _put_io_data_to_configs(self, configs, input_id, output_id):
# def _prepare_job_running(self, job):
# def check_run_jobs(self):
# def _job_batching(self, pre_exec):
# def _create_datasources(self, job):
# def create(ds, name):
# def _create_job_binaries(self, job):
# def _create_job_binary(self, job_binary):
# def _create_job(self, type, mains, libs):
# def _parse_job_configs(self, job):
# def _run_job(self, job_id, input_id, output_id, configs):
# def _poll_jobs_status(self, exec_ids):
# def _get_file_with_defaults(self, file_path):
# def _read_source_file(self, source):
# def _create_swift_data(self, source=None, destination=None):
# def _create_s3_data(self, source=None, destination=None):
# def _create_dfs_data(self, source, destination, hdfs_username, fs):
# def to_hex_present(string):
# def _create_internal_db_data(self, source):
# def _get_swift_container(self):
# def _get_s3_bucket(self):
# def check_scale(self):
# def _validate_scaling(self, after, expected_count):
# def _get_expected_count_of_nodes(self, before, body):
# def check_cinder(self):
# def _get_node_list_with_volumes(self):
# def _create_node_group_templates(self):
# def _get_flavor_id(self, flavor):
# def _create_cluster_template(self):
# def _check_event_logs(self, cluster):
# def _create_cluster(self, cluster_template_id):
# def _poll_cluster_status_tracked(self, cluster_id):
# def _poll_cluster_status(self, cluster_id):
# def _run_command_on_node(self, node_ip, command):
# def _get_nodes_with_process(self, process=None):
# def _get_health_status(self, cluster):
# def _poll_verification_status(self, cluster_id):
# def check_verification(self, cluster_id):
# def __create_node_group_template(self, *args, **kwargs):
# def __create_security_group(self, sg_name):
# def __create_cluster_template(self, *args, **kwargs):
# def __create_cluster(self, *args, **kwargs):
# def __create_datasource(self, *args, **kwargs):
# def __create_internal_db_data(self, *args, **kwargs):
# def __create_job_binary(self, *args, **kwargs):
# def __create_job(self, *args, **kwargs):
# def __run_job(self, *args, **kwargs):
# def __create_container(self, container_name):
# def __upload_to_container(self, container_name, object_name, data=None):
# def __create_bucket(self, bucket_name):
# def __upload_to_bucket(self, bucket_name, object_name, data=None):
# def __create_keypair(self):
# def check_feature_available(self, feature_name):
# def tearDown(self):
# class BaseTestCase(base.BaseTestCase):
#
# Path: sahara_tests/scenario/timeouts.py
# class Defaults(object):
# def __init__(self, config):
# def init_defaults(cls, config):
, which may include functions, classes, or code. Output only the next line. | self.base_scenario = base.BaseTestCase() |
Predict the next line for this snippet: <|code_start|> "source": "sahara_tests/scenario/defaults/"
"edp-examples/edp-pig/"
"top-todoers/data/input"
},
"output_datasource": {
"type": "hdfs",
"destination": "/user/hadoop/edp-output"
},
"main_lib": {
"type": "s3",
"source": "sahara_tests/scenario/defaults/"
"edp-examples/edp-pig/"
"top-todoers/example.pig"
}
}
]
}
}
self.base_scenario.ng_id_map = {'worker': 'set_id', 'master': 'set_id'}
self.base_scenario.ng_name_map = {}
self.base_scenario.key_name = 'test_key'
self.base_scenario.key = 'key_from_yaml'
self.base_scenario.template_path = ('sahara_tests/scenario/templates/'
'vanilla/2.7.1')
self.job = self.base_scenario.testcase["edp_jobs_flow"].get(
'test_flow')[0]
self.base_scenario.cluster_id = 'some_id'
self.base_scenario.proxy_ng_name = False
self.base_scenario.proxy = False
self.base_scenario.setUpClass()
<|code_end|>
with the help of current file imports:
from unittest import mock
from saharaclient.api import cluster_templates
from saharaclient.api import clusters
from saharaclient.api import data_sources
from saharaclient.api import images
from saharaclient.api import job_binaries
from saharaclient.api import job_binary_internals
from saharaclient.api import job_executions
from saharaclient.api import jobs
from saharaclient.api import node_group_templates
from saharaclient.api import plugins
from tempest.lib import exceptions as exc
from sahara_tests.scenario import base
from sahara_tests.scenario import timeouts
import testtools
and context from other files:
# Path: sahara_tests/scenario/base.py
# CHECK_OK_STATUS = "OK"
# CHECK_FAILED_STATUS = "FAILED"
# CLUSTER_STATUS_ACTIVE = "Active"
# CLUSTER_STATUS_ERROR = "Error"
# HEALTH_CHECKS = ["RED", "YELLOW", "GREEN"]
# def track_result(check_name, exit_with_error=True):
# def decorator(fct):
# def wrapper(self, *args, **kwargs):
# def setUpClass(cls):
# def setUp(self):
# def _init_clients(self):
# def create_cluster(self):
# def _get_proxy(self, cluster):
# def check_transient(self):
# def _inject_datasources_data(self, arg, input_url, output_url):
# def _put_io_data_to_configs(self, configs, input_id, output_id):
# def _prepare_job_running(self, job):
# def check_run_jobs(self):
# def _job_batching(self, pre_exec):
# def _create_datasources(self, job):
# def create(ds, name):
# def _create_job_binaries(self, job):
# def _create_job_binary(self, job_binary):
# def _create_job(self, type, mains, libs):
# def _parse_job_configs(self, job):
# def _run_job(self, job_id, input_id, output_id, configs):
# def _poll_jobs_status(self, exec_ids):
# def _get_file_with_defaults(self, file_path):
# def _read_source_file(self, source):
# def _create_swift_data(self, source=None, destination=None):
# def _create_s3_data(self, source=None, destination=None):
# def _create_dfs_data(self, source, destination, hdfs_username, fs):
# def to_hex_present(string):
# def _create_internal_db_data(self, source):
# def _get_swift_container(self):
# def _get_s3_bucket(self):
# def check_scale(self):
# def _validate_scaling(self, after, expected_count):
# def _get_expected_count_of_nodes(self, before, body):
# def check_cinder(self):
# def _get_node_list_with_volumes(self):
# def _create_node_group_templates(self):
# def _get_flavor_id(self, flavor):
# def _create_cluster_template(self):
# def _check_event_logs(self, cluster):
# def _create_cluster(self, cluster_template_id):
# def _poll_cluster_status_tracked(self, cluster_id):
# def _poll_cluster_status(self, cluster_id):
# def _run_command_on_node(self, node_ip, command):
# def _get_nodes_with_process(self, process=None):
# def _get_health_status(self, cluster):
# def _poll_verification_status(self, cluster_id):
# def check_verification(self, cluster_id):
# def __create_node_group_template(self, *args, **kwargs):
# def __create_security_group(self, sg_name):
# def __create_cluster_template(self, *args, **kwargs):
# def __create_cluster(self, *args, **kwargs):
# def __create_datasource(self, *args, **kwargs):
# def __create_internal_db_data(self, *args, **kwargs):
# def __create_job_binary(self, *args, **kwargs):
# def __create_job(self, *args, **kwargs):
# def __run_job(self, *args, **kwargs):
# def __create_container(self, container_name):
# def __upload_to_container(self, container_name, object_name, data=None):
# def __create_bucket(self, bucket_name):
# def __upload_to_bucket(self, bucket_name, object_name, data=None):
# def __create_keypair(self):
# def check_feature_available(self, feature_name):
# def tearDown(self):
# class BaseTestCase(base.BaseTestCase):
#
# Path: sahara_tests/scenario/timeouts.py
# class Defaults(object):
# def __init__(self, config):
# def init_defaults(cls, config):
, which may contain function names, class names, or code. Output only the next line. | timeouts.Defaults.init_defaults(self.base_scenario.testcase) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.