Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Next line prediction: <|code_start|> User = get_user_model() TEST_USERNAME = "admin" TEST_PASSWORD = "battery-horse-staple" class AdminTest(TestCase): @classmethod def setUpTestData(self): <|code_end|> . Use current file imports: (from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from django.utils.translation import override from .app.models import Category, Site from .utils import load_wiki) and context including class names, function names, or small code snippets from other files: # Path: tests/app/models.py # class Category(models.Model): # # name = models.CharField(max_length=255) # title = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name", "title")) # # objects = CategoryQueryset.as_manager() # # def __str__(self): # return self.name # # class Site(models.Model): # name = models.CharField(max_length=255) # # objects = MultilingualManager() # # def __str__(self): # return self.name # # Path: tests/utils.py # def load_wiki(): # wiki = Category.objects.create(name="Wikipedia") # with open(os.path.join("tests", "fixtures", "fulltextsearch.json")) as infile: # data = json.load(infile) # # for article in data: # kwargs = {} # for item in article: # lang = "_" + item["lang"] # # kwargs["title" + lang] = item["title"] # kwargs["body" + lang] = item["body"] # # Blog.objects.create(category=wiki, **kwargs) . Output only the next line.
User.objects.create_superuser(
Based on the snippet: <|code_start|> self.assertContains(response, self.wikipedia.name) with override("nl"): response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, self.wikipedia.name) with override("de"): response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, self.wikipedia.name) def test_non_translated_admin(self): url = reverse("admin:app_site_change", args=(self.site.pk,)) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_search(self): def url(q): return "{}?q={}".format(reverse("admin:app_blog_changelist"), q) with override("nl"): response = self.client.get(url("kker")) self.assertContains(response, "Kikkers") with override("en"): response = self.client.get(url("kker")) self.assertNotContains(response, "Kikkers") <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from django.utils.translation import override from .app.models import Category, Site from .utils import load_wiki and context (classes, functions, sometimes code) from other files: # Path: tests/app/models.py # class Category(models.Model): # # name = models.CharField(max_length=255) # title = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name", "title")) # # objects = CategoryQueryset.as_manager() # # def __str__(self): # return self.name # # class Site(models.Model): # name = models.CharField(max_length=255) # # objects = MultilingualManager() # # def __str__(self): # return self.name # # Path: tests/utils.py # def load_wiki(): # wiki = Category.objects.create(name="Wikipedia") # with open(os.path.join("tests", "fixtures", "fulltextsearch.json")) as infile: # data = json.load(infile) # # for article in data: # kwargs = {} # for item in article: # lang = "_" + item["lang"] # # kwargs["title" + lang] = item["title"] # kwargs["body" + lang] = item["body"] # # Blog.objects.create(category=wiki, **kwargs) . Output only the next line.
response = self.client.get(url("frog"))
Based on the snippet: <|code_start|> template_name = "table.html" class FilteredBlogListView(FilterView, tables.SingleTableView): table_class = BlogTable model = Blog template_name = "table.html" filterset_class = BlogFilter class BlogView(DetailView): model = Blog template_name = "blog.html" class BlogUpdateView(UpdateView): model = Blog fields = ["title_en", "title_i18n", "body_en", "body_i18n", "category"] template_name = "blog_update_form.html" template_name_suffix = "_update_form" # success_url = reverse_lazy('blogs') def fixtures(request): Blog.objects.all().delete() Category.objects.all().delete() <|code_end|> , predict the immediate next line with the help of imports: import json import django_tables2 as tables from django.shortcuts import redirect from django.views.generic import DetailView from django.views.generic.edit import UpdateView from django_filters import FilterSet from django_filters.views import FilterView from .models import Blog, Category and context (classes, functions, sometimes code) from other files: # Path: example/app/models.py # class Blog(models.Model): # title = models.CharField(max_length=255) # body = models.TextField(null=True, blank=True) # # category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) # # i18n = TranslationField(fields=("title", "body")) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # # def __str__(self): # return self.title_i18n # # def get_absolute_url(self): # return reverse("blog_detail", args=(self.pk,)) # # class Category(models.Model): # name = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name",)) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # verbose_name_plural = "categories" # # def __str__(self): # return self.name_i18n . Output only the next line.
with open("data/species.json") as f:
Predict the next line for this snippet: <|code_start|> class BlogTable(tables.Table): title_i18n = tables.LinkColumn("blog_detail", args=(tables.A("pk"),)) edit = tables.TemplateColumn( template_code="""<a href="{% url 'blog-edit' pk=record.pk %}" class="btn btn-sm btn-primary">edit</a>""", empty_values=(), orderable=False, verbose_name="edit", ) class Meta: model = Blog fields = ( # this field should use the active language (from LANGUAGE_CODE) "title_i18n", <|code_end|> with the help of current file imports: import json import django_tables2 as tables from django.shortcuts import redirect from django.views.generic import DetailView from django.views.generic.edit import UpdateView from django_filters import FilterSet from django_filters.views import FilterView from .models import Blog, Category and context from other files: # Path: example/app/models.py # class Blog(models.Model): # title = models.CharField(max_length=255) # body = models.TextField(null=True, blank=True) # # category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) # # i18n = TranslationField(fields=("title", "body")) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # # def __str__(self): # return self.title_i18n # # def get_absolute_url(self): # return reverse("blog_detail", args=(self.pk,)) # # class Category(models.Model): # name = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name",)) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # verbose_name_plural = "categories" # # def __str__(self): # return self.name_i18n , which may contain function names, class names, or code. Output only the next line.
"title_en",
Given the following code snippet before the placeholder: <|code_start|> admin.site.has_permission = disable_admin_login() @admin.register(Blog) class BlogAdmin(ActiveLanguageMixin, admin.ModelAdmin): <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from modeltrans.admin import ActiveLanguageMixin from .models import Blog, Category from .utils import disable_admin_login and context including class names, function names, and sometimes code from other files: # Path: modeltrans/admin.py # class ActiveLanguageMixin: # """ # ModelAdmin mixin to only show fields for the fallback and current language in the change view. # """ # # form_class = TranslationModelForm # # Path: example/app/models.py # class Blog(models.Model): # title = models.CharField(max_length=255) # body = models.TextField(null=True, blank=True) # # category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) # # i18n = TranslationField(fields=("title", "body")) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # # def __str__(self): # return self.title_i18n # # def get_absolute_url(self): # return reverse("blog_detail", args=(self.pk,)) # # class Category(models.Model): # name = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name",)) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # verbose_name_plural = "categories" # # def __str__(self): # return self.name_i18n # # Path: example/app/utils.py # def disable_admin_login(): # """ # Disable admin login, but allow editing. # # amended from: https://stackoverflow.com/a/40008282/517560 # """ # User = get_user_model() # # try: # user, created = User.objects.update_or_create( # id=1, # defaults=dict( # first_name="Default Admin", # last_name="User", # is_superuser=True, # is_active=True, # is_staff=True, # ), # ) # except ProgrammingError: # # auth_user doesn't exist, this allows the migrations to run properly. # user = None # # def no_login_has_permission(request): # setattr(request, "user", user) # # return True # # return no_login_has_permission . Output only the next line.
list_display = ("title_i18n", "category")
Given snippet: <|code_start|> admin.site.has_permission = disable_admin_login() @admin.register(Blog) class BlogAdmin(ActiveLanguageMixin, admin.ModelAdmin): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from modeltrans.admin import ActiveLanguageMixin from .models import Blog, Category from .utils import disable_admin_login and context: # Path: modeltrans/admin.py # class ActiveLanguageMixin: # """ # ModelAdmin mixin to only show fields for the fallback and current language in the change view. # """ # # form_class = TranslationModelForm # # Path: example/app/models.py # class Blog(models.Model): # title = models.CharField(max_length=255) # body = models.TextField(null=True, blank=True) # # category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) # # i18n = TranslationField(fields=("title", "body")) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # # def __str__(self): # return self.title_i18n # # def get_absolute_url(self): # return reverse("blog_detail", args=(self.pk,)) # # class Category(models.Model): # name = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name",)) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # verbose_name_plural = "categories" # # def __str__(self): # return self.name_i18n # # Path: example/app/utils.py # def disable_admin_login(): # """ # Disable admin login, but allow editing. # # amended from: https://stackoverflow.com/a/40008282/517560 # """ # User = get_user_model() # # try: # user, created = User.objects.update_or_create( # id=1, # defaults=dict( # first_name="Default Admin", # last_name="User", # is_superuser=True, # is_active=True, # is_staff=True, # ), # ) # except ProgrammingError: # # auth_user doesn't exist, this allows the migrations to run properly. # user = None # # def no_login_has_permission(request): # setattr(request, "user", user) # # return True # # return no_login_has_permission which might include code, classes, or functions. Output only the next line.
list_display = ("title_i18n", "category")
Next line prediction: <|code_start|> admin.site.has_permission = disable_admin_login() @admin.register(Blog) class BlogAdmin(ActiveLanguageMixin, admin.ModelAdmin): list_display = ("title_i18n", "category") <|code_end|> . Use current file imports: (from django.contrib import admin from modeltrans.admin import ActiveLanguageMixin from .models import Blog, Category from .utils import disable_admin_login) and context including class names, function names, or small code snippets from other files: # Path: modeltrans/admin.py # class ActiveLanguageMixin: # """ # ModelAdmin mixin to only show fields for the fallback and current language in the change view. # """ # # form_class = TranslationModelForm # # Path: example/app/models.py # class Blog(models.Model): # title = models.CharField(max_length=255) # body = models.TextField(null=True, blank=True) # # category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) # # i18n = TranslationField(fields=("title", "body")) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # # def __str__(self): # return self.title_i18n # # def get_absolute_url(self): # return reverse("blog_detail", args=(self.pk,)) # # class Category(models.Model): # name = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name",)) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # verbose_name_plural = "categories" # # def __str__(self): # return self.name_i18n # # Path: example/app/utils.py # def disable_admin_login(): # """ # Disable admin login, but allow editing. # # amended from: https://stackoverflow.com/a/40008282/517560 # """ # User = get_user_model() # # try: # user, created = User.objects.update_or_create( # id=1, # defaults=dict( # first_name="Default Admin", # last_name="User", # is_superuser=True, # is_active=True, # is_staff=True, # ), # ) # except ProgrammingError: # # auth_user doesn't exist, this allows the migrations to run properly. # user = None # # def no_login_has_permission(request): # setattr(request, "user", user) # # return True # # return no_login_has_permission . Output only the next line.
search_fields = ("title_i18n", "category__name_i18n")
Based on the snippet: <|code_start|> admin.site.has_permission = disable_admin_login() @admin.register(Blog) class BlogAdmin(ActiveLanguageMixin, admin.ModelAdmin): <|code_end|> , predict the immediate next line with the help of imports: from django.contrib import admin from modeltrans.admin import ActiveLanguageMixin from .models import Blog, Category from .utils import disable_admin_login and context (classes, functions, sometimes code) from other files: # Path: modeltrans/admin.py # class ActiveLanguageMixin: # """ # ModelAdmin mixin to only show fields for the fallback and current language in the change view. # """ # # form_class = TranslationModelForm # # Path: example/app/models.py # class Blog(models.Model): # title = models.CharField(max_length=255) # body = models.TextField(null=True, blank=True) # # category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) # # i18n = TranslationField(fields=("title", "body")) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # # def __str__(self): # return self.title_i18n # # def get_absolute_url(self): # return reverse("blog_detail", args=(self.pk,)) # # class Category(models.Model): # name = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name",)) # # class Meta: # indexes = [GinIndex(fields=["i18n"])] # verbose_name_plural = "categories" # # def __str__(self): # return self.name_i18n # # Path: example/app/utils.py # def disable_admin_login(): # """ # Disable admin login, but allow editing. # # amended from: https://stackoverflow.com/a/40008282/517560 # """ # User = get_user_model() # # try: # user, created = User.objects.update_or_create( # id=1, # defaults=dict( # first_name="Default Admin", # last_name="User", # is_superuser=True, # is_active=True, # is_staff=True, # ), # ) # except ProgrammingError: # # auth_user doesn't exist, this allows the migrations to run properly. # user = None # # def no_login_has_permission(request): # setattr(request, "user", user) # # return True # # return no_login_has_permission . Output only the next line.
list_display = ("title_i18n", "category")
Given the following code snippet before the placeholder: <|code_start|> class Category(models.Model): name = models.CharField(max_length=255) i18n = TranslationField(fields=("name",)) class Meta: indexes = [GinIndex(fields=["i18n"])] verbose_name_plural = "categories" def __str__(self): return self.name_i18n class Blog(models.Model): <|code_end|> , predict the next line using imports from the current file: from django.contrib.postgres.indexes import GinIndex from django.db import models from django.urls import reverse from modeltrans.fields import TranslationField and context including class names, function names, and sometimes code from other files: # Path: modeltrans/fields.py # class TranslationField(JSONField): # """ # This model field is used to store the translations in the translated model. # # Arguments: # fields (iterable): List of model field names to make translatable. # required_languages (iterable or dict): List of languages required for the model. # If a dict is supplied, the keys must be translated field names with the value # containing a list of required languages for that specific field. # virtual_fields (bool): If `False`, do not add virtual fields to access # translated values with. # Set to `True` during migration from django-modeltranslation to prevent # collisions with it's database fields while having the `i18n` field available. # fallback_language_field: If not None, this should be the name of the field containing a # language code to use as the first language in any fallback chain. # For example: if you have a model instance with 'nl' as language_code, and set # fallback_language_field='language_code', 'nl' will always be tried after the current # language before any other language. # """ # # description = "Translation storage for a model" # # def __init__( # self, # fields=None, # required_languages=None, # virtual_fields=True, # fallback_language_field=None, # *args, # **kwargs, # ): # self.fields = fields or () # self.required_languages = required_languages or () # self.virtual_fields = virtual_fields # self.fallback_language_field = fallback_language_field # # kwargs["editable"] = False # kwargs["null"] = True # super().__init__(*args, **kwargs) # # def deconstruct(self): # name, path, args, kwargs = super().deconstruct() # # del kwargs["editable"] # del kwargs["null"] # kwargs["fields"] = self.fields # kwargs["required_languages"] = self.required_languages # kwargs["virtual_fields"] = self.virtual_fields # # return name, path, args, kwargs # # def get_translated_fields(self): # """Return a generator for all translated fields.""" # for field in self.model._meta.get_fields(): # if isinstance(field, TranslatedVirtualField): # yield field # # def contribute_to_class(self, cls, name): # if name != "i18n": # raise ImproperlyConfigured('{} must have name "i18n"'.format(self.__class__.__name__)) # # super().contribute_to_class(cls, name) . Output only the next line.
title = models.CharField(max_length=255)
Continue the code snippet: <|code_start|> class FallbackConfTest(TestCase): @override_settings(MODELTRANS_FALLBACK={"fy": ("nl", "en")}) def test_fallback_must_have_default(self): message = "MODELTRANS_FALLBACK setting must have a `default` key." with self.assertRaisesMessage(ImproperlyConfigured, message): check_fallback_chain() @override_settings( MODELTRANS_AVAILABLE_LANGUAGES=("nl", "en"), MODELTRANS_FALLBACK={"default": ("en",), "fy": ("nl", "en")}, ) def test_fallback_must_use_available_languages_as_key(self): message = "MODELTRANS_FALLBACK contains language `fy` which is not in MODELTRANS_AVAILABLE_LANGUAGES" with self.assertRaisesMessage(ImproperlyConfigured, message): check_fallback_chain() <|code_end|> . Use current file imports: from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings from modeltrans.conf import check_fallback_chain, get_available_languages_setting and context (classes, functions, or code) from other files: # Path: modeltrans/conf.py # def check_fallback_chain(): # MODELTRANS_FALLBACK = get_modeltrans_setting("MODELTRANS_FALLBACK") # MODELTRANS_AVAILABLE_LANGUAGES = get_available_languages(include_default=True) # # if "default" not in MODELTRANS_FALLBACK: # raise ImproperlyConfigured("MODELTRANS_FALLBACK setting must have a `default` key.") # # message_fmt = ( # "MODELTRANS_FALLBACK contains language `{}` " # "which is not in MODELTRANS_AVAILABLE_LANGUAGES" # ) # for lang, chain in MODELTRANS_FALLBACK.items(): # if lang != "default" and lang not in MODELTRANS_AVAILABLE_LANGUAGES: # raise ImproperlyConfigured(message_fmt.format(lang)) # for lang in chain: # if lang not in MODELTRANS_AVAILABLE_LANGUAGES: # raise ImproperlyConfigured(message_fmt.format(lang)) # # def get_available_languages_setting(): # """ # list of available languages for modeltrans translations. # defaults to the list of language codes extracted from django setting LANGUAGES # """ # languages = tuple( # set( # getattr( # settings, # "MODELTRANS_AVAILABLE_LANGUAGES", # (code for code, _ in getattr(settings, "LANGUAGES")), # ) # ) # ) # # if not all(isinstance(x, str) for x in languages): # raise ImproperlyConfigured( # "MODELTRANS_AVAILABLE_LANGUAGES should be an iterable of strings" # ) # # # make sure LANGUAGE_CODE is not in available languages # return (lang for lang in languages if lang != get_default_language()) . Output only the next line.
@override_settings(
Predict the next line after this snippet: <|code_start|> class FallbackConfTest(TestCase): @override_settings(MODELTRANS_FALLBACK={"fy": ("nl", "en")}) def test_fallback_must_have_default(self): message = "MODELTRANS_FALLBACK setting must have a `default` key." with self.assertRaisesMessage(ImproperlyConfigured, message): check_fallback_chain() @override_settings( MODELTRANS_AVAILABLE_LANGUAGES=("nl", "en"), MODELTRANS_FALLBACK={"default": ("en",), "fy": ("nl", "en")}, ) def test_fallback_must_use_available_languages_as_key(self): message = "MODELTRANS_FALLBACK contains language `fy` which is not in MODELTRANS_AVAILABLE_LANGUAGES" with self.assertRaisesMessage(ImproperlyConfigured, message): check_fallback_chain() @override_settings( MODELTRANS_AVAILABLE_LANGUAGES=("fy", "nl", "en"), MODELTRANS_FALLBACK={"default": ("en",), "fy": ("nl", "fr", "en")}, ) def test_fallback_must_use_available_languages_in_chain(self): message = "MODELTRANS_FALLBACK contains language `fr` which is not in MODELTRANS_AVAILABLE_LANGUAGES" <|code_end|> using the current file's imports: from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings from modeltrans.conf import check_fallback_chain, get_available_languages_setting and any relevant context from other files: # Path: modeltrans/conf.py # def check_fallback_chain(): # MODELTRANS_FALLBACK = get_modeltrans_setting("MODELTRANS_FALLBACK") # MODELTRANS_AVAILABLE_LANGUAGES = get_available_languages(include_default=True) # # if "default" not in MODELTRANS_FALLBACK: # raise ImproperlyConfigured("MODELTRANS_FALLBACK setting must have a `default` key.") # # message_fmt = ( # "MODELTRANS_FALLBACK contains language `{}` " # "which is not in MODELTRANS_AVAILABLE_LANGUAGES" # ) # for lang, chain in MODELTRANS_FALLBACK.items(): # if lang != "default" and lang not in MODELTRANS_AVAILABLE_LANGUAGES: # raise ImproperlyConfigured(message_fmt.format(lang)) # for lang in chain: # if lang not in MODELTRANS_AVAILABLE_LANGUAGES: # raise ImproperlyConfigured(message_fmt.format(lang)) # # def get_available_languages_setting(): # """ # list of available languages for modeltrans translations. # defaults to the list of language codes extracted from django setting LANGUAGES # """ # languages = tuple( # set( # getattr( # settings, # "MODELTRANS_AVAILABLE_LANGUAGES", # (code for code, _ in getattr(settings, "LANGUAGES")), # ) # ) # ) # # if not all(isinstance(x, str) for x in languages): # raise ImproperlyConfigured( # "MODELTRANS_AVAILABLE_LANGUAGES should be an iterable of strings" # ) # # # make sure LANGUAGE_CODE is not in available languages # return (lang for lang in languages if lang != get_default_language()) . Output only the next line.
with self.assertRaisesMessage(ImproperlyConfigured, message):
Given the following code snippet before the placeholder: <|code_start|> @admin.register(Blog) class BlogAdmin(admin.ModelAdmin): list_display = ("title_i18n", "category") search_fields = ("title_i18n", "category__name_i18n", "site__name") @admin.register(Category) class CategoryAdmin(ActiveLanguageMixin, admin.ModelAdmin): pass @admin.register(Site) class SiteAdmin(ActiveLanguageMixin, admin.ModelAdmin): <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from modeltrans.admin import ActiveLanguageMixin from .models import Blog, Category, Site and context including class names, function names, and sometimes code from other files: # Path: modeltrans/admin.py # class ActiveLanguageMixin: # """ # ModelAdmin mixin to only show fields for the fallback and current language in the change view. # """ # # form_class = TranslationModelForm # # Path: tests/app/models.py # class Blog(models.Model): # title = models.CharField(max_length=255) # body = models.TextField(null=True) # # category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) # site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE) # # i18n = TranslationField(fields=("title", "body"), required_languages=("nl",)) # # def __str__(self): # return self.title # # class Category(models.Model): # # name = models.CharField(max_length=255) # title = models.CharField(max_length=255) # # i18n = TranslationField(fields=("name", "title")) # # objects = CategoryQueryset.as_manager() # # def __str__(self): # return self.name # # class Site(models.Model): # name = models.CharField(max_length=255) # # objects = MultilingualManager() # # def __str__(self): # return self.name . Output only the next line.
pass
Predict the next line for this snippet: <|code_start|> try: # django==3.1 moved JSONField into django.db.models except ImportError: SUPPORTED_FIELDS = (fields.CharField, fields.TextField) DEFAULT_LANGUAGE = get_default_language() <|code_end|> with the help of current file imports: from django.core.exceptions import ImproperlyConfigured from django.db.models import F, fields from django.db.models.functions import Cast, Coalesce from django.utils.translation import gettext_lazy as _ from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting from .utils import ( FallbackTransform, build_localized_fieldname, get_instance_field_value, get_language, ) from django.db.models import JSONField from django.db.models.fields.json import KeyTextTransform from django.contrib.postgres.fields import JSONField from django.contrib.postgres.fields.jsonb import KeyTextTransform and context from other files: # Path: modeltrans/conf.py # def get_default_language(): # return settings.LANGUAGE_CODE # # def get_fallback_chain(lang): # """ # Returns the list of fallback languages for language `lang`. # # For example, this function will return `('nl', 'en')` when called # with `lang='fy'` and configured like this:: # # LANGUAGE_CODE = 'en' # # MODELTRANS_FALLBACK = { # 'default': (LANGUAGE_CODE, ), # 'fy': ('nl', 'en') # } # """ # MODELTRANS_FALLBACK = get_modeltrans_setting("MODELTRANS_FALLBACK") # # if lang not in MODELTRANS_FALLBACK.keys(): # lang = "default" # # return MODELTRANS_FALLBACK[lang] # # def get_modeltrans_setting(key): # modeltrans_settings = { # "MODELTRANS_AVAILABLE_LANGUAGES": get_available_languages(), # "MODELTRANS_FALLBACK": getattr( # settings, "MODELTRANS_FALLBACK", {"default": (get_default_language(),)} # ), # "MODELTRANS_ADD_FIELD_HELP_TEXT": getattr(settings, "MODELTRANS_ADD_FIELD_HELP_TEXT", True), # } # return modeltrans_settings.get(key) # # Path: modeltrans/utils.py # class FallbackTransform(Transform): # """ # Custom version of KeyTextTransform to use a database field as part of the key. # # For example: with default_language="nl", calling # `FallbackTransform("title_", F("fallback_language"), "i18n")` becomes in SQL" # `"i18n"->>('title_' || "fallback_language")` # """ # # def __init__(self, field_prefix, language_expression, *args, **kwargs): # super().__init__(*args, **kwargs) # self.field_prefix = field_prefix # self.language_expression = language_expression # # def preprocess_lhs(self, compiler, connection, lhs_only=False): # if not lhs_only: # key_transforms = [self.field_prefix] # previous = self.lhs # while isinstance(previous, KeyTransform): # if not lhs_only: # key_transforms.insert(0, previous.key_name) # previous = previous.lhs # lhs, params = compiler.compile(previous) # return (lhs, params, key_transforms) if not lhs_only else (lhs, params) # # def as_postgresql(self, compiler, connection): # lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) # params.extend([self.field_prefix]) # # rhs = self.language_expression.resolve_expression(compiler.query) # rhs_sql, rhs_params = compiler.compile(rhs) # params.extend(rhs_params) # # return "(%s ->> (%%s || %s ))" % (lhs, rhs_sql), (params) # # def build_localized_fieldname(field_name, lang, ignore_default=False): # if lang == "id": # # The 2-letter Indonesian language code is problematic with the # # current naming scheme as Django foreign keys also add "id" suffix. # lang = "ind" # if ignore_default and lang == get_default_language(): # return field_name # return "{}_{}".format(field_name, lang.replace("-", "_")) # # def get_instance_field_value(instance, path): # """ # Return the value of a field or related field for a model instance. # """ # value = instance # for bit in path.split(LOOKUP_SEP): # try: # value = getattr(value, bit) # except AttributeError: # return None # # return value # # def get_language(): # """ # Return an active language code that is guaranteed to be in settings.LANGUAGES # # (Django does not seem to guarantee this for us.) # """ # lang = _get_language() # if lang in get_available_languages(): # return lang # return get_default_language() , which may contain function names, class names, or code. Output only the next line.
def translated_field_factory(original_field, language=None, *args, **kwargs):
Using the snippet: <|code_start|> try: # django==3.1 moved JSONField into django.db.models except ImportError: SUPPORTED_FIELDS = (fields.CharField, fields.TextField) DEFAULT_LANGUAGE = get_default_language() def translated_field_factory(original_field, language=None, *args, **kwargs): if not isinstance(original_field, SUPPORTED_FIELDS): raise ImproperlyConfigured( "{} is not supported by django-modeltrans.".format(original_field.__class__.__name__) <|code_end|> , determine the next line of code. You have imports: from django.core.exceptions import ImproperlyConfigured from django.db.models import F, fields from django.db.models.functions import Cast, Coalesce from django.utils.translation import gettext_lazy as _ from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting from .utils import ( FallbackTransform, build_localized_fieldname, get_instance_field_value, get_language, ) from django.db.models import JSONField from django.db.models.fields.json import KeyTextTransform from django.contrib.postgres.fields import JSONField from django.contrib.postgres.fields.jsonb import KeyTextTransform and context (class names, function names, or code) available: # Path: modeltrans/conf.py # def get_default_language(): # return settings.LANGUAGE_CODE # # def get_fallback_chain(lang): # """ # Returns the list of fallback languages for language `lang`. # # For example, this function will return `('nl', 'en')` when called # with `lang='fy'` and configured like this:: # # LANGUAGE_CODE = 'en' # # MODELTRANS_FALLBACK = { # 'default': (LANGUAGE_CODE, ), # 'fy': ('nl', 'en') # } # """ # MODELTRANS_FALLBACK = get_modeltrans_setting("MODELTRANS_FALLBACK") # # if lang not in MODELTRANS_FALLBACK.keys(): # lang = "default" # # return MODELTRANS_FALLBACK[lang] # # def get_modeltrans_setting(key): # modeltrans_settings = { # "MODELTRANS_AVAILABLE_LANGUAGES": get_available_languages(), # "MODELTRANS_FALLBACK": getattr( # settings, "MODELTRANS_FALLBACK", {"default": (get_default_language(),)} # ), # "MODELTRANS_ADD_FIELD_HELP_TEXT": getattr(settings, "MODELTRANS_ADD_FIELD_HELP_TEXT", True), # } # return modeltrans_settings.get(key) # # Path: modeltrans/utils.py # class FallbackTransform(Transform): # """ # Custom version of KeyTextTransform to use a database field as part of the key. # # For example: with default_language="nl", calling # `FallbackTransform("title_", F("fallback_language"), "i18n")` becomes in SQL" # `"i18n"->>('title_' || "fallback_language")` # """ # # def __init__(self, field_prefix, language_expression, *args, **kwargs): # super().__init__(*args, **kwargs) # self.field_prefix = field_prefix # self.language_expression = language_expression # # def preprocess_lhs(self, compiler, connection, lhs_only=False): # if not lhs_only: # key_transforms = [self.field_prefix] # previous = self.lhs # while isinstance(previous, KeyTransform): # if not lhs_only: # key_transforms.insert(0, previous.key_name) # previous = previous.lhs # lhs, params = compiler.compile(previous) # return (lhs, params, key_transforms) if not lhs_only else (lhs, params) # # def as_postgresql(self, compiler, connection): # lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) # params.extend([self.field_prefix]) # # rhs = self.language_expression.resolve_expression(compiler.query) # rhs_sql, rhs_params = compiler.compile(rhs) # params.extend(rhs_params) # # return "(%s ->> (%%s || %s ))" % (lhs, rhs_sql), (params) # # def build_localized_fieldname(field_name, lang, ignore_default=False): # if lang == "id": # # The 2-letter Indonesian language code is problematic with the # # current naming scheme as Django foreign keys also add "id" suffix. # lang = "ind" # if ignore_default and lang == get_default_language(): # return field_name # return "{}_{}".format(field_name, lang.replace("-", "_")) # # def get_instance_field_value(instance, path): # """ # Return the value of a field or related field for a model instance. # """ # value = instance # for bit in path.split(LOOKUP_SEP): # try: # value = getattr(value, bit) # except AttributeError: # return None # # return value # # def get_language(): # """ # Return an active language code that is guaranteed to be in settings.LANGUAGES # # (Django does not seem to guarantee this for us.) # """ # lang = _get_language() # if lang in get_available_languages(): # return lang # return get_default_language() . Output only the next line.
)
Using the snippet: <|code_start|> try: # django==3.1 moved JSONField into django.db.models except ImportError: SUPPORTED_FIELDS = (fields.CharField, fields.TextField) DEFAULT_LANGUAGE = get_default_language() def translated_field_factory(original_field, language=None, *args, **kwargs): if not isinstance(original_field, SUPPORTED_FIELDS): raise ImproperlyConfigured( "{} is not supported by django-modeltrans.".format(original_field.__class__.__name__) ) class Specific(TranslatedVirtualField, original_field.__class__): pass Specific.__name__ = "Translated{}".format(original_field.__class__.__name__) <|code_end|> , determine the next line of code. You have imports: from django.core.exceptions import ImproperlyConfigured from django.db.models import F, fields from django.db.models.functions import Cast, Coalesce from django.utils.translation import gettext_lazy as _ from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting from .utils import ( FallbackTransform, build_localized_fieldname, get_instance_field_value, get_language, ) from django.db.models import JSONField from django.db.models.fields.json import KeyTextTransform from django.contrib.postgres.fields import JSONField from django.contrib.postgres.fields.jsonb import KeyTextTransform and context (class names, function names, or code) available: # Path: modeltrans/conf.py # def get_default_language(): # return settings.LANGUAGE_CODE # # def get_fallback_chain(lang): # """ # Returns the list of fallback languages for language `lang`. # # For example, this function will return `('nl', 'en')` when called # with `lang='fy'` and configured like this:: # # LANGUAGE_CODE = 'en' # # MODELTRANS_FALLBACK = { # 'default': (LANGUAGE_CODE, ), # 'fy': ('nl', 'en') # } # """ # MODELTRANS_FALLBACK = get_modeltrans_setting("MODELTRANS_FALLBACK") # # if lang not in MODELTRANS_FALLBACK.keys(): # lang = "default" # # return MODELTRANS_FALLBACK[lang] # # def get_modeltrans_setting(key): # modeltrans_settings = { # "MODELTRANS_AVAILABLE_LANGUAGES": get_available_languages(), # "MODELTRANS_FALLBACK": getattr( # settings, "MODELTRANS_FALLBACK", {"default": (get_default_language(),)} # ), # "MODELTRANS_ADD_FIELD_HELP_TEXT": getattr(settings, "MODELTRANS_ADD_FIELD_HELP_TEXT", True), # } # return modeltrans_settings.get(key) # # Path: modeltrans/utils.py # class FallbackTransform(Transform): # """ # Custom version of KeyTextTransform to use a database field as part of the key. # # For example: with default_language="nl", calling # `FallbackTransform("title_", F("fallback_language"), "i18n")` becomes in SQL" # `"i18n"->>('title_' || "fallback_language")` # """ # # def __init__(self, field_prefix, language_expression, *args, **kwargs): # super().__init__(*args, **kwargs) # self.field_prefix = field_prefix # self.language_expression = language_expression # # def preprocess_lhs(self, compiler, connection, lhs_only=False): # if not lhs_only: # key_transforms = [self.field_prefix] # previous = self.lhs # while isinstance(previous, KeyTransform): # if not lhs_only: # key_transforms.insert(0, previous.key_name) # previous = previous.lhs # lhs, params = compiler.compile(previous) # return (lhs, params, key_transforms) if not lhs_only else (lhs, params) # # def as_postgresql(self, compiler, connection): # lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) # params.extend([self.field_prefix]) # # rhs = self.language_expression.resolve_expression(compiler.query) # rhs_sql, rhs_params = compiler.compile(rhs) # params.extend(rhs_params) # # return "(%s ->> (%%s || %s ))" % (lhs, rhs_sql), (params) # # def build_localized_fieldname(field_name, lang, ignore_default=False): # if lang == "id": # # The 2-letter Indonesian language code is problematic with the # # current naming scheme as Django foreign keys also add "id" suffix. # lang = "ind" # if ignore_default and lang == get_default_language(): # return field_name # return "{}_{}".format(field_name, lang.replace("-", "_")) # # def get_instance_field_value(instance, path): # """ # Return the value of a field or related field for a model instance. # """ # value = instance # for bit in path.split(LOOKUP_SEP): # try: # value = getattr(value, bit) # except AttributeError: # return None # # return value # # def get_language(): # """ # Return an active language code that is guaranteed to be in settings.LANGUAGES # # (Django does not seem to guarantee this for us.) # """ # lang = _get_language() # if lang in get_available_languages(): # return lang # return get_default_language() . Output only the next line.
return Specific(original_field, language, *args, **kwargs)
Predict the next line for this snippet: <|code_start|> try: # django==3.1 moved JSONField into django.db.models except ImportError: SUPPORTED_FIELDS = (fields.CharField, fields.TextField) DEFAULT_LANGUAGE = get_default_language() def translated_field_factory(original_field, language=None, *args, **kwargs): if not isinstance(original_field, SUPPORTED_FIELDS): raise ImproperlyConfigured( "{} is not supported by django-modeltrans.".format(original_field.__class__.__name__) ) <|code_end|> with the help of current file imports: from django.core.exceptions import ImproperlyConfigured from django.db.models import F, fields from django.db.models.functions import Cast, Coalesce from django.utils.translation import gettext_lazy as _ from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting from .utils import ( FallbackTransform, build_localized_fieldname, get_instance_field_value, get_language, ) from django.db.models import JSONField from django.db.models.fields.json import KeyTextTransform from django.contrib.postgres.fields import JSONField from django.contrib.postgres.fields.jsonb import KeyTextTransform and context from other files: # Path: modeltrans/conf.py # def get_default_language(): # return settings.LANGUAGE_CODE # # def get_fallback_chain(lang): # """ # Returns the list of fallback languages for language `lang`. # # For example, this function will return `('nl', 'en')` when called # with `lang='fy'` and configured like this:: # # LANGUAGE_CODE = 'en' # # MODELTRANS_FALLBACK = { # 'default': (LANGUAGE_CODE, ), # 'fy': ('nl', 'en') # } # """ # MODELTRANS_FALLBACK = get_modeltrans_setting("MODELTRANS_FALLBACK") # # if lang not in MODELTRANS_FALLBACK.keys(): # lang = "default" # # return MODELTRANS_FALLBACK[lang] # # def get_modeltrans_setting(key): # modeltrans_settings = { # "MODELTRANS_AVAILABLE_LANGUAGES": get_available_languages(), # "MODELTRANS_FALLBACK": getattr( # settings, "MODELTRANS_FALLBACK", {"default": (get_default_language(),)} # ), # "MODELTRANS_ADD_FIELD_HELP_TEXT": getattr(settings, "MODELTRANS_ADD_FIELD_HELP_TEXT", True), # } # return modeltrans_settings.get(key) # # Path: modeltrans/utils.py # class FallbackTransform(Transform): # """ # Custom version of KeyTextTransform to use a database field as part of the key. # # For example: with default_language="nl", calling # `FallbackTransform("title_", F("fallback_language"), "i18n")` becomes in SQL" # `"i18n"->>('title_' || "fallback_language")` # """ # # def __init__(self, field_prefix, language_expression, *args, **kwargs): # super().__init__(*args, **kwargs) # self.field_prefix = field_prefix # self.language_expression = language_expression # # def preprocess_lhs(self, compiler, connection, lhs_only=False): # if not lhs_only: # key_transforms = [self.field_prefix] # previous = self.lhs # while isinstance(previous, KeyTransform): # if not lhs_only: # key_transforms.insert(0, previous.key_name) # previous = previous.lhs # lhs, params = compiler.compile(previous) # return (lhs, params, key_transforms) if not lhs_only else (lhs, params) # # def as_postgresql(self, compiler, connection): # lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) # params.extend([self.field_prefix]) # # rhs = self.language_expression.resolve_expression(compiler.query) # rhs_sql, rhs_params = compiler.compile(rhs) # params.extend(rhs_params) # # return "(%s ->> (%%s || %s ))" % (lhs, rhs_sql), (params) # # def build_localized_fieldname(field_name, lang, ignore_default=False): # if lang == "id": # # The 2-letter Indonesian language code is problematic with the # # current naming scheme as Django foreign keys also add "id" suffix. # lang = "ind" # if ignore_default and lang == get_default_language(): # return field_name # return "{}_{}".format(field_name, lang.replace("-", "_")) # # def get_instance_field_value(instance, path): # """ # Return the value of a field or related field for a model instance. # """ # value = instance # for bit in path.split(LOOKUP_SEP): # try: # value = getattr(value, bit) # except AttributeError: # return None # # return value # # def get_language(): # """ # Return an active language code that is guaranteed to be in settings.LANGUAGES # # (Django does not seem to guarantee this for us.) # """ # lang = _get_language() # if lang in get_available_languages(): # return lang # return get_default_language() , which may contain function names, class names, or code. Output only the next line.
class Specific(TranslatedVirtualField, original_field.__class__):
Given snippet: <|code_start|> try: # django==3.1 moved JSONField into django.db.models except ImportError: SUPPORTED_FIELDS = (fields.CharField, fields.TextField) DEFAULT_LANGUAGE = get_default_language() def translated_field_factory(original_field, language=None, *args, **kwargs): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.core.exceptions import ImproperlyConfigured from django.db.models import F, fields from django.db.models.functions import Cast, Coalesce from django.utils.translation import gettext_lazy as _ from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting from .utils import ( FallbackTransform, build_localized_fieldname, get_instance_field_value, get_language, ) from django.db.models import JSONField from django.db.models.fields.json import KeyTextTransform from django.contrib.postgres.fields import JSONField from django.contrib.postgres.fields.jsonb import KeyTextTransform and context: # Path: modeltrans/conf.py # def get_default_language(): # return settings.LANGUAGE_CODE # # def get_fallback_chain(lang): # """ # Returns the list of fallback languages for language `lang`. # # For example, this function will return `('nl', 'en')` when called # with `lang='fy'` and configured like this:: # # LANGUAGE_CODE = 'en' # # MODELTRANS_FALLBACK = { # 'default': (LANGUAGE_CODE, ), # 'fy': ('nl', 'en') # } # """ # MODELTRANS_FALLBACK = get_modeltrans_setting("MODELTRANS_FALLBACK") # # if lang not in MODELTRANS_FALLBACK.keys(): # lang = "default" # # return MODELTRANS_FALLBACK[lang] # # def get_modeltrans_setting(key): # modeltrans_settings = { # "MODELTRANS_AVAILABLE_LANGUAGES": get_available_languages(), # "MODELTRANS_FALLBACK": getattr( # settings, "MODELTRANS_FALLBACK", {"default": (get_default_language(),)} # ), # "MODELTRANS_ADD_FIELD_HELP_TEXT": getattr(settings, "MODELTRANS_ADD_FIELD_HELP_TEXT", True), # } # return modeltrans_settings.get(key) # # Path: modeltrans/utils.py # class FallbackTransform(Transform): # """ # Custom version of KeyTextTransform to use a database field as part of the key. # # For example: with default_language="nl", calling # `FallbackTransform("title_", F("fallback_language"), "i18n")` becomes in SQL" # `"i18n"->>('title_' || "fallback_language")` # """ # # def __init__(self, field_prefix, language_expression, *args, **kwargs): # super().__init__(*args, **kwargs) # self.field_prefix = field_prefix # self.language_expression = language_expression # # def preprocess_lhs(self, compiler, connection, lhs_only=False): # if not lhs_only: # key_transforms = [self.field_prefix] # previous = self.lhs # while isinstance(previous, KeyTransform): # if not lhs_only: # key_transforms.insert(0, previous.key_name) # previous = previous.lhs # lhs, params = compiler.compile(previous) # return (lhs, params, key_transforms) if not lhs_only else (lhs, params) # # def as_postgresql(self, compiler, connection): # lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) # params.extend([self.field_prefix]) # # rhs = self.language_expression.resolve_expression(compiler.query) # rhs_sql, rhs_params = compiler.compile(rhs) # params.extend(rhs_params) # # return "(%s ->> (%%s || %s ))" % (lhs, rhs_sql), (params) # # def build_localized_fieldname(field_name, lang, ignore_default=False): # if lang == "id": # # The 2-letter Indonesian language code is problematic with the # # current naming scheme as Django foreign keys also add "id" suffix. # lang = "ind" # if ignore_default and lang == get_default_language(): # return field_name # return "{}_{}".format(field_name, lang.replace("-", "_")) # # def get_instance_field_value(instance, path): # """ # Return the value of a field or related field for a model instance. # """ # value = instance # for bit in path.split(LOOKUP_SEP): # try: # value = getattr(value, bit) # except AttributeError: # return None # # return value # # def get_language(): # """ # Return an active language code that is guaranteed to be in settings.LANGUAGES # # (Django does not seem to guarantee this for us.) # """ # lang = _get_language() # if lang in get_available_languages(): # return lang # return get_default_language() which might include code, classes, or functions. Output only the next line.
if not isinstance(original_field, SUPPORTED_FIELDS):
Given the following code snippet before the placeholder: <|code_start|> FRIENDLY_NAME = 'Time' class Form(forms.Form): when = SmartDateField(label='Expire on') <|code_end|> , predict the next line using imports from the current file: from django import forms from web.models import Quota from web.forms import SmartDateField from core.util import smart_datetime from core.util import smart_datetime from django.utils import timezone and context including class names, function names, and sometimes code from other files: # Path: web/models.py # class Quota(models.Model): # account = models.ForeignKey(ProxyAccount, on_delete=models.CASCADE) # enabled = models.BooleanField(default=True) # last_trigged = models.DateTimeField(auto_now_add=True, blank=True) # comment = models.CharField(max_length=140, default='') # # is_alias_of = models.ForeignKey('self', on_delete=models.CASCADE, default=-1) # clone type and param from this one # type = models.CharField(default='Unconfigured', max_length=20) # param = JSONField(default={}) # # synced = False # alias_target_enabled = True # # def update_from_alias(self, forced=False): # '''Copy type and param from the alias target, if is_alias_of is set. # # Call this function before reading type or param. # ''' # if not forced and self.synced: # return # self.synced = True # if self.is_alias_of_id != -1 : # a = self.is_alias_of # self.type = a.type # self.param = a.param # self.alias_target_enabled = a.enabled # # @property # def is_really_enabled(self): # self.update_from_alias() # return self.alias_target_enabled and self.enabled and self.account.enabled # # @property # def module(self): # self.update_from_alias() # return getQuotaModule(self.type) # # @property # def name(self): # return self.module.FRIENDLY_NAME # # def descript(self, is_admin=False): # return self.module.descript(self, is_admin) # # def trig(self): # self.account.enabled = False # self.account.save() # self.reset() # # def reset(self): # from django.utils import timezone # self.last_trigged = timezone.now() # self.save() # # def is_exceeded(self): # try: # return self.module.is_exceeded(self) # except Exception as e: # from core.util import print_exception # print_exception(e) # print('Failed to judge Quota %d status', self.pk) # return False # # Path: web/forms.py # class SmartDateField(forms.Field): # def __init__(self, *args, **kwargs): # super(SmartDateField, self).__init__(*args, **kwargs) # # def to_python(self, value): # value = force_text(value) # return value # # def widget_attrs(self, widget): # attrs = super(SmartDateField, self).widget_attrs(widget) # attrs['data-smartdate'] = 'true' # return attrs . Output only the next line.
def descript(q, is_admin=False):
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Shadowsocks service # from __future__ import absolute_import, print_function config = { "executable": "ssserver", "config-file": "/etc/shadowsocks.json", <|code_end|> , predict the immediate next line with the help of imports: import base64 import json import logging import time import os import random from collections import OrderedDict from core.util import get_stdout, encodeURIComponent, random_password from core.ssutil import ShadowsocksStat from web.models import TrafficStat, ProxyAccount from core.util import html_strip_table from django import forms from web.forms import VisiblePasswordField and context (classes, functions, sometimes code) from other files: # Path: core/util.py # def get_stdout(*args): # ''' # Execute an application, returning (stdout, exitcode) # # Example: # response, retval = get_stdout(["whoami"]) # ''' # import subprocess # p = subprocess.Popen(*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) # o = [] # p.stdin.close() # with p.stdout: # for line in iter(p.stdout.readline, b''): # o.append(line) # p.wait() # wait for the subprocess to exit # return ''.join(o), p.returncode # # def encodeURIComponent(str): # return urllib.quote(str, safe='~()*!.\'') # # def random_password(N=16): # import random, string # return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) # # Path: core/ssutil.py # class ShadowsocksStat: # def __init__(self, manager_address, loop): # self.loop = loop # self.ctx = ShadowsocksCtx(manager_address) # self.manager_address = manager_address # self.callback=None # # def set_callback(self, callback): # '''the callback when new traffic statistic data comes # # def callback(dict):... # ''' # self.callback=callback # # def add_to_loop(self): # self.ctx.connect() # self.ctx.command('ping') # self.loop.add(self.ctx, eventloop.POLL_IN, self) # # def handle_event(self, sock, fd, event): # if sock == self.ctx and event == eventloop.POLL_IN: # data = self.ctx.recv(4096) # data = common.to_str(data) # if data.startswith('stat:'): # data = data.split('stat:')[1] # stat_data = json.loads(data) # if self.callback: self.callback(stat_data) # # Path: web/models.py # class TrafficStat(models.Model): # account = models.ForeignKey(ProxyAccount, on_delete=models.CASCADE) # time = models.DateTimeField(auto_now_add=True, blank=True) # amount = models.IntegerField() # # class ProxyAccount(models.Model): # user = models.ForeignKey(auth_models.User) # service = models.CharField(max_length=130) # enabled = models.BooleanField(default=False) # config = JSONField(default={}) # log = models.TextField(default="") # created_at = models.DateTimeField(auto_now_add=True, blank=True) # expire_when = models.DateTimeField(auto_now_add=True, blank=True) # # @property # def is_active(self): # return self.enabled and self.user.is_active # # def stop_service(self): # '''DANGEROUS: unconditionally stop service for this account''' # getService(self.service).remove(self.config) # # def start_service(self): # '''DANGEROUS: unconditionally start service for this account''' # getService(self.service).add(self.config) # # def save(self, *args, **kw): # self.config['id'] = self.pk # try: # orig = ProxyAccount.objects.get(pk=self.pk) # serv = getService(self.service) # # a_orig = orig.is_active # a_curr = self.is_active # # if not a_orig and a_curr: serv.add(self.config) # add # if a_orig and not a_curr: serv.remove(self.config) # remove # if a_orig and a_curr: serv.update(self.config) # update # # except ProxyAccount.DoesNotExist as e: # pass # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to update service for ProxyAccount %d", self.pk) # super(ProxyAccount, self).save(*args, **kw) # # def delete(self, *args, **kw): # try: # if self.is_active: # getService(self.service).remove(self.config) # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to stop ProxyAccount %d before deleting", self.pk) # super(ProxyAccount, self).delete(*args, **kw) # # @property # def html(self): # cl = getService(self.service) # return cl.html(self.config) # # @property # def form(self): # cl = getService(self.service) # return cl.UserForm # # @property # def adminForm(self): # cl = getService(self.service) # return cl.AdminForm # # Path: web/forms.py # class VisiblePasswordField(forms.CharField): # def __init__(self, *args, **kwargs): # super(VisiblePasswordField, self).__init__(*args, **kwargs) # # def widget_attrs(self, widget): # attrs = super(VisiblePasswordField, self).widget_attrs(widget) # attrs['data-visiblepass'] = 'true' # return attrs . Output only the next line.
"manager-address": "/var/run/shadowsocks-manager.sock",
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Shadowsocks service # from __future__ import absolute_import, print_function config = { "executable": "ssserver", "config-file": "/etc/shadowsocks.json", "manager-address": "/var/run/shadowsocks-manager.sock", <|code_end|> , predict the immediate next line with the help of imports: import base64 import json import logging import time import os import random from collections import OrderedDict from core.util import get_stdout, encodeURIComponent, random_password from core.ssutil import ShadowsocksStat from web.models import TrafficStat, ProxyAccount from core.util import html_strip_table from django import forms from web.forms import VisiblePasswordField and context (classes, functions, sometimes code) from other files: # Path: core/util.py # def get_stdout(*args): # ''' # Execute an application, returning (stdout, exitcode) # # Example: # response, retval = get_stdout(["whoami"]) # ''' # import subprocess # p = subprocess.Popen(*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) # o = [] # p.stdin.close() # with p.stdout: # for line in iter(p.stdout.readline, b''): # o.append(line) # p.wait() # wait for the subprocess to exit # return ''.join(o), p.returncode # # def encodeURIComponent(str): # return urllib.quote(str, safe='~()*!.\'') # # def random_password(N=16): # import random, string # return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) # # Path: core/ssutil.py # class ShadowsocksStat: # def __init__(self, manager_address, loop): # self.loop = loop # self.ctx = ShadowsocksCtx(manager_address) # self.manager_address = manager_address # self.callback=None # # def set_callback(self, callback): # '''the callback when new traffic statistic data comes # # def callback(dict):... # ''' # self.callback=callback # # def add_to_loop(self): # self.ctx.connect() # self.ctx.command('ping') # self.loop.add(self.ctx, eventloop.POLL_IN, self) # # def handle_event(self, sock, fd, event): # if sock == self.ctx and event == eventloop.POLL_IN: # data = self.ctx.recv(4096) # data = common.to_str(data) # if data.startswith('stat:'): # data = data.split('stat:')[1] # stat_data = json.loads(data) # if self.callback: self.callback(stat_data) # # Path: web/models.py # class TrafficStat(models.Model): # account = models.ForeignKey(ProxyAccount, on_delete=models.CASCADE) # time = models.DateTimeField(auto_now_add=True, blank=True) # amount = models.IntegerField() # # class ProxyAccount(models.Model): # user = models.ForeignKey(auth_models.User) # service = models.CharField(max_length=130) # enabled = models.BooleanField(default=False) # config = JSONField(default={}) # log = models.TextField(default="") # created_at = models.DateTimeField(auto_now_add=True, blank=True) # expire_when = models.DateTimeField(auto_now_add=True, blank=True) # # @property # def is_active(self): # return self.enabled and self.user.is_active # # def stop_service(self): # '''DANGEROUS: unconditionally stop service for this account''' # getService(self.service).remove(self.config) # # def start_service(self): # '''DANGEROUS: unconditionally start service for this account''' # getService(self.service).add(self.config) # # def save(self, *args, **kw): # self.config['id'] = self.pk # try: # orig = ProxyAccount.objects.get(pk=self.pk) # serv = getService(self.service) # # a_orig = orig.is_active # a_curr = self.is_active # # if not a_orig and a_curr: serv.add(self.config) # add # if a_orig and not a_curr: serv.remove(self.config) # remove # if a_orig and a_curr: serv.update(self.config) # update # # except ProxyAccount.DoesNotExist as e: # pass # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to update service for ProxyAccount %d", self.pk) # super(ProxyAccount, self).save(*args, **kw) # # def delete(self, *args, **kw): # try: # if self.is_active: # getService(self.service).remove(self.config) # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to stop ProxyAccount %d before deleting", self.pk) # super(ProxyAccount, self).delete(*args, **kw) # # @property # def html(self): # cl = getService(self.service) # return cl.html(self.config) # # @property # def form(self): # cl = getService(self.service) # return cl.UserForm # # @property # def adminForm(self): # cl = getService(self.service) # return cl.AdminForm # # Path: web/forms.py # class VisiblePasswordField(forms.CharField): # def __init__(self, *args, **kwargs): # super(VisiblePasswordField, self).__init__(*args, **kwargs) # # def widget_attrs(self, widget): # attrs = super(VisiblePasswordField, self).widget_attrs(widget) # attrs['data-visiblepass'] = 'true' # return attrs . Output only the next line.
"statistic_interval": 7200,
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Shadowsocks service # from __future__ import absolute_import, print_function config = { "executable": "ssserver", "config-file": "/etc/shadowsocks.json", "manager-address": "/var/run/shadowsocks-manager.sock", "statistic_interval": 7200, "port-range": (6789, 45678), # used to generate new account # The infos that display on website. # 1. leave them empty and SSLand will read the config file. # 2. or write something. this will not affect the config file. "server": "", "method": "", <|code_end|> . Use current file imports: import base64 import json import logging import time import os import random from collections import OrderedDict from core.util import get_stdout, encodeURIComponent, random_password from core.ssutil import ShadowsocksStat from web.models import TrafficStat, ProxyAccount from core.util import html_strip_table from django import forms from web.forms import VisiblePasswordField and context (classes, functions, or code) from other files: # Path: core/util.py # def get_stdout(*args): # ''' # Execute an application, returning (stdout, exitcode) # # Example: # response, retval = get_stdout(["whoami"]) # ''' # import subprocess # p = subprocess.Popen(*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) # o = [] # p.stdin.close() # with p.stdout: # for line in iter(p.stdout.readline, b''): # o.append(line) # p.wait() # wait for the subprocess to exit # return ''.join(o), p.returncode # # def encodeURIComponent(str): # return urllib.quote(str, safe='~()*!.\'') # # def random_password(N=16): # import random, string # return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) # # Path: core/ssutil.py # class ShadowsocksStat: # def __init__(self, manager_address, loop): # self.loop = loop # self.ctx = ShadowsocksCtx(manager_address) # self.manager_address = manager_address # self.callback=None # # def set_callback(self, callback): # '''the callback when new traffic statistic data comes # # def callback(dict):... # ''' # self.callback=callback # # def add_to_loop(self): # self.ctx.connect() # self.ctx.command('ping') # self.loop.add(self.ctx, eventloop.POLL_IN, self) # # def handle_event(self, sock, fd, event): # if sock == self.ctx and event == eventloop.POLL_IN: # data = self.ctx.recv(4096) # data = common.to_str(data) # if data.startswith('stat:'): # data = data.split('stat:')[1] # stat_data = json.loads(data) # if self.callback: self.callback(stat_data) # # Path: web/models.py # class TrafficStat(models.Model): # account = models.ForeignKey(ProxyAccount, on_delete=models.CASCADE) # time = models.DateTimeField(auto_now_add=True, blank=True) # amount = models.IntegerField() # # class ProxyAccount(models.Model): # user = models.ForeignKey(auth_models.User) # service = models.CharField(max_length=130) # enabled = models.BooleanField(default=False) # config = JSONField(default={}) # log = models.TextField(default="") # created_at = models.DateTimeField(auto_now_add=True, blank=True) # expire_when = models.DateTimeField(auto_now_add=True, blank=True) # # @property # def is_active(self): # return self.enabled and self.user.is_active # # def stop_service(self): # '''DANGEROUS: unconditionally stop service for this account''' # getService(self.service).remove(self.config) # # def start_service(self): # '''DANGEROUS: unconditionally start service for this account''' # getService(self.service).add(self.config) # # def save(self, *args, **kw): # self.config['id'] = self.pk # try: # orig = ProxyAccount.objects.get(pk=self.pk) # serv = getService(self.service) # # a_orig = orig.is_active # a_curr = self.is_active # # if not a_orig and a_curr: serv.add(self.config) # add # if a_orig and not a_curr: serv.remove(self.config) # remove # if a_orig and a_curr: serv.update(self.config) # update # # except ProxyAccount.DoesNotExist as e: # pass # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to update service for ProxyAccount %d", self.pk) # super(ProxyAccount, self).save(*args, **kw) # # def delete(self, *args, **kw): # try: # if self.is_active: # getService(self.service).remove(self.config) # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to stop ProxyAccount %d before deleting", self.pk) # super(ProxyAccount, self).delete(*args, **kw) # # @property # def html(self): # cl = getService(self.service) # return cl.html(self.config) # # @property # def form(self): # cl = getService(self.service) # return cl.UserForm # # @property # def adminForm(self): # cl = getService(self.service) # return cl.AdminForm # # Path: web/forms.py # class VisiblePasswordField(forms.CharField): # def __init__(self, *args, **kwargs): # super(VisiblePasswordField, self).__init__(*args, **kwargs) # # def widget_attrs(self, widget): # attrs = super(VisiblePasswordField, self).widget_attrs(widget) # attrs['data-visiblepass'] = 'true' # return attrs . Output only the next line.
}
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Shadowsocks service # from __future__ import absolute_import, print_function config = { "executable": "ssserver", "config-file": "/etc/shadowsocks.json", "manager-address": "/var/run/shadowsocks-manager.sock", "statistic_interval": 7200, "port-range": (6789, 45678), # used to generate new account # The infos that display on website. # 1. leave them empty and SSLand will read the config file. # 2. or write something. this will not affect the config file. "server": "", <|code_end|> , continue by predicting the next line. Consider current file imports: import base64 import json import logging import time import os import random from collections import OrderedDict from core.util import get_stdout, encodeURIComponent, random_password from core.ssutil import ShadowsocksStat from web.models import TrafficStat, ProxyAccount from core.util import html_strip_table from django import forms from web.forms import VisiblePasswordField and context: # Path: core/util.py # def get_stdout(*args): # ''' # Execute an application, returning (stdout, exitcode) # # Example: # response, retval = get_stdout(["whoami"]) # ''' # import subprocess # p = subprocess.Popen(*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) # o = [] # p.stdin.close() # with p.stdout: # for line in iter(p.stdout.readline, b''): # o.append(line) # p.wait() # wait for the subprocess to exit # return ''.join(o), p.returncode # # def encodeURIComponent(str): # return urllib.quote(str, safe='~()*!.\'') # # def random_password(N=16): # import random, string # return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) # # Path: core/ssutil.py # class ShadowsocksStat: # def __init__(self, manager_address, loop): # self.loop = loop # self.ctx = ShadowsocksCtx(manager_address) # self.manager_address = manager_address # self.callback=None # # def set_callback(self, callback): # '''the callback when new traffic statistic data comes # # def callback(dict):... # ''' # self.callback=callback # # def add_to_loop(self): # self.ctx.connect() # self.ctx.command('ping') # self.loop.add(self.ctx, eventloop.POLL_IN, self) # # def handle_event(self, sock, fd, event): # if sock == self.ctx and event == eventloop.POLL_IN: # data = self.ctx.recv(4096) # data = common.to_str(data) # if data.startswith('stat:'): # data = data.split('stat:')[1] # stat_data = json.loads(data) # if self.callback: self.callback(stat_data) # # Path: web/models.py # class TrafficStat(models.Model): # account = models.ForeignKey(ProxyAccount, on_delete=models.CASCADE) # time = models.DateTimeField(auto_now_add=True, blank=True) # amount = models.IntegerField() # # class ProxyAccount(models.Model): # user = models.ForeignKey(auth_models.User) # service = models.CharField(max_length=130) # enabled = models.BooleanField(default=False) # config = JSONField(default={}) # log = models.TextField(default="") # created_at = models.DateTimeField(auto_now_add=True, blank=True) # expire_when = models.DateTimeField(auto_now_add=True, blank=True) # # @property # def is_active(self): # return self.enabled and self.user.is_active # # def stop_service(self): # '''DANGEROUS: unconditionally stop service for this account''' # getService(self.service).remove(self.config) # # def start_service(self): # '''DANGEROUS: unconditionally start service for this account''' # getService(self.service).add(self.config) # # def save(self, *args, **kw): # self.config['id'] = self.pk # try: # orig = ProxyAccount.objects.get(pk=self.pk) # serv = getService(self.service) # # a_orig = orig.is_active # a_curr = self.is_active # # if not a_orig and a_curr: serv.add(self.config) # add # if a_orig and not a_curr: serv.remove(self.config) # remove # if a_orig and a_curr: serv.update(self.config) # update # # except ProxyAccount.DoesNotExist as e: # pass # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to update service for ProxyAccount %d", self.pk) # super(ProxyAccount, self).save(*args, **kw) # # def delete(self, *args, **kw): # try: # if self.is_active: # getService(self.service).remove(self.config) # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to stop ProxyAccount %d before deleting", self.pk) # super(ProxyAccount, self).delete(*args, **kw) # # @property # def html(self): # cl = getService(self.service) # return cl.html(self.config) # # @property # def form(self): # cl = getService(self.service) # return cl.UserForm # # @property # def adminForm(self): # cl = getService(self.service) # return cl.AdminForm # # Path: web/forms.py # class VisiblePasswordField(forms.CharField): # def __init__(self, *args, **kwargs): # super(VisiblePasswordField, self).__init__(*args, **kwargs) # # def widget_attrs(self, widget): # attrs = super(VisiblePasswordField, self).widget_attrs(widget) # attrs['data-visiblepass'] = 'true' # return attrs which might include code, classes, or functions. Output only the next line.
"method": "",
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Shadowsocks service # from __future__ import absolute_import, print_function config = { "executable": "ssserver", "config-file": "/etc/shadowsocks.json", <|code_end|> , determine the next line of code. You have imports: import base64 import json import logging import time import os import random from collections import OrderedDict from core.util import get_stdout, encodeURIComponent, random_password from core.ssutil import ShadowsocksStat from web.models import TrafficStat, ProxyAccount from core.util import html_strip_table from django import forms from web.forms import VisiblePasswordField and context (class names, function names, or code) available: # Path: core/util.py # def get_stdout(*args): # ''' # Execute an application, returning (stdout, exitcode) # # Example: # response, retval = get_stdout(["whoami"]) # ''' # import subprocess # p = subprocess.Popen(*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) # o = [] # p.stdin.close() # with p.stdout: # for line in iter(p.stdout.readline, b''): # o.append(line) # p.wait() # wait for the subprocess to exit # return ''.join(o), p.returncode # # def encodeURIComponent(str): # return urllib.quote(str, safe='~()*!.\'') # # def random_password(N=16): # import random, string # return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) # # Path: core/ssutil.py # class ShadowsocksStat: # def __init__(self, manager_address, loop): # self.loop = loop # self.ctx = ShadowsocksCtx(manager_address) # self.manager_address = manager_address # self.callback=None # # def set_callback(self, callback): # '''the callback when new traffic statistic data comes # # def callback(dict):... # ''' # self.callback=callback # # def add_to_loop(self): # self.ctx.connect() # self.ctx.command('ping') # self.loop.add(self.ctx, eventloop.POLL_IN, self) # # def handle_event(self, sock, fd, event): # if sock == self.ctx and event == eventloop.POLL_IN: # data = self.ctx.recv(4096) # data = common.to_str(data) # if data.startswith('stat:'): # data = data.split('stat:')[1] # stat_data = json.loads(data) # if self.callback: self.callback(stat_data) # # Path: web/models.py # class TrafficStat(models.Model): # account = models.ForeignKey(ProxyAccount, on_delete=models.CASCADE) # time = models.DateTimeField(auto_now_add=True, blank=True) # amount = models.IntegerField() # # class ProxyAccount(models.Model): # user = models.ForeignKey(auth_models.User) # service = models.CharField(max_length=130) # enabled = models.BooleanField(default=False) # config = JSONField(default={}) # log = models.TextField(default="") # created_at = models.DateTimeField(auto_now_add=True, blank=True) # expire_when = models.DateTimeField(auto_now_add=True, blank=True) # # @property # def is_active(self): # return self.enabled and self.user.is_active # # def stop_service(self): # '''DANGEROUS: unconditionally stop service for this account''' # getService(self.service).remove(self.config) # # def start_service(self): # '''DANGEROUS: unconditionally start service for this account''' # getService(self.service).add(self.config) # # def save(self, *args, **kw): # self.config['id'] = self.pk # try: # orig = ProxyAccount.objects.get(pk=self.pk) # serv = getService(self.service) # # a_orig = orig.is_active # a_curr = self.is_active # # if not a_orig and a_curr: serv.add(self.config) # add # if a_orig and not a_curr: serv.remove(self.config) # remove # if a_orig and a_curr: serv.update(self.config) # update # # except ProxyAccount.DoesNotExist as e: # pass # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to update service for ProxyAccount %d", self.pk) # super(ProxyAccount, self).save(*args, **kw) # # def delete(self, *args, **kw): # try: # if self.is_active: # getService(self.service).remove(self.config) # except Exception as e2: # from core.util import print_exception # import logging # print_exception(e2) # logging.error("Failed to stop ProxyAccount %d before deleting", self.pk) # super(ProxyAccount, self).delete(*args, **kw) # # @property # def html(self): # cl = getService(self.service) # return cl.html(self.config) # # @property # def form(self): # cl = getService(self.service) # return cl.UserForm # # @property # def adminForm(self): # cl = getService(self.service) # return cl.AdminForm # # Path: web/forms.py # class VisiblePasswordField(forms.CharField): # def __init__(self, *args, **kwargs): # super(VisiblePasswordField, self).__init__(*args, **kwargs) # # def widget_attrs(self, widget): # attrs = super(VisiblePasswordField, self).widget_attrs(widget) # attrs['data-visiblepass'] = 'true' # return attrs . Output only the next line.
"manager-address": "/var/run/shadowsocks-manager.sock",
Given the code snippet: <|code_start|># Purpose: manage header section # Created: 12.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" MIN_HEADER_TEXT = """ 0 SECTION 2 HEADER 9 $ACADVER 1 AC1009 <|code_end|> , generate the next line using the imports in this file: from collections import OrderedDict from ..tools.c23 import ustr from ..lldxf.types import strtag from ..lldxf.tags import TagGroups, Tags, DXFStructureError and context (functions, classes, or occasionally code) from other files: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # def isstring(s): # # Path: core/ezdxf/lldxf/types.py # def strtag(tag): # return TAG_STRING_FORMAT % tag # # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): . Output only the next line.
9
Next line prediction: <|code_start|># Purpose: manage header section # Created: 12.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" MIN_HEADER_TEXT = """ 0 SECTION 2 <|code_end|> . Use current file imports: (from collections import OrderedDict from ..tools.c23 import ustr from ..lldxf.types import strtag from ..lldxf.tags import TagGroups, Tags, DXFStructureError) and context including class names, function names, or small code snippets from other files: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # def isstring(s): # # Path: core/ezdxf/lldxf/types.py # def strtag(tag): # return TAG_STRING_FORMAT % tag # # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): . Output only the next line.
HEADER
Given the code snippet: <|code_start|># Purpose: manage header section # Created: 12.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" MIN_HEADER_TEXT = """ 0 SECTION 2 <|code_end|> , generate the next line using the imports in this file: from collections import OrderedDict from ..tools.c23 import ustr from ..lldxf.types import strtag from ..lldxf.tags import TagGroups, Tags, DXFStructureError and context (functions, classes, or occasionally code) from other files: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # def isstring(s): # # Path: core/ezdxf/lldxf/types.py # def strtag(tag): # return TAG_STRING_FORMAT % tag # # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): . Output only the next line.
HEADER
Using the snippet: <|code_start|># Purpose: manage header section # Created: 12.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" MIN_HEADER_TEXT = """ 0 SECTION 2 HEADER 9 $ACADVER 1 AC1009 9 $DWGCODEPAGE 3 ANSI_1252 9 $HANDSEED <|code_end|> , determine the next line of code. You have imports: from collections import OrderedDict from ..tools.c23 import ustr from ..lldxf.types import strtag from ..lldxf.tags import TagGroups, Tags, DXFStructureError and context (class names, function names, or code) available: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # def isstring(s): # # Path: core/ezdxf/lldxf/types.py # def strtag(tag): # return TAG_STRING_FORMAT % tag # # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): . Output only the next line.
5
Predict the next line for this snippet: <|code_start|># Purpose: manage header section # Created: 12.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" MIN_HEADER_TEXT = """ 0 SECTION 2 HEADER 9 $ACADVER 1 <|code_end|> with the help of current file imports: from collections import OrderedDict from ..tools.c23 import ustr from ..lldxf.types import strtag from ..lldxf.tags import TagGroups, Tags, DXFStructureError and context from other files: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # def isstring(s): # # Path: core/ezdxf/lldxf/types.py # def strtag(tag): # return TAG_STRING_FORMAT % tag # # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): , which may contain function names, class names, or code. Output only the next line.
AC1009
Based on the snippet: <|code_start|> return is_point_code(tag[0]) def cast_tag(tag, types=TYPE_TABLE): caster = types.get(tag[0], ustr) try: return DXFTag(tag[0], caster(tag[1])) except ValueError: if caster is int: # convert float to int return DXFTag(tag[0], int(float(tag[1]))) else: raise def cast_tag_value(code, value, types=TYPE_TABLE): return types.get(code, ustr)(value) def tag_type(code): try: return TYPE_TABLE[code] except KeyError: raise ValueError("Invalid tag code: {}".format(code)) def strtag(tag): return TAG_STRING_FORMAT % tag def strtag2(tag): <|code_end|> , predict the immediate next line with the help of imports: from collections import namedtuple from ..tools.c23 import ustr and context (classes, functions, sometimes code) from other files: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # def isstring(s): . Output only the next line.
code = tag.code
Using the snippet: <|code_start|># Purpose: database module # Created: 11.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" def factory(): <|code_end|> , determine the next line of code. You have imports: from .tools.binarydata import compress_binary_data from .tools.handle import HandleGenerator and context (class names, function names, or code) available: # Path: core/ezdxf/tools/binarydata.py # def compress_binary_data(tags): # dxftype = tags.dxftype() # for subclass in tags.subclasses[1:]: # if not subclass: # empty subclass AcDbVertex # continue # todo: why is subclass AcDbVertex empty, should contain DXFTag(100, 'AcDbVertex') # # but it works, output DXF contains all necessary subclasses # name = subclass[0].value # if name == 'AcDbEntity' and dxftype in ENTITIES_WITH_PROXY_GRAPHIC: # # 310: proxy entity graphics data # _compress_binary_tags(subclass) # if name in SUBCLASSES_WITH_BINARY_DATA: # # 310: binary object data # _compress_binary_tags(subclass) # # Path: core/ezdxf/tools/handle.py # class HandleGenerator(object): # def __init__(self, start_value='1'): # self._handle = int(start_value, 16) # reset = __init__ # # def __str__(self): # return "%X" % self._handle # # def next(self): # next_handle = self.__str__() # self._handle += 1 # return next_handle # __next__ = next . Output only the next line.
return EntityDB()
Given the following code snippet before the placeholder: <|code_start|># Purpose: database module # Created: 11.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" def factory(): <|code_end|> , predict the next line using imports from the current file: from .tools.binarydata import compress_binary_data from .tools.handle import HandleGenerator and context including class names, function names, and sometimes code from other files: # Path: core/ezdxf/tools/binarydata.py # def compress_binary_data(tags): # dxftype = tags.dxftype() # for subclass in tags.subclasses[1:]: # if not subclass: # empty subclass AcDbVertex # continue # todo: why is subclass AcDbVertex empty, should contain DXFTag(100, 'AcDbVertex') # # but it works, output DXF contains all necessary subclasses # name = subclass[0].value # if name == 'AcDbEntity' and dxftype in ENTITIES_WITH_PROXY_GRAPHIC: # # 310: proxy entity graphics data # _compress_binary_tags(subclass) # if name in SUBCLASSES_WITH_BINARY_DATA: # # 310: binary object data # _compress_binary_tags(subclass) # # Path: core/ezdxf/tools/handle.py # class HandleGenerator(object): # def __init__(self, start_value='1'): # self._handle = int(start_value, 16) # reset = __init__ # # def __str__(self): # return "%X" % self._handle # # def next(self): # next_handle = self.__str__() # self._handle += 1 # return next_handle # __next__ = next . Output only the next line.
return EntityDB()
Predict the next line after this snippet: <|code_start|># License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" BINARY_DATA_CODES = frozenset(range(310, 320)) ENTITIES_WITH_PROXY_GRAPHIC = frozenset(['MESH', 'BODY', 'REGION', '3DSOLID', 'SURFACE', 'PLANESURFACE', 'HELIX', 'TABLE']) SUBCLASSES_WITH_BINARY_DATA = frozenset(['AcDbProxyEntity', 'AcDbProxyObject', 'AcDbOleFrame', 'AcDbOle2Frame', 'AcDbVbaProject', 'AcDbXrecord']) def compress_binary_data(tags): dxftype = tags.dxftype() for subclass in tags.subclasses[1:]: if not subclass: # empty subclass AcDbVertex continue # todo: why is subclass AcDbVertex empty, should contain DXFTag(100, 'AcDbVertex') # but it works, output DXF contains all necessary subclasses name = subclass[0].value if name == 'AcDbEntity' and dxftype in ENTITIES_WITH_PROXY_GRAPHIC: # 310: proxy entity graphics data _compress_binary_tags(subclass) if name in SUBCLASSES_WITH_BINARY_DATA: # 310: binary object data _compress_binary_tags(subclass) def _compress_binary_tags(tags): compress_tasks = _collect_compress_tasks(tags) <|code_end|> using the current file's imports: from .c23 import PY3 from ..lldxf.tags import CompressedTags from array import array and any relevant context from other files: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # # Path: core/ezdxf/lldxf/tags.py # class CompressedTags(object): # """Store multiple tags, compressed by zlib, as one DXFTag(code, value). value is a CompressedString() object. # """ # def __init__(self, code, tags): # self.code = code # self.value = CompressedString("".join(strtag2(tag) for tag in tags)) # # def __getitem__(self, item): # if item == 0: # return self.code # elif item == 1: # return self.value # else: # raise IndexError # # def decompress(self): # return Tags.from_text(self.value.decompress()) # # def write(self, stream): # stream.write(self.value.decompress()) . Output only the next line.
if len(compress_tasks):
Predict the next line after this snippet: <|code_start|># Purpose: binary data management # Created: 03.05.2014 # Copyright (C) 2014, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" BINARY_DATA_CODES = frozenset(range(310, 320)) ENTITIES_WITH_PROXY_GRAPHIC = frozenset(['MESH', 'BODY', 'REGION', '3DSOLID', 'SURFACE', 'PLANESURFACE', 'HELIX', 'TABLE']) SUBCLASSES_WITH_BINARY_DATA = frozenset(['AcDbProxyEntity', 'AcDbProxyObject', 'AcDbOleFrame', 'AcDbOle2Frame', 'AcDbVbaProject', 'AcDbXrecord']) def compress_binary_data(tags): <|code_end|> using the current file's imports: from .c23 import PY3 from ..lldxf.tags import CompressedTags from array import array and any relevant context from other files: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # # Path: core/ezdxf/lldxf/tags.py # class CompressedTags(object): # """Store multiple tags, compressed by zlib, as one DXFTag(code, value). value is a CompressedString() object. # """ # def __init__(self, code, tags): # self.code = code # self.value = CompressedString("".join(strtag2(tag) for tag in tags)) # # def __getitem__(self, item): # if item == 0: # return self.code # elif item == 1: # return self.value # else: # raise IndexError # # def decompress(self): # return Tags.from_text(self.value.decompress()) # # def write(self, stream): # stream.write(self.value.decompress()) . Output only the next line.
dxftype = tags.dxftype()
Continue the code snippet: <|code_start|> self.build(faces) @property def nvertices(self): return len(self.vertices) @property def nfaces(self): return len(self.faces) def get_vertices(self): vertices = self.vertices[:] vertices.extend(self.faces) return vertices def build(self, faces): for face in faces: face_record = face.face_record for vertex, name in zip(face, VERTEXNAMES): index = self.add(vertex) # preserve sign of old index value sign = -1 if face_record.get_dxf_attrib(name, 0) < 0 else +1 face_record.set_dxf_attrib(name, (index + 1) * sign) self.faces.append(face_record) def add(self, vertex): def key(point): return tuple((round(coord, self.precision) for coord in point)) location = key(vertex.dxf.location) <|code_end|> . Use current file imports: from ..lldxf.const import VERTEXNAMES and context (classes, functions, or code) from other files: # Path: core/ezdxf/lldxf/const.py # VERTEXNAMES = ('vtx0', 'vtx1', 'vtx2', 'vtx3') . Output only the next line.
try:
Based on the snippet: <|code_start|># Purpose: classified tags # Created: 30.04.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" APP_DATA_MARKER = 102 <|code_end|> , predict the immediate next line with the help of imports: from .tags import Tags, DXFStructureError, DXFTag, write_tags from ..tools.c23 import isstring from .tagger import string_tagger, skip_comments and context (classes, functions, sometimes code) from other files: # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): # # Path: core/ezdxf/tools/c23.py # def isstring(s): # return isinstance(s, basestring) # # Path: core/ezdxf/lldxf/tagger.py # def string_tagger(s): # """ Generates DXFTag() from trusted (internal) source - relies on # well formed and error free DXF format. Does not skip comment # tags 999. # """ # # lines = s.split('\n') # if s.endswith('\n'): # split() creates an extra item, if s ends with '\n' # lines.pop() # pos = 0 # # def next_tag(): # return DXFTag(int(lines[pos]), lines[pos+1]) # # count = len(lines) # while pos < count: # x = next_tag() # pos += 2 # code = x.code # if is_point_code(code): # y = next_tag() # y coordinate is mandatory - string_tagger relies on well formed DXF strings # pos += 2 # if pos < count: # z = next_tag() # z coordinate just for 3d points # else: # if string s ends with a 2d point # z = DUMMY_TAG # if z.code == code + 20: # pos += 2 # point = (float(x.value), float(y.value), float(z.value)) # else: # point = (float(x.value), float(y.value)) # yield DXFTag(code, point) # else: # yield cast_tag(x) # # def skip_comments(tagger, comments=None): # if comments is None: # comments = [] # for tag in tagger: # if tag.code != 999: # yield tag # else: # comments.append(tag.value) . Output only the next line.
SUBCLASS_MARKER = 100
Here is a snippet: <|code_start|># Purpose: classified tags # Created: 30.04.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" APP_DATA_MARKER = 102 SUBCLASS_MARKER = 100 <|code_end|> . Write the next line using the current file imports: from .tags import Tags, DXFStructureError, DXFTag, write_tags from ..tools.c23 import isstring from .tagger import string_tagger, skip_comments and context from other files: # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): # # Path: core/ezdxf/tools/c23.py # def isstring(s): # return isinstance(s, basestring) # # Path: core/ezdxf/lldxf/tagger.py # def string_tagger(s): # """ Generates DXFTag() from trusted (internal) source - relies on # well formed and error free DXF format. Does not skip comment # tags 999. # """ # # lines = s.split('\n') # if s.endswith('\n'): # split() creates an extra item, if s ends with '\n' # lines.pop() # pos = 0 # # def next_tag(): # return DXFTag(int(lines[pos]), lines[pos+1]) # # count = len(lines) # while pos < count: # x = next_tag() # pos += 2 # code = x.code # if is_point_code(code): # y = next_tag() # y coordinate is mandatory - string_tagger relies on well formed DXF strings # pos += 2 # if pos < count: # z = next_tag() # z coordinate just for 3d points # else: # if string s ends with a 2d point # z = DUMMY_TAG # if z.code == code + 20: # pos += 2 # point = (float(x.value), float(y.value), float(z.value)) # else: # point = (float(x.value), float(y.value)) # yield DXFTag(code, point) # else: # yield cast_tag(x) # # def skip_comments(tagger, comments=None): # if comments is None: # comments = [] # for tag in tagger: # if tag.code != 999: # yield tag # else: # comments.append(tag.value) , which may include functions, classes, or code. Output only the next line.
XDATA_MARKER = 1001
Given snippet: <|code_start|># Purpose: classified tags # Created: 30.04.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" APP_DATA_MARKER = 102 SUBCLASS_MARKER = 100 XDATA_MARKER = 1001 NoneTag = DXFTag(None, None) <|code_end|> , continue by predicting the next line. Consider current file imports: from .tags import Tags, DXFStructureError, DXFTag, write_tags from ..tools.c23 import isstring from .tagger import string_tagger, skip_comments and context: # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): # # Path: core/ezdxf/tools/c23.py # def isstring(s): # return isinstance(s, basestring) # # Path: core/ezdxf/lldxf/tagger.py # def string_tagger(s): # """ Generates DXFTag() from trusted (internal) source - relies on # well formed and error free DXF format. Does not skip comment # tags 999. # """ # # lines = s.split('\n') # if s.endswith('\n'): # split() creates an extra item, if s ends with '\n' # lines.pop() # pos = 0 # # def next_tag(): # return DXFTag(int(lines[pos]), lines[pos+1]) # # count = len(lines) # while pos < count: # x = next_tag() # pos += 2 # code = x.code # if is_point_code(code): # y = next_tag() # y coordinate is mandatory - string_tagger relies on well formed DXF strings # pos += 2 # if pos < count: # z = next_tag() # z coordinate just for 3d points # else: # if string s ends with a 2d point # z = DUMMY_TAG # if z.code == code + 20: # pos += 2 # point = (float(x.value), float(y.value), float(z.value)) # else: # point = (float(x.value), float(y.value)) # yield DXFTag(code, point) # else: # yield cast_tag(x) # # def skip_comments(tagger, comments=None): # if comments is None: # comments = [] # for tag in tagger: # if tag.code != 999: # yield tag # else: # comments.append(tag.value) which might include code, classes, or functions. Output only the next line.
class ClassifiedTags(object):
Given the code snippet: <|code_start|># Purpose: classified tags # Created: 30.04.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" APP_DATA_MARKER = 102 SUBCLASS_MARKER = 100 XDATA_MARKER = 1001 NoneTag = DXFTag(None, None) <|code_end|> , generate the next line using the imports in this file: from .tags import Tags, DXFStructureError, DXFTag, write_tags from ..tools.c23 import isstring from .tagger import string_tagger, skip_comments and context (functions, classes, or occasionally code) from other files: # Path: core/ezdxf/lldxf/tags.py # COMMENT_CODE = 999 # def write_tags(stream, tags): # def text2tags(text): # def __init__(self): # def DWGCODEPAGE(self, value): # def ACADVER(self, value): # def HANDSEED(self, value): # def dxf_info(stream): # def write(self, stream): # def from_text(cls, text): # def __copy__(self): # def get_handle(self): # def replace_handle(self, new_handle): # def dxftype(self): # def has_tag(self, code): # def find_first(self, code, default=ValueError): # def get_first_tag(self, code, default=ValueError): # def find_all(self, code): # def tag_index(self, code, start=0, end=None): # def update(self, code, value): # def set_first(self, code, value): # def remove_tags(self, codes): # def collect_consecutive_tags(self, codes, start=0, end=None): # def __init__(self, tags, splitcode=0): # def _build_groups(self, tags, splitcode): # def append(tag): # first do nothing, skip tags in front of the first split tag # def get_name(self, index): # def from_text(cls, text, splitcode=0): # def strip_tags(tags, codes): # def __init__(self, code, tags): # def __getitem__(self, item): # def decompress(self): # def write(self, stream): # class DXFInfo(object): # class Tags(list): # class TagGroups(list): # class CompressedTags(object): # # Path: core/ezdxf/tools/c23.py # def isstring(s): # return isinstance(s, basestring) # # Path: core/ezdxf/lldxf/tagger.py # def string_tagger(s): # """ Generates DXFTag() from trusted (internal) source - relies on # well formed and error free DXF format. Does not skip comment # tags 999. # """ # # lines = s.split('\n') # if s.endswith('\n'): # split() creates an extra item, if s ends with '\n' # lines.pop() # pos = 0 # # def next_tag(): # return DXFTag(int(lines[pos]), lines[pos+1]) # # count = len(lines) # while pos < count: # x = next_tag() # pos += 2 # code = x.code # if is_point_code(code): # y = next_tag() # y coordinate is mandatory - string_tagger relies on well formed DXF strings # pos += 2 # if pos < count: # z = next_tag() # z coordinate just for 3d points # else: # if string s ends with a 2d point # z = DUMMY_TAG # if z.code == code + 20: # pos += 2 # point = (float(x.value), float(y.value), float(z.value)) # else: # point = (float(x.value), float(y.value)) # yield DXFTag(code, point) # else: # yield cast_tag(x) # # def skip_comments(tagger, comments=None): # if comments is None: # comments = [] # for tag in tagger: # if tag.code != 999: # yield tag # else: # comments.append(tag.value) . Output only the next line.
class ClassifiedTags(object):
Given the code snippet: <|code_start|>class DefaultChunk(object): def __init__(self, tags, drawing): self.tags = tags self._drawing = drawing @property def dxffactory(self): return self._drawing.dxffactory @property def name(self): return self.tags[1].value.lower() def write(self, stream): self.tags.write(stream) class CompressedDefaultChunk(DefaultChunk): def __init__(self, tags, drawing): compressed_tags = CompressedTags(COMPRESSED_TAGS, tags) super(CompressedDefaultChunk, self).__init__(Tags((tags[0], tags[1], compressed_tags)), drawing) self._compressed_tags = compressed_tags def write(self, stream): self._compressed_tags.write(stream) def iter_chunks(tagreader, stoptag='EOF', endofchunk='ENDSEC'): try: while True: <|code_end|> , generate the next line using the imports in this file: from .tags import Tags, CompressedTags from .const import COMPRESSED_TAGS and context (functions, classes, or occasionally code) from other files: # Path: core/ezdxf/lldxf/tags.py # class Tags(list): # """ DXFTag() chunk as flat list. """ # def write(self, stream): # write_tags(stream, self) # # @classmethod # def from_text(cls, text): # return cls(skip_comments(string_tagger(text))) # # def __copy__(self): # return self.__class__(DXFTag(*tag) for tag in self) # # clone = __copy__ # # def get_handle(self): # """Get DXF handle. Raises ValueError if handle not exists. # # :returns: handle as hex-string like 'FF' # """ # handle = '' # for tag in self: # if tag.code in (5, 105): # handle = tag.value # break # int(handle, 16) # check for valid handle # return handle # # def replace_handle(self, new_handle): # """Replace existing handle. # """ # for index, tag in enumerate(self): # if tag.code in (5, 105): # self[index] = DXFTag(tag.code, new_handle) # return # # def dxftype(self): # return self[0].value # # def has_tag(self, code): # return any(True for tag in self if tag.code == code) # # def find_first(self, code, default=ValueError): # """Returns value of first DXFTag(code, value) or default if default != ValueError, else raises ValueError. # """ # for tag in self: # if tag.code == code: # return tag.value # if default is ValueError: # raise ValueError(code) # else: # return default # # def get_first_tag(self, code, default=ValueError): # """Returns first DXFTag(code, value) or default if default != ValueError, else raises ValueError. # """ # for tag in self: # if tag.code == code: # return tag # if default is ValueError: # raise ValueError(code) # else: # return default # # def find_all(self, code): # """Returns a list of DXFTag(code, value). # """ # return [tag for tag in self if tag.code == code] # # def tag_index(self, code, start=0, end=None): # """Return first index of DXFTag(code, value). # """ # if end is None: # end = len(self) # index = start # while index < end: # if self[index].code == code: # return index # index += 1 # raise ValueError(code) # # def update(self, code, value): # """Update first existing tag, raises ValueError if tag not exists. # """ # index = self.tag_index(code) # self[index] = DXFTag(code, value) # # def set_first(self, code, value): # """Update first existing DXFTag(code, value) or append a new # DXFTag(code, value). # # """ # try: # self.update(code, value) # except ValueError: # self.append(DXFTag(code, value)) # # def remove_tags(self, codes): # self[:] = [tag for tag in self if tag.code not in set(codes)] # # def collect_consecutive_tags(self, codes, start=0, end=None): # """Collect all consecutive tags with code in codes, start and end delimits the search range. A tag code not # in codes ends the process. # # Returns the collected tags in a collection of type Tag(). # """ # codes = frozenset(codes) # collected_tags = Tags() # if end is None: # end = len(self) # index = start # while index < end: # tag = self[index] # if tag.code in codes: # collected_tags.append(tag) # index += 1 # else: # break # return collected_tags # # class CompressedTags(object): # """Store multiple tags, compressed by zlib, as one DXFTag(code, value). value is a CompressedString() object. # """ # def __init__(self, code, tags): # self.code = code # self.value = CompressedString("".join(strtag2(tag) for tag in tags)) # # def __getitem__(self, item): # if item == 0: # return self.code # elif item == 1: # return self.value # else: # raise IndexError # # def decompress(self): # return Tags.from_text(self.value.decompress()) # # def write(self, stream): # stream.write(self.value.decompress()) # # Path: core/ezdxf/lldxf/const.py # COMPRESSED_TAGS = -10 . Output only the next line.
tag = next(tagreader)
Given the code snippet: <|code_start|># Purpose: default chunk # Created: 12.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" class DefaultChunk(object): def __init__(self, tags, drawing): self.tags = tags self._drawing = drawing @property <|code_end|> , generate the next line using the imports in this file: from .tags import Tags, CompressedTags from .const import COMPRESSED_TAGS and context (functions, classes, or occasionally code) from other files: # Path: core/ezdxf/lldxf/tags.py # class Tags(list): # """ DXFTag() chunk as flat list. """ # def write(self, stream): # write_tags(stream, self) # # @classmethod # def from_text(cls, text): # return cls(skip_comments(string_tagger(text))) # # def __copy__(self): # return self.__class__(DXFTag(*tag) for tag in self) # # clone = __copy__ # # def get_handle(self): # """Get DXF handle. Raises ValueError if handle not exists. # # :returns: handle as hex-string like 'FF' # """ # handle = '' # for tag in self: # if tag.code in (5, 105): # handle = tag.value # break # int(handle, 16) # check for valid handle # return handle # # def replace_handle(self, new_handle): # """Replace existing handle. # """ # for index, tag in enumerate(self): # if tag.code in (5, 105): # self[index] = DXFTag(tag.code, new_handle) # return # # def dxftype(self): # return self[0].value # # def has_tag(self, code): # return any(True for tag in self if tag.code == code) # # def find_first(self, code, default=ValueError): # """Returns value of first DXFTag(code, value) or default if default != ValueError, else raises ValueError. # """ # for tag in self: # if tag.code == code: # return tag.value # if default is ValueError: # raise ValueError(code) # else: # return default # # def get_first_tag(self, code, default=ValueError): # """Returns first DXFTag(code, value) or default if default != ValueError, else raises ValueError. # """ # for tag in self: # if tag.code == code: # return tag # if default is ValueError: # raise ValueError(code) # else: # return default # # def find_all(self, code): # """Returns a list of DXFTag(code, value). # """ # return [tag for tag in self if tag.code == code] # # def tag_index(self, code, start=0, end=None): # """Return first index of DXFTag(code, value). # """ # if end is None: # end = len(self) # index = start # while index < end: # if self[index].code == code: # return index # index += 1 # raise ValueError(code) # # def update(self, code, value): # """Update first existing tag, raises ValueError if tag not exists. # """ # index = self.tag_index(code) # self[index] = DXFTag(code, value) # # def set_first(self, code, value): # """Update first existing DXFTag(code, value) or append a new # DXFTag(code, value). # # """ # try: # self.update(code, value) # except ValueError: # self.append(DXFTag(code, value)) # # def remove_tags(self, codes): # self[:] = [tag for tag in self if tag.code not in set(codes)] # # def collect_consecutive_tags(self, codes, start=0, end=None): # """Collect all consecutive tags with code in codes, start and end delimits the search range. A tag code not # in codes ends the process. # # Returns the collected tags in a collection of type Tag(). # """ # codes = frozenset(codes) # collected_tags = Tags() # if end is None: # end = len(self) # index = start # while index < end: # tag = self[index] # if tag.code in codes: # collected_tags.append(tag) # index += 1 # else: # break # return collected_tags # # class CompressedTags(object): # """Store multiple tags, compressed by zlib, as one DXFTag(code, value). value is a CompressedString() object. # """ # def __init__(self, code, tags): # self.code = code # self.value = CompressedString("".join(strtag2(tag) for tag in tags)) # # def __getitem__(self, item): # if item == 0: # return self.code # elif item == 1: # return self.value # else: # raise IndexError # # def decompress(self): # return Tags.from_text(self.value.decompress()) # # def write(self, stream): # stream.write(self.value.decompress()) # # Path: core/ezdxf/lldxf/const.py # COMPRESSED_TAGS = -10 . Output only the next line.
def dxffactory(self):
Next line prediction: <|code_start|># Purpose: default chunk # Created: 12.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" class DefaultChunk(object): def __init__(self, tags, drawing): self.tags = tags self._drawing = drawing @property <|code_end|> . Use current file imports: (from .tags import Tags, CompressedTags from .const import COMPRESSED_TAGS) and context including class names, function names, or small code snippets from other files: # Path: core/ezdxf/lldxf/tags.py # class Tags(list): # """ DXFTag() chunk as flat list. """ # def write(self, stream): # write_tags(stream, self) # # @classmethod # def from_text(cls, text): # return cls(skip_comments(string_tagger(text))) # # def __copy__(self): # return self.__class__(DXFTag(*tag) for tag in self) # # clone = __copy__ # # def get_handle(self): # """Get DXF handle. Raises ValueError if handle not exists. # # :returns: handle as hex-string like 'FF' # """ # handle = '' # for tag in self: # if tag.code in (5, 105): # handle = tag.value # break # int(handle, 16) # check for valid handle # return handle # # def replace_handle(self, new_handle): # """Replace existing handle. # """ # for index, tag in enumerate(self): # if tag.code in (5, 105): # self[index] = DXFTag(tag.code, new_handle) # return # # def dxftype(self): # return self[0].value # # def has_tag(self, code): # return any(True for tag in self if tag.code == code) # # def find_first(self, code, default=ValueError): # """Returns value of first DXFTag(code, value) or default if default != ValueError, else raises ValueError. # """ # for tag in self: # if tag.code == code: # return tag.value # if default is ValueError: # raise ValueError(code) # else: # return default # # def get_first_tag(self, code, default=ValueError): # """Returns first DXFTag(code, value) or default if default != ValueError, else raises ValueError. # """ # for tag in self: # if tag.code == code: # return tag # if default is ValueError: # raise ValueError(code) # else: # return default # # def find_all(self, code): # """Returns a list of DXFTag(code, value). # """ # return [tag for tag in self if tag.code == code] # # def tag_index(self, code, start=0, end=None): # """Return first index of DXFTag(code, value). # """ # if end is None: # end = len(self) # index = start # while index < end: # if self[index].code == code: # return index # index += 1 # raise ValueError(code) # # def update(self, code, value): # """Update first existing tag, raises ValueError if tag not exists. # """ # index = self.tag_index(code) # self[index] = DXFTag(code, value) # # def set_first(self, code, value): # """Update first existing DXFTag(code, value) or append a new # DXFTag(code, value). # # """ # try: # self.update(code, value) # except ValueError: # self.append(DXFTag(code, value)) # # def remove_tags(self, codes): # self[:] = [tag for tag in self if tag.code not in set(codes)] # # def collect_consecutive_tags(self, codes, start=0, end=None): # """Collect all consecutive tags with code in codes, start and end delimits the search range. A tag code not # in codes ends the process. # # Returns the collected tags in a collection of type Tag(). # """ # codes = frozenset(codes) # collected_tags = Tags() # if end is None: # end = len(self) # index = start # while index < end: # tag = self[index] # if tag.code in codes: # collected_tags.append(tag) # index += 1 # else: # break # return collected_tags # # class CompressedTags(object): # """Store multiple tags, compressed by zlib, as one DXFTag(code, value). value is a CompressedString() object. # """ # def __init__(self, code, tags): # self.code = code # self.value = CompressedString("".join(strtag2(tag) for tag in tags)) # # def __getitem__(self, item): # if item == 0: # return self.code # elif item == 1: # return self.value # else: # raise IndexError # # def decompress(self): # return Tags.from_text(self.value.decompress()) # # def write(self, stream): # stream.write(self.value.decompress()) # # Path: core/ezdxf/lldxf/const.py # COMPRESSED_TAGS = -10 . Output only the next line.
def dxffactory(self):
Given snippet: <|code_start|># Purpose: entity section # Created: 13.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" class ClassesSection(AbstractSection): name = 'classes' def __init__(self, tags, drawing): entity_space = EntitySpace(drawing.entitydb) super(ClassesSection, self).__init__(entity_space, tags, drawing) <|code_end|> , continue by predicting the next line. Consider current file imports: from ..entityspace import EntitySpace from .abstract import AbstractSection and context: # Path: core/ezdxf/entityspace.py # class EntitySpace(list): # """An EntitySpace is a collection of drawing entities. # The ENTITY section is such an entity space, but also blocks. # The EntitySpace stores only handles to the drawing entity database. # """ # def __init__(self, entitydb): # self._entitydb = entitydb # # def get_tags_by_handle(self, handle): # return self._entitydb[handle] # # def store_tags(self, tags): # try: # handle = tags.get_handle() # except ValueError: # no handle tag available # # handle is not stored in tags!!! # handle = self._entitydb.handles.next() # self.append(handle) # self._entitydb[handle] = tags # return handle # # def write(self, stream): # for handle in self: # # write linked entities # while handle is not None: # tags = self._entitydb[handle] # tags.write(stream) # handle = tags.link # # def delete_entity(self, entity): # # do not delete database objects - entity space just manage handles # self.remove(entity.dxf.handle) # # def delete_all_entities(self): # # do not delete database objects - entity space just manage handles # del self[:] # # def add_handle(self, handle): # self.append(handle) # # Path: core/ezdxf/sections/abstract.py # class AbstractSection(object): # name = 'abstract' # # def __init__(self, entity_space, tags, drawing): # self._entity_space = entity_space # self.drawing = drawing # if tags is not None: # self._build(tags) # # @property # def dxffactory(self): # return self.drawing.dxffactory # # @property # def entitydb(self): # return self.drawing.entitydb # # def get_entity_space(self): # return self._entity_space # # def _build(self, tags): # if tags[0] != (0, 'SECTION') or tags[1] != (2, self.name.upper()) or tags[-1] != (0, 'ENDSEC'): # raise DXFStructureError("Critical structure error in {} section.".format(self.name.upper())) # # if len(tags) == 3: # empty entities section # return # # linked_tags = get_tags_linker() # store_tags = self._entity_space.store_tags # entitydb = self.entitydb # fix_tags = self.dxffactory.modify_tags # # for group in TagGroups(islice(tags, 2, len(tags)-1)): # tags = ClassifiedTags(group) # fix_tags(tags) # post read tags fixer for VERTEX! # handle = entitydb.add_tags(tags) # if not linked_tags(tags, handle): # also creates the link structure as side effect # store_tags(tags) # add to entity space # # def write(self, stream): # stream.write(" 0\nSECTION\n 2\n%s\n" % self.name.upper()) # self._entity_space.write(stream) # stream.write(" 0\nENDSEC\n") # # def create_new_dxf_entity(self, _type, dxfattribs): # """ Create new DXF entity add it to th entity database and add it to the entity space. # """ # dxf_entity = self.dxffactory.create_db_entry(_type, dxfattribs) # self._entity_space.add_handle(dxf_entity.dxf.handle) # return dxf_entity # # def add_handle(self, handle): # self._entity_space.add_handle(handle) # # def remove_handle(self, handle): # self._entity_space.remove(handle) # # def delete_entity(self, entity): # self.remove_handle(entity.dxf.handle) # self.entitydb.delete_entity(entity) # # # start of public interface # # def __len__(self): # return len(self._entity_space) # # def __contains__(self, handle): # return handle in self._entity_space # # def query(self, query='*'): # return EntityQuery(iter(self), query) # # def delete_all_entities(self): # """ Delete all entities. """ # self._entity_space.delete_all_entities() # # # end of public interface which might include code, classes, or functions. Output only the next line.
def __iter__(self): # no layout setting required/possible
Given snippet: <|code_start|># Purpose: dxf tag type def # Created: 30.04.2014 # Copyright (C) 2014, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" class CompressedString(object): def __init__(self, s): self._data = zlib.compress(unicode2bytes(s)) def __str__(self): return 'compressed data' def __len__(self): return len(self._data) <|code_end|> , continue by predicting the next line. Consider current file imports: from .c23 import unicode2bytes import zlib and context: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 # def isstring(s): which might include code, classes, or functions. Output only the next line.
def write(self, stream):
Using the snippet: <|code_start|># Purpose: entity section # Created: 13.03.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" class ObjectsSection(ClassesSection): name = 'objects' @property <|code_end|> , determine the next line of code. You have imports: from .classes import ClassesSection from ..lldxf.const import DXFStructureError, DXFInternalEzdxfError from ..modern.groups import DXFGroupTable and context (class names, function names, or code) available: # Path: core/ezdxf/sections/classes.py # class ClassesSection(AbstractSection): # name = 'classes' # # def __init__(self, tags, drawing): # entity_space = EntitySpace(drawing.entitydb) # super(ClassesSection, self).__init__(entity_space, tags, drawing) # # def __iter__(self): # no layout setting required/possible # for handle in self._entity_space: # yield self.dxffactory.wrap_handle(handle) # # Path: core/ezdxf/lldxf/const.py # class DXFStructureError(DXFError): # pass # # class DXFInternalEzdxfError(DXFError): # pass # # Path: core/ezdxf/modern/groups.py # class DXFGroupTable(object): # def __init__(self, dxfgroups): # self.dxfgroups = dxfgroups # AcDbDictionary # self.objects_section = dxfgroups.drawing.objects # self._next_unnamed_number = 0 # # def __iter__(self): # wrap = self.dxfgroups.dxffactory.wrap_handle # for name, handle in self.dxfgroups.items(): # yield name, wrap(handle) # # def __len__(self): # return len(self.dxfgroups) # # def __contains__(self, name): # return name in self.dxfgroups # # def groups(self): # for name, group in self: # yield group # # def next_name(self): # name_exists = True # while name_exists: # name = self._next_name() # name_exists = name in self.dxfgroups # return name # # def _next_name(self): # self._next_unnamed_number += 1 # return "*A{}".format(self._next_unnamed_number) # # def add(self, name=None, description="", selectable=1): # TODO remove deprecated interface # warnings.warn("DXFGroupTable.add() is deprecated use DXFGroupTable.new() instead.", DeprecationWarning) # self.new(name, description, selectable) # # def new(self, name=None, description="", selectable=1): # if name in self.dxfgroups: # raise ValueError("Group '{}' already exists. Group name has to be unique.".format(name)) # unnamed = 0 # if name is None: # name = self.next_name() # unnamed = 1 # # The group name isn't stored in the group entity itself. # group = self.objects_section.create_new_dxf_entity("GROUP", dxfattribs={ # 'description': description, # 'unnamed': unnamed, # 'selectable': selectable, # }) # self.dxfgroups[name] = group.dxf.handle # group.dxf.owner = self.dxfgroups.dxf.handle # group table is owner of group # return group # # def get(self, name): # for group_name, group in self: # if name == group_name: # return group # raise KeyError("KeyError: '{}'".format(name)) # # def delete(self, group): # """Delete group. Does not delete any drawing entities referenced by this group. # """ # if isstring(group): # delete group by name # name = group # group_handle = self.dxfgroups[name] # del self.dxfgroups[name] # else: # group should be a DXFEntity # group_handle = group.dxf.handle # for name, _group in self: # if group_handle == _group.dxf.handle: # del self.dxfgroups[name] # return # raise ValueError("Group not in group table registered.") # self._destroy_dxf_group_entity(group_handle) # # def _destroy_dxf_group_entity(self, handle): # self.objects_section.remove_handle(handle) # remove from entity space # self.objects_section.entitydb.delete_handle(handle) # remove from drawing database # # def clear(self): # """Delete all groups. Does not delete any drawing entities referenced by this groups. # """ # for name, group in self: # destroy dxf group entities # self._destroy_dxf_group_entity(group.dxf.handle) # self.dxfgroups.clear() # delete all group references # # def cleanup(self): # """Removes invalid handles in all groups and removes empty groups. # """ # empty_groups = [] # for name, group in self: # group.remove_invalid_handles() # if not len(group): # remove empty group # # do not delete groups while iterating over groups! # empty_groups.append(name) # # # now delete emtpy groups # for name in empty_groups: # self.delete(name) . Output only the next line.
def roothandle(self):
Continue the code snippet: <|code_start|># Copyright (C) 2014, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" _decode_table = { 0x20: ' ', 0x40: '_', 0x5F: '@', } for c in range(0x41, 0x5F): _decode_table[c] = chr(0x41 + (0x5E - c)) # 0x5E -> 'A', 0x5D->'B', ... def decode(text_lines): def _decode(text): dectab = _decode_table # fast local var s = [] if PY3: text = bytes(text, 'ascii') else: text = map(ord, text) skip = False for c in text: if skip: skip = False continue if c in dectab: <|code_end|> . Use current file imports: from .c23 import PY3 and context (classes, functions, or code) from other files: # Path: core/ezdxf/tools/c23.py # PY3 = sys.version_info.major > 2 . Output only the next line.
s += dectab[c]
Given the following code snippet before the placeholder: <|code_start|># Purpose: DXF Pretty Printer # Created: 16.07.2015 # Copyright (C) 2015, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" if __name__ == "__main__": options.compress_binary_data = True filename = sys.argv[1] <|code_end|> , predict the next line using imports from the current file: import sys import os import io from .dxf2html import dxf2html from ezdxf import readfile, options and context including class names, function names, and sometimes code from other files: # Path: core/ezdxf/pp/dxf2html.py # def dxf2html(self): # """Creates a structured HTML view of the DXF tags - not a CAD drawing! # """ # def get_name(): # if self.drawing.filename is None: # return "unknown" # else: # filename = os.path.basename(self.drawing.filename) # return os.path.splitext(filename)[0] # # template = load_resource('dxf2html.html') # return template.format( # name=get_name(), # css=load_resource('dxf2html.css'), # javascript=load_resource('dxf2html.js'), # dxf_file=self.sections2html(), # section_links=self.sections_link_bar(), # ) . Output only the next line.
try:
Continue the code snippet: <|code_start|> '$UCSBASE': partial(SingleValue, code=2), '$UCSNAME': partial(SingleValue, code=2), '$UCSORG': Point3D, '$UCSORGBACK': Point3D, '$UCSORGBOTTOM': Point3D, '$UCSORGFRONT': Point3D, '$UCSORGLEFT': Point3D, '$UCSORGRIGHT': Point3D, '$UCSORGTOP': Point3D, '$UCSORTHOREF': partial(SingleValue, code=2), '$UCSORTHOVIEW': partial(SingleValue, code=70), '$UCSXDIR': Point3D, '$UCSYDIR': Point3D, '$UNITMODE': partial(SingleValue, code=70), '$USERI1': partial(SingleValue, code=70), '$USERI2': partial(SingleValue, code=70), '$USERI3': partial(SingleValue, code=70), '$USERI4': partial(SingleValue, code=70), '$USERI5': partial(SingleValue, code=70), '$USERR1': partial(SingleValue, code=40), '$USERR2': partial(SingleValue, code=40), '$USERR3': partial(SingleValue, code=40), '$USERR4': partial(SingleValue, code=40), '$USERR5': partial(SingleValue, code=40), '$USRTIMER': partial(SingleValue, code=70), '$VERSIONGUID': partial(SingleValue, code=2), '$VISRETAIN': partial(SingleValue, code=70), '$WORLDVIEW': partial(SingleValue, code=70), '$XCLIPFRAME': partial(SingleValue, code=280), '$XEDIT': partial(SingleValue, code=290), <|code_end|> . Use current file imports: from functools import partial from ..lldxf.hdrvars import SingleValue, Point2D, Point3D and context (classes, functions, or code) from other files: # Path: core/ezdxf/lldxf/hdrvars.py # def SingleValue(value, code=1): # return cast_tag((code, value)) # # def Point2D(value): # return DXFTag(10, (value[0], value[1])) # # def Point3D(value): # return DXFTag(10, (value[0], value[1], value[2])) . Output only the next line.
}
Predict the next line for this snippet: <|code_start|># Purpose: trusted string tag reader & stream tag reader # Created: 10.04.2016 # Copyright (C) 2016, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" DUMMY_TAG = DXFTag(999, '') <|code_end|> with the help of current file imports: from .types import DXFTag, is_point_code, cast_tag from .const import DXFStructureError and context from other files: # Path: core/ezdxf/lldxf/types.py # NONE_TAG = DXFTag(None, None) # TAG_STRING_FORMAT = '%3d\n%s\n' # TYPE_TABLE = _build_type_table([ # (internal_type, (-10, )), # spacial tags for internal use # (ustr, range(0, 10)), # (point_tuple, range(10, 20)), # 2d or 3d points # (float, range(20, 60)), # code 20-39 belongs to 2d/3d points and should not appear alone # (int, range(60, 100)), # (ustr, range(100, 106)), # (point_tuple, range(110, 113)), # 110, 111, 112 - UCS definition # (float, range(113, 150)), # 113-139 belongs to UCS definition and should not appear alone # (int, range(160, 170)), # (int, range(170, 180)), # (point_tuple, [210]), # extrusion direction # (float, range(211, 240)), # code 220, 230 belongs to extrusion direction and should not appear alone # (int, range(270, 290)), # (int, range(290, 300)), # bool 1=True 0=False # (ustr, range(300, 370)), # (int, range(370, 390)), # (ustr, range(390, 400)), # (int, range(400, 410)), # (ustr, range(410, 420)), # (int, range(420, 430)), # (ustr, range(430, 440)), # (int, range(440, 460)), # (float, range(460, 470)), # (ustr, range(470, 480)), # (ustr, range(480, 482)), # (ustr, range(999, 1010)), # (point_tuple, range(1010, 1020)), # (float, range(1020, 1060)), # code 1020-1039 belongs to 2d/3d points and should not appear alone # (int, range(1060, 1072)), # ]) # def point_tuple(value): # def _build_type_table(types): # def internal_type(value): # def is_point_code(code): # def is_point_tag(tag): # def cast_tag(tag, types=TYPE_TABLE): # def cast_tag_value(code, value, types=TYPE_TABLE): # def tag_type(code): # def strtag(tag): # def strtag2(tag): # def convert_tags_to_text_lines(line_tags): # def convert_text_lines_to_tags(text_lines): # # Path: core/ezdxf/lldxf/const.py # class DXFStructureError(DXFError): # pass , which may contain function names, class names, or code. Output only the next line.
def string_tagger(s):
Based on the snippet: <|code_start|># This file is part of the Edison Project. # Please refer to the LICENSE document that was supplied with this software for information on how it can be used. # Models for Change Management System class ChangeStatus(models.Model): Description = models.CharField(max_length=128) ClosesChangeRequest = models.BooleanField() def __unicode__(self): return self.Description class Meta: verbose_name = 'Current Status' verbose_name_plural = 'Change Statuses' class Scmtype(models.Model): Name = models.CharField(max_length=50) LibraryName = models.CharField(max_length=255) def __unicode__(self): <|code_end|> , predict the immediate next line with the help of imports: import datetime from django.db import models from django.contrib.auth.models import User from cmdb.models import ConfigurationItem and context (classes, functions, sometimes code) from other files: # Path: cmdb/models.py # class ConfigurationItem(models.Model): # Hostname = models.CharField(max_length=255) # Rack = models.ForeignKey('DataCentreRack') # Asset = models.CharField(max_length=128) # SupportTag = models.CharField(max_length=128) # Class = models.ForeignKey(ConfigurationItemClass) # Owner = models.ForeignKey(User) # NetworkInterface = models.ManyToManyField(NetworkInterface) # Profile = models.ForeignKey(ConfigurationItemProfile) # VMImagePath = models.CharField(max_length=255,blank=True,null=True,verbose_name='Path for Virtual Images') # IsVirtual = models.BooleanField() # BuildOnNextBoot = models.BooleanField(verbose_name="PXE Build",help_text="Should this box be rebuilt the next time it is booted?") # IsVMHost = models.BooleanField() # rootpwhash = models.CharField(max_length=255) # # def __unicode__(self): # return self.Hostname # # class Meta: # #permissions = () # verbose_name = 'Configuration Item' # verbose_name_plural = 'Configuration Items' # ordering = ['Hostname'] . Output only the next line.
return self.Name
Given the code snippet: <|code_start|># This file is part of the Edison Project. # Please refer to the LICENSE document that was supplied with this software for information on how it can be used. # Create your models here. # log the packages that are updated every time the package manager runs # # Need to write a yum/apt-plugin to post to the API for this... class Package(models.Model): Name = models.CharField(max_length=255) Version = models.CharField(max_length=255) Repository = models.CharField(max_length=255) AffectedItem = models.ForeignKey(ConfigurationItem) DateApplied = models.DateTimeField() def __unicode__(self): return u'%s - %s' % (self.Name,self.Version) <|code_end|> , generate the next line using the imports in this file: from django.db import models from cmdb.models import ConfigurationItem and context (functions, classes, or occasionally code) from other files: # Path: cmdb/models.py # class ConfigurationItem(models.Model): # Hostname = models.CharField(max_length=255) # Rack = models.ForeignKey('DataCentreRack') # Asset = models.CharField(max_length=128) # SupportTag = models.CharField(max_length=128) # Class = models.ForeignKey(ConfigurationItemClass) # Owner = models.ForeignKey(User) # NetworkInterface = models.ManyToManyField(NetworkInterface) # Profile = models.ForeignKey(ConfigurationItemProfile) # VMImagePath = models.CharField(max_length=255,blank=True,null=True,verbose_name='Path for Virtual Images') # IsVirtual = models.BooleanField() # BuildOnNextBoot = models.BooleanField(verbose_name="PXE Build",help_text="Should this box be rebuilt the next time it is booted?") # IsVMHost = models.BooleanField() # rootpwhash = models.CharField(max_length=255) # # def __unicode__(self): # return self.Hostname # # class Meta: # #permissions = () # verbose_name = 'Configuration Item' # verbose_name_plural = 'Configuration Items' # ordering = ['Hostname'] . Output only the next line.
class Meta:
Using the snippet: <|code_start|> Name = models.CharField(max_length=255) Creator = models.ForeignKey(User) Notes = models.TextField() AffectedItems = models.ManyToManyField(ConfigurationItem) def __unicode__(self): return self.Name class Meta: verbose_name = 'Orchestration Class' verbose_name_plural = 'Orchestration Classes' ordering = ['Name'] # Metadata to be provided for each cfgitem (Datacentre etc) class OrchestraMetaDataName(models.Model): Name = models.CharField(max_length=255) def __unicode__(self): return self.Name class Meta: verbose_name = 'Orchestration Metadata' ordering = ['Name'] class OrchestraMetaDataValue(models.Model): Name = models.ForeignKey(OrchestraMetaDataName) Value = models.CharField(max_length=255) AffectedItems = models.ManyToManyField(ConfigurationItem) def __unicode__(self): <|code_end|> , determine the next line of code. You have imports: from django.db import models from django.contrib.auth.models import User from cmdb.models import ConfigurationItem and context (class names, function names, or code) available: # Path: cmdb/models.py # class ConfigurationItem(models.Model): # Hostname = models.CharField(max_length=255) # Rack = models.ForeignKey('DataCentreRack') # Asset = models.CharField(max_length=128) # SupportTag = models.CharField(max_length=128) # Class = models.ForeignKey(ConfigurationItemClass) # Owner = models.ForeignKey(User) # NetworkInterface = models.ManyToManyField(NetworkInterface) # Profile = models.ForeignKey(ConfigurationItemProfile) # VMImagePath = models.CharField(max_length=255,blank=True,null=True,verbose_name='Path for Virtual Images') # IsVirtual = models.BooleanField() # BuildOnNextBoot = models.BooleanField(verbose_name="PXE Build",help_text="Should this box be rebuilt the next time it is booted?") # IsVMHost = models.BooleanField() # rootpwhash = models.CharField(max_length=255) # # def __unicode__(self): # return self.Hostname # # class Meta: # #permissions = () # verbose_name = 'Configuration Item' # verbose_name_plural = 'Configuration Items' # ordering = ['Hostname'] . Output only the next line.
return u'%s = %s' % (self.Name,self.Value)
Predict the next line after this snippet: <|code_start|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. setup(name='dizzy', version=CONFIG["GLOBALS"]["VERSION"], description='Dizzy Fuzzing Library', author='Daniel Mende', author_email='mail@c0decafe.de', url='https://c0decafe.de', license='BSD', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: BSD License', 'Natural Language :: English ', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Security', 'Topic :: Software Development :: Testing'], packages=['dizzy', 'dizzy.encodings', 'dizzy.functions', 'dizzy.objects', 'dizzy.probe', 'dizzy.session'], scripts=['dizzy_cmd'], <|code_end|> using the current file's imports: from setuptools import setup from dizzy.config import CONFIG and any relevant context from other files: # Path: dizzy/config.py # CONFIG = { "GLOBALS" : # { "VERSION" : "2.0", # "PLATFORM" : system(), # "RANDOM_SEED" : "1l0v3D1zzYc4us31tsR4nd0m1sr3Pr0duc4bl3!", # "CODEC" : "utf-8", # "DEFAULT_STR_LIB_NAME" : "std_string_lib.txt", # "INTERACTION_GLOBALS" : {}, # "GLOBAL_LIBRARY" : DizzyLibrary(), # "ROOTDIR" : "~/.local/share/dizzy", # "CONFIGFILE" : "dizzy.conf", # "SESSION" : None, # }, # } . Output only the next line.
data_files=[('share/dizzy/', ['lib/std_string_lib.txt'])],
Given snippet: <|code_start|># contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class TestTcp(TestCase): def test_probe(self): config_parser = ConfigParser() config_parser.add_section("probe") config_parser.set("probe", "type", "tcp") config_parser.set("probe", "target.host", "127.0.0.1") config_parser.set("probe", "target.port", "12345") self.section_proxy = config_parser['probe'] probe = DizzyProbe(self.section_proxy) probe.open() result = probe.probe() probe.close() <|code_end|> , continue by predicting the next line. Consider current file imports: from configparser import ConfigParser from unittest import TestCase, main from dizzy.probe.tcp import DizzyProbe and context: # Path: dizzy/probe/tcp.py # class DizzyProbe(object): # def __init__(self, section_proxy): # self.target_host = section_proxy.get('target_host') # self.target_port = section_proxy.getint('target_port') # self.source_host = section_proxy.get('source_host', None) # self.source_port = section_proxy.getint('source_port', None) # if not self.source_host is None and self.source_port <= 1024: # check_root("use a source port <= 1024") # self.timeout = section_proxy.getfloat('timeout', 1) # self.retry = section_proxy.getint('retry', 2) # self.is_open = False # self.socket = None # # try: # inet_aton(self.target_host) # self.af = AF_INET # except Exception as e: # try: # inet_pton(AF_INET6, self.target_host) # self.af = AF_INET6 # except Exception as f: # raise ProbeParseException("probe/tcp: unknown address family: %s: %s, %s" % # (self.target_host, e, f)) # if not self.source_host is None: # try: # inet_aton(self.source_host) # except Exception as e: # try: # inet_pton(AF_INET6, self.source_host) # except Exception as f: # raise ProbeParseException("probe/tcp: unknown address family: %s: %s, %s" % # (self.source_host, e, f)) # else: # if not self.af == AF_INET6: # raise ProbeParseException("probe/tcp: address family mismatch: %s - %s" % # (self.target_host, self.source_host)) # else: # if not self.af == AF_INET: # raise ProbeParseException("probe/tcp: address family mismatch: %s - %s" % # (self.target_host, self.source_host)) # # def open(self): # self.is_open = True # # def probe(self): # try: # self.socket = socket(self.af, SOCK_STREAM) # if self.target_host == "255.255.255.255": # self.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) # self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # self.socket.settimeout(self.timeout) # if not self.source_host is None and not self.source_port is None: # self.socket.bind((self.source_host, self.source_port)) # except Exception as e: # if not self.socket is None: # self.socket.close() # print_dizzy("probe/tcp: open error: %s" % e) # print_dizzy(e, DEBUG) # # for attempt in range(1, self.retry + 1): # print_dizzy("probe/tcp: probe attempt: %d" % attempt, VERBOSE_1) # try: # self.socket.connect((self.target_host, self.target_port)) # except (ConnectionAbortedError, ConnectionRefusedError) as e: # pass # except Exception as e: # print_dizzy("probe/tcp: probe error: '%s'" % type(e)) # print_dizzy(e, DEBUG) # else: # self.socket.close() # return True # return False # # def close(self): # if not self.is_open: # return # self.is_open = False which might include code, classes, or functions. Output only the next line.
self.assertTrue(result)
Given the following code snippet before the placeholder: <|code_start|> def test_eq(self): v1 = Value(b"\x01\x23", 10) v2 = Value(b"\x01\x23", 10) v3 = Value(b"\x02", 2) self.assertEqual(v1, v2) self.assertNotEqual(v2, v3) def test_add_aligned(self): chars1 = b"This is a test " chars2 = b"of adding adding aligned" chars3 = b" values." v1 = Value(chars1, len(chars1) * 8) v2 = Value(chars2, len(chars2) * 8) v3 = Value(chars3, len(chars3) * 8) v4 = v1 + v2 + v3 self.assertEqual(v4.byte, chars1 + chars2 + chars3) self.assertEqual(v4.size // 8, len(chars1) + len(chars2) + len(chars3)) def test_add_unaligned(self): v1 = Value(b"\x01\x23", 10) v2 = Value(b"\x02", 2) v3 = v1 + v2 self.assertEqual(v3.byte, b"\x04\x8e") self.assertEqual(v3.size, 12) v3 = v2 + v1 self.assertEqual(v3.byte, b"\x09\x23") self.assertEqual(v3.size, 12) v1 = Value(b'\x00\x00', 10) v2 = Value(b'\x00\x1f\xf0\xff', 30) <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase, main from dizzy.value import Value and context including class names, function names, and sometimes code from other files: # Path: dizzy/value.py # class Value(object): # def __init__(self, byte=b'', size=None): # if isinstance(byte, str): # from dizzy.config import CONFIG # byte = byte.encode(CONFIG["GLOBALS"]["CODEC"]) # if isinstance(byte, bytes): # if size is None: # self.byte = byte # self.size = len(self.byte) * 8 # elif isinstance(size, int): # self.byte = format_bytes(byte, size) # self.size = size # else: # raise TypeError() # else: # raise TypeError() # # def __add__(self, other): # result = Value() # # if self.size == 0: # result.byte = format_bytes(copy(other.byte), other.size) # result.size = other.size # elif other.size == 0: # result.byte = format_bytes(copy(self.byte), self.size) # result.size = self.size # else: # result.byte = bytearray(format_bytes(other.byte, other.size)) # mod = other.size % 8 # # if mod == 0: # result.byte = self.byte + result.byte # else: # for x in reversed(self.byte): # result.byte[0] |= (x << mod) & 0xff # result.byte.insert(0, x >> (8 - mod)) # # result.size = self.size + other.size # result.byte = bytes(format_bytes(result.byte, result.size)) # # return result # # def __bytes__(self): # return self.byte # # def __repr__(self): # return "Value(%s, %d)" % (self.byte, self.size) # # def __len__(self): # return self.size # # def __eq__(self, other): # if not isinstance(other, Value): # return False # return self.byte == other.byte and self.size == other.size . Output only the next line.
v3 = v1 + v2
Continue the code snippet: <|code_start|># modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class DizzState(State): def __init__(self, obj): State.__init__(self, obj) <|code_end|> . Use current file imports: from types import GeneratorType from dizzy.state import State from dizzy.dizz_iterator import DizzIterator and context (classes, functions, or code) from other files: # Path: dizzy/state.py # class State: # def __init__(self, obj): # self.obj = obj # self.iter = iter(obj) # self.bak = None # self.cur = None # # try: # # Get the first value(it is the default value) and save it in self.cur # self.next() # except StopIteration: # raise Exception("At least one element") # # def __next__(self): # try: # # Mutate and call the functions(if self.iter is a DizzIterator) and # # save the current state in self.cur # self.next() # except StopIteration: # # Reset the iterator and raise a StopIteration to signal that this field or dizz object is done # self.iter = iter(self.obj) # self.next() # raise StopIteration # # def call_functions(self, when): # self.cur = self.iter.call_functions(when) # return self.cur # # def next(self): # raise NotImplementedError("Overload Me !!!") . Output only the next line.
def next(self):
Given snippet: <|code_start|># distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. if CONFIG["DEPS"]["Crypto"]: def aes_encrypt(start, stop, key, mode=AES.MODE_CBC, mode_param=None, when=BOTH): def func(dizzy_iterator): enc = AES.new(key, mode, mode_param) dizzy_iterator[start:stop] = enc.encrypt(dizzy_iterator[start:stop].byte) return (func, when) def aes_decrypt(start, stop, key, mode=AES.MODE_CBC, mode_param=None, when=BOTH): <|code_end|> , continue by predicting the next line. Consider current file imports: from dizzy.config import CONFIG from Crypto.Cipher import AES from . import BOTH and context: # Path: dizzy/config.py # CONFIG = { "GLOBALS" : # { "VERSION" : "2.0", # "PLATFORM" : system(), # "RANDOM_SEED" : "1l0v3D1zzYc4us31tsR4nd0m1sr3Pr0duc4bl3!", # "CODEC" : "utf-8", # "DEFAULT_STR_LIB_NAME" : "std_string_lib.txt", # "INTERACTION_GLOBALS" : {}, # "GLOBAL_LIBRARY" : DizzyLibrary(), # "ROOTDIR" : "~/.local/share/dizzy", # "CONFIGFILE" : "dizzy.conf", # "SESSION" : None, # }, # } which might include code, classes, or functions. Output only the next line.
def func(dizzy_iterator):
Given the code snippet: <|code_start|> v = Value(l.rstrip(b'\n')) self.lib[listname].append(v) return self.lib[listname] class dizz_library(object): def __init__(self): self.lib = {} self.load_strings(CONFIG["GLOBALS"]["DEFAULT_STR_LIB"]) def get_next(self, obj): libidx = obj["length"] if libidx is None: if not obj["encoding"] is None: cur = obj["cur"].decode(obj["encoding"]) else: cur = obj["cur"].decode(CONFIG["GLOBALS"]["CODEC"]) else: cur = obj["cur"] if obj["_type"] == "list": libidx = obj["listname"] if not libidx in self.lib: self.gen_entries(libidx) if cur not in self.lib[libidx]: <|code_end|> , generate the next line using the imports in this file: from dizzy import tools from dizzy.value import Value and context (functions, classes, or occasionally code) from other files: # Path: dizzy/tools.py # def check_root(text): # def unique(seq, idfun=None): # def idfun(x): return x # def read_with_length(data, length, endian='!'): # def pack_with_length(value, size, endian='!'): # def chr_to_bin(c): # def str_to_bin(s): # def shift_left(inp, by, out=None): # def shift_right(inp, by, out=None): # def csum_inet(data, csum=0): # # Path: dizzy/value.py # class Value(object): # def __init__(self, byte=b'', size=None): # if isinstance(byte, str): # from dizzy.config import CONFIG # byte = byte.encode(CONFIG["GLOBALS"]["CODEC"]) # if isinstance(byte, bytes): # if size is None: # self.byte = byte # self.size = len(self.byte) * 8 # elif isinstance(size, int): # self.byte = format_bytes(byte, size) # self.size = size # else: # raise TypeError() # else: # raise TypeError() # # def __add__(self, other): # result = Value() # # if self.size == 0: # result.byte = format_bytes(copy(other.byte), other.size) # result.size = other.size # elif other.size == 0: # result.byte = format_bytes(copy(self.byte), self.size) # result.size = self.size # else: # result.byte = bytearray(format_bytes(other.byte, other.size)) # mod = other.size % 8 # # if mod == 0: # result.byte = self.byte + result.byte # else: # for x in reversed(self.byte): # result.byte[0] |= (x << mod) & 0xff # result.byte.insert(0, x >> (8 - mod)) # # result.size = self.size + other.size # result.byte = bytes(format_bytes(result.byte, result.size)) # # return result # # def __bytes__(self): # return self.byte # # def __repr__(self): # return "Value(%s, %d)" % (self.byte, self.size) # # def __len__(self): # return self.size # # def __eq__(self, other): # if not isinstance(other, Value): # return False # return self.byte == other.byte and self.size == other.size . Output only the next line.
if libidx == None:
Predict the next line after this snippet: <|code_start|># "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import math #from dizzy.config import CONFIG class DizzyLibrary(object): def __init__(self): self.lib = {} def load_file(self, filename, listname=None): if listname is None: listname = filename if listname in self.lib: return self.lib[listname] self.lib[listname] = [] with open(filename, 'r+b') as f: for l in f: if l.rstrip(b'\n') in self.lib[listname]: pass v = Value(l.rstrip(b'\n')) <|code_end|> using the current file's imports: from dizzy import tools from dizzy.value import Value and any relevant context from other files: # Path: dizzy/tools.py # def check_root(text): # def unique(seq, idfun=None): # def idfun(x): return x # def read_with_length(data, length, endian='!'): # def pack_with_length(value, size, endian='!'): # def chr_to_bin(c): # def str_to_bin(s): # def shift_left(inp, by, out=None): # def shift_right(inp, by, out=None): # def csum_inet(data, csum=0): # # Path: dizzy/value.py # class Value(object): # def __init__(self, byte=b'', size=None): # if isinstance(byte, str): # from dizzy.config import CONFIG # byte = byte.encode(CONFIG["GLOBALS"]["CODEC"]) # if isinstance(byte, bytes): # if size is None: # self.byte = byte # self.size = len(self.byte) * 8 # elif isinstance(size, int): # self.byte = format_bytes(byte, size) # self.size = size # else: # raise TypeError() # else: # raise TypeError() # # def __add__(self, other): # result = Value() # # if self.size == 0: # result.byte = format_bytes(copy(other.byte), other.size) # result.size = other.size # elif other.size == 0: # result.byte = format_bytes(copy(self.byte), self.size) # result.size = self.size # else: # result.byte = bytearray(format_bytes(other.byte, other.size)) # mod = other.size % 8 # # if mod == 0: # result.byte = self.byte + result.byte # else: # for x in reversed(self.byte): # result.byte[0] |= (x << mod) & 0xff # result.byte.insert(0, x >> (8 - mod)) # # result.size = self.size + other.size # result.byte = bytes(format_bytes(result.byte, result.size)) # # return result # # def __bytes__(self): # return self.byte # # def __repr__(self): # return "Value(%s, %d)" % (self.byte, self.size) # # def __len__(self): # return self.size # # def __eq__(self, other): # if not isinstance(other, Value): # return False # return self.byte == other.byte and self.size == other.size . Output only the next line.
self.lib[listname].append(v)
Using the snippet: <|code_start|># Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class TestIcmp(TestCase): def test_probe(self): config_parser = ConfigParser() <|code_end|> , determine the next line of code. You have imports: from configparser import ConfigParser from unittest import TestCase, main from dizzy.probe.icmp import DizzyProbe and context (class names, function names, or code) available: # Path: dizzy/probe/icmp.py # class DizzyProbe(object): # ICMP_ECHO_REPLY = 0 # ICMP_ECHO = 8 # ICMP6_ECHO = 128 # ICMP6_ECHO_REPLY = 129 # # def __init__(self, section_proxy): # check_root("use the ICMP probe") # # self.target_host = section_proxy.get('target_host') # self.timeout = section_proxy.getfloat('timeout', 1) # self.pkg_size = section_proxy.getint('pkg_size', 64) # self.retry = section_proxy.getint('retry', 2) # self.socket = None # self.is_open = False # # try: # inet_aton(self.target_host) # self.af = AF_INET # self.proto = getprotobyname("icmp") # echo = self.ICMP_ECHO # except Exception as e: # try: # inet_pton(AF_INET6, self.target_host) # self.af = AF_INET6 # self.proto = getprotobyname("ipv6-icmp") # echo = self.ICMP6_ECHO # except Exception as f: # raise ProbeParseException("probe/icmp: unknown address family: %s: %s, %s" % # (self.target_host, e, f)) # self.pid = getpid() & 0xFFFF # self.header = pack("!BBHHH", echo, 0, 0, self.pid, 0) # # pad = list() # for i in range(0x41, 0x41 + self.pkg_size): # pad += [(i & 0xff)] # self.data = bytearray(pad) # # checksum = csum_inet(self.header + self.data) # self.header = self.header[0:2] + checksum + self.header[4:] # # def open(self): # try: # self.socket = socket(self.af, SOCK_RAW, self.proto) # except error as e: # if not self.socket is None: # self.socket.close() # print_dizzy("probe/icmp: open error: '%s'" % e) # print_dizzy(e, DEBUG) # self.is_open = True # # def probe(self): # if not self.is_open: # print_dizzy("probe/tcp: not opened.", DEBUG) # return False # for attempt in range(1, self.retry + 1): # print_dizzy("probe/icmp: probe attempt: %d" % attempt, VERBOSE_1) # # try: # if self.af == AF_INET6: # self.socket.sendto(self.header + self.data, (self.target_host, 0, 0, 0)) # else: # self.socket.sendto(self.header + self.data, (self.target_host, 0)) # # if self.af == AF_INET6: # (data, (address, _, _, _)) = self.socket.recvfrom(2048) # if address == self.target_host: # pid, = unpack("!H", data[4:6]) # if data[0] == self.ICMP6_ECHO_REPLY and pid == self.pid: # return True # else: # (data, (address, _)) = self.socket.recvfrom(2048) # if address == self.target_host: # hl = (data[0] & 0x0f) * 4 # pid, = unpack("!H", data[hl + 4:hl + 6]) # if data[hl] == self.ICMP_ECHO_REPLY and pid == self.pid: # return True # except error as e: # print_dizzy("probe/icmp: reopening: '%s'" % e) # print_dizzy(e, DEBUG) # self.close() # self.open() # # return False # # def close(self): # if not self.is_open: # return # if self.socket is not None: # self.socket.close() # self.socket = None # self.is_open = False . Output only the next line.
config_parser.add_section("probe")
Predict the next line for this snippet: <|code_start|># notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. encodings = { "DER" : encode_der } def apply_extra_encoding(dizz_state): enclist = [] for obj in dizz_state: <|code_end|> with the help of current file imports: from dizzy.encodings.der import encode as encode_der and context from other files: # Path: dizzy/encodings/der.py # def encode(dizz_state): # tree = None # cur_depth = 0 # cur_node = None # # for obj in dizz_state: # enc = obj.obj.extra_encoding # if enc is "DER": # (_, depth) = obj.obj.extra_encoding_data # if tree is None: # if not depth is 0: # raise DizzyRuntimeException("DER encoding: First element needs depth 0.") # else: # tree = Tree(None, obj) # cur_node = tree # else: # if depth is cur_depth + 1: # new_node = Tree(cur_node, obj) # cur_node.down.append(new_node) # cur_node = new_node # cur_depth = depth # elif depth > cur_depth: # raise DizzyRuntimeException("DER encoding: Can only increment depth by one.") # elif depth is cur_depth: # new_node = Tree(cur_node.up, obj) # cur_node.up.down.append(new_node) # cur_node = new_node # else: # lam = cur_depth - depth # #print(cur_depth, lam) # for _ in range(lam): # #print (".") # if not cur_node.up is None: # #print (",") # cur_node = cur_node.up # #print(cur_node) # new_node = Tree(cur_node.up, obj) # cur_node.up.down.append(new_node) # cur_node = new_node # cur_depth = depth # # #from pprint import pprint # #pprint(tree) # # return enc_tree(tree) , which may contain function names, class names, or code. Output only the next line.
if not obj.obj.extra_encoding is None:
Continue the code snippet: <|code_start|> print_dizzy("pcap/init: using bpf '%s'." % self.filter, VERBOSE_1) self.snaplen = config.getint("snaplen", 8192) self.promisc = config.getboolean("promisc", True) self.to_ms = config.getint("to_ms", 10) self.cooldown = config.getint("cooldown", 0) self.filename = filename self.is_open = False def run(self): if self.pcap is None: return self.run = True self.pcap_object = self.pcap.open_live(self.interface, self.snaplen, self.promisc, self.to_ms) print_dizzy("pcap/run: pcap object opened.", VERBOSE_2) if not self.filter is "": self.pcap_object.setfilter(self.filter) self.pcap_dumper = self.pcap_object.dump_open(self.filename) print_dizzy("pcap/run: pcap dumper opened for file '%s'." % self.filename, VERBOSE_2) self.is_open = True while self.run: hdr, data = self.pcap_object.next() if not hdr is None: if self.is_open: self.pcap_dumper.dump(hdr, data) def stop(self): if self.pcap is None: return if self.cooldown > 0: print_dizzy("pcap/stop: cooling down for %d seconds." % self.cooldown, VERBOSE_1) <|code_end|> . Use current file imports: from threading import Thread from time import sleep from dizzy.tools import check_root from dizzy.log import print_dizzy, VERBOSE_1, VERBOSE_2 import pcapy and context (classes, functions, or code) from other files: # Path: dizzy/tools.py # def check_root(text): # if hasattr(os, 'geteuid'): # if os.geteuid() != 0: # print_dizzy("You must be root to " + text + ".") # exit(1) # else: # if ctypes.windll.shell32.IsUserAnAdmin() != 1: # print_dizzy("You must be Admin to " + text + ".") # exit(1) # # Path: dizzy/log.py # def print_dizzy(value, level=NORMAL): # if print_level >= level: # with print_lock: # print(print_colors[level], end='') # print(value) # if isinstance(value, Exception): # ex_type, ex, tb = exc_info() # print_tb(tb) # print(ENDC, end='') # # VERBOSE_1 = 3 # # VERBOSE_2 = 4 . Output only the next line.
sleep(self.cooldown)
Using the snippet: <|code_start|> except: print_dizzy("No usable pcap library found. Be sure you have pcapy installed!") print_dizzy("Pcap recording disabled!") self.pcap = None return self.interface = config.get("interface", "any") check_root("use the PCAP feature") print_dizzy("pcap/init: listening on interface '%s'." % self.interface, VERBOSE_1) if not self.interface is "any": if not self.interface in self.pcap.findalldevs(): print_dizzy("Device '%s' not found, recording on _all_ interfaces.") self.interface = "any" self.filter = config.get("filter", "") if not self.filter is "": print_dizzy("pcap/init: using bpf '%s'." % self.filter, VERBOSE_1) self.snaplen = config.getint("snaplen", 8192) self.promisc = config.getboolean("promisc", True) self.to_ms = config.getint("to_ms", 10) self.cooldown = config.getint("cooldown", 0) self.filename = filename self.is_open = False def run(self): if self.pcap is None: return self.run = True self.pcap_object = self.pcap.open_live(self.interface, self.snaplen, self.promisc, self.to_ms) print_dizzy("pcap/run: pcap object opened.", VERBOSE_2) if not self.filter is "": self.pcap_object.setfilter(self.filter) <|code_end|> , determine the next line of code. You have imports: from threading import Thread from time import sleep from dizzy.tools import check_root from dizzy.log import print_dizzy, VERBOSE_1, VERBOSE_2 import pcapy and context (class names, function names, or code) available: # Path: dizzy/tools.py # def check_root(text): # if hasattr(os, 'geteuid'): # if os.geteuid() != 0: # print_dizzy("You must be root to " + text + ".") # exit(1) # else: # if ctypes.windll.shell32.IsUserAnAdmin() != 1: # print_dizzy("You must be Admin to " + text + ".") # exit(1) # # Path: dizzy/log.py # def print_dizzy(value, level=NORMAL): # if print_level >= level: # with print_lock: # print(print_colors[level], end='') # print(value) # if isinstance(value, Exception): # ex_type, ex, tb = exc_info() # print_tb(tb) # print(ENDC, end='') # # VERBOSE_1 = 3 # # VERBOSE_2 = 4 . Output only the next line.
self.pcap_dumper = self.pcap_object.dump_open(self.filename)
Using the snippet: <|code_start|> def __init__(self, config, filename): Thread.__init__(self) try: self.pcap = pcapy except: print_dizzy("No usable pcap library found. Be sure you have pcapy installed!") print_dizzy("Pcap recording disabled!") self.pcap = None return self.interface = config.get("interface", "any") check_root("use the PCAP feature") print_dizzy("pcap/init: listening on interface '%s'." % self.interface, VERBOSE_1) if not self.interface is "any": if not self.interface in self.pcap.findalldevs(): print_dizzy("Device '%s' not found, recording on _all_ interfaces.") self.interface = "any" self.filter = config.get("filter", "") if not self.filter is "": print_dizzy("pcap/init: using bpf '%s'." % self.filter, VERBOSE_1) self.snaplen = config.getint("snaplen", 8192) self.promisc = config.getboolean("promisc", True) self.to_ms = config.getint("to_ms", 10) self.cooldown = config.getint("cooldown", 0) self.filename = filename self.is_open = False def run(self): if self.pcap is None: return self.run = True <|code_end|> , determine the next line of code. You have imports: from threading import Thread from time import sleep from dizzy.tools import check_root from dizzy.log import print_dizzy, VERBOSE_1, VERBOSE_2 import pcapy and context (class names, function names, or code) available: # Path: dizzy/tools.py # def check_root(text): # if hasattr(os, 'geteuid'): # if os.geteuid() != 0: # print_dizzy("You must be root to " + text + ".") # exit(1) # else: # if ctypes.windll.shell32.IsUserAnAdmin() != 1: # print_dizzy("You must be Admin to " + text + ".") # exit(1) # # Path: dizzy/log.py # def print_dizzy(value, level=NORMAL): # if print_level >= level: # with print_lock: # print(print_colors[level], end='') # print(value) # if isinstance(value, Exception): # ex_type, ex, tb = exc_info() # print_tb(tb) # print(ENDC, end='') # # VERBOSE_1 = 3 # # VERBOSE_2 = 4 . Output only the next line.
self.pcap_object = self.pcap.open_live(self.interface, self.snaplen, self.promisc, self.to_ms)
Given the following code snippet before the placeholder: <|code_start|># LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class Pcap(Thread): def __init__(self, config, filename): Thread.__init__(self) try: self.pcap = pcapy except: print_dizzy("No usable pcap library found. Be sure you have pcapy installed!") print_dizzy("Pcap recording disabled!") self.pcap = None return self.interface = config.get("interface", "any") check_root("use the PCAP feature") print_dizzy("pcap/init: listening on interface '%s'." % self.interface, VERBOSE_1) if not self.interface is "any": if not self.interface in self.pcap.findalldevs(): print_dizzy("Device '%s' not found, recording on _all_ interfaces.") self.interface = "any" self.filter = config.get("filter", "") <|code_end|> , predict the next line using imports from the current file: from threading import Thread from time import sleep from dizzy.tools import check_root from dizzy.log import print_dizzy, VERBOSE_1, VERBOSE_2 import pcapy and context including class names, function names, and sometimes code from other files: # Path: dizzy/tools.py # def check_root(text): # if hasattr(os, 'geteuid'): # if os.geteuid() != 0: # print_dizzy("You must be root to " + text + ".") # exit(1) # else: # if ctypes.windll.shell32.IsUserAnAdmin() != 1: # print_dizzy("You must be Admin to " + text + ".") # exit(1) # # Path: dizzy/log.py # def print_dizzy(value, level=NORMAL): # if print_level >= level: # with print_lock: # print(print_colors[level], end='') # print(value) # if isinstance(value, Exception): # ex_type, ex, tb = exc_info() # print_tb(tb) # print(ENDC, end='') # # VERBOSE_1 = 3 # # VERBOSE_2 = 4 . Output only the next line.
if not self.filter is "":
Continue the code snippet: <|code_start|># notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class InteractionState(State): def __init__(self, obj): State.__init__(self, obj) def next(self): # Mutate the dizz object before the dizz functions is call self.bak = self.iter.mutate() # Call the dizz functions and return the current state <|code_end|> . Use current file imports: from dizzy.state import State and context (classes, functions, or code) from other files: # Path: dizzy/state.py # class State: # def __init__(self, obj): # self.obj = obj # self.iter = iter(obj) # self.bak = None # self.cur = None # # try: # # Get the first value(it is the default value) and save it in self.cur # self.next() # except StopIteration: # raise Exception("At least one element") # # def __next__(self): # try: # # Mutate and call the functions(if self.iter is a DizzIterator) and # # save the current state in self.cur # self.next() # except StopIteration: # # Reset the iterator and raise a StopIteration to signal that this field or dizz object is done # self.iter = iter(self.obj) # self.next() # raise StopIteration # # def call_functions(self, when): # self.cur = self.iter.call_functions(when) # return self.cur # # def next(self): # raise NotImplementedError("Overload Me !!!") . Output only the next line.
self.cur = self.iter.call_functions()
Next line prediction: <|code_start|># # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class DizzyModule(object): def __init__(self, path, config): self.path = path self.global_config = config self.zipimport = zipimporter(path) <|code_end|> . Use current file imports: (from zipimport import zipimporter from dizzy.log import print_dizzy, VERBOSE_1, VERBOSE_2, DEBUG import sys) and context including class names, function names, or small code snippets from other files: # Path: dizzy/log.py # def print_dizzy(value, level=NORMAL): # if print_level >= level: # with print_lock: # print(print_colors[level], end='') # print(value) # if isinstance(value, Exception): # ex_type, ex, tb = exc_info() # print_tb(tb) # print(ENDC, end='') # # VERBOSE_1 = 3 # # VERBOSE_2 = 4 # # DEBUG = 5 . Output only the next line.
self.config = self.zipimport.load_module("config")
Next line prediction: <|code_start|># met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class DizzyModule(object): def __init__(self, path, config): self.path = path self.global_config = config <|code_end|> . Use current file imports: (from zipimport import zipimporter from dizzy.log import print_dizzy, VERBOSE_1, VERBOSE_2, DEBUG import sys) and context including class names, function names, or small code snippets from other files: # Path: dizzy/log.py # def print_dizzy(value, level=NORMAL): # if print_level >= level: # with print_lock: # print(print_colors[level], end='') # print(value) # if isinstance(value, Exception): # ex_type, ex, tb = exc_info() # print_tb(tb) # print(ENDC, end='') # # VERBOSE_1 = 3 # # VERBOSE_2 = 4 # # DEBUG = 5 . Output only the next line.
self.zipimport = zipimporter(path)
Predict the next line for this snippet: <|code_start|> class DizzyModule(object): def __init__(self, path, config): self.path = path self.global_config = config self.zipimport = zipimporter(path) self.config = self.zipimport.load_module("config") def load(self): inventory = self.zipimport.load_module(self.name).__all__ if "deps" in inventory: depspath = self.path + "/" + self.name + "/deps" sys.path.insert(0, depspath) print_dizzy("mod:%s/load: added dependency path '%s'" % (self.name, depspath), VERBOSE_1) sys.path.insert(0, self.path) if "dizz" in inventory: dizz = __import__(self.name + ".dizz").dizz self.dizz = [] for i in dizz.__all__: name = self.name + "/dizz/" + i obj = dizz.__loader__.get_data(name) self.dizz.append(name) self.global_config["DIZZ"][name] = obj.decode(self.global_config["GLOBALS"]["CODEC"]) print_dizzy("mod:%s/load: Loaded %d dizz files." % (self.name, len(self.dizz)), VERBOSE_1) print_dizzy("mod:%s/load: %s" % (self.name, self.dizz), DEBUG) if "act" in inventory: <|code_end|> with the help of current file imports: from zipimport import zipimporter from dizzy.log import print_dizzy, VERBOSE_1, VERBOSE_2, DEBUG import sys and context from other files: # Path: dizzy/log.py # def print_dizzy(value, level=NORMAL): # if print_level >= level: # with print_lock: # print(print_colors[level], end='') # print(value) # if isinstance(value, Exception): # ex_type, ex, tb = exc_info() # print_tb(tb) # print(ENDC, end='') # # VERBOSE_1 = 3 # # VERBOSE_2 = 4 # # DEBUG = 5 , which may contain function names, class names, or code. Output only the next line.
act = __import__(self.name + ".act").act
Here is a snippet: <|code_start|># Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class TestRegex(TestCase): def test_init(self): f = Regex("test", "[0-9a-f]{1,2}\.[a-g]") <|code_end|> . Write the next line using the current file imports: from unittest import TestCase, main from dizzy.objects.regex import Regex from dizzy.value import Value and context from other files: # Path: dizzy/objects/regex.py # class Regex: # def __init__(self, name, regex, limit=20): # if isinstance(name, str) and name: # self.name = name # else: # raise DizzyParseException("Name must be str and not empty.") # # if isinstance(regex, str): # self.regex = regex # else: # raise DizzyParseException("regex must be str.") # # if isinstance(limit, int): # self.limit = limit # else: # raise DizzyParseException("limit must be int.") # # self.len = count(self.regex, self.limit) # # def __iter__(self): # for string in generate(self.regex, self.limit): # value = bytes(string, encoding=CONFIG["GLOBALS"]["CODEC"]) # yield Value(value, len(value) * 8) # # def length(self): # return self.len # # Path: dizzy/value.py # class Value(object): # def __init__(self, byte=b'', size=None): # if isinstance(byte, str): # from dizzy.config import CONFIG # byte = byte.encode(CONFIG["GLOBALS"]["CODEC"]) # if isinstance(byte, bytes): # if size is None: # self.byte = byte # self.size = len(self.byte) * 8 # elif isinstance(size, int): # self.byte = format_bytes(byte, size) # self.size = size # else: # raise TypeError() # else: # raise TypeError() # # def __add__(self, other): # result = Value() # # if self.size == 0: # result.byte = format_bytes(copy(other.byte), other.size) # result.size = other.size # elif other.size == 0: # result.byte = format_bytes(copy(self.byte), self.size) # result.size = self.size # else: # result.byte = bytearray(format_bytes(other.byte, other.size)) # mod = other.size % 8 # # if mod == 0: # result.byte = self.byte + result.byte # else: # for x in reversed(self.byte): # result.byte[0] |= (x << mod) & 0xff # result.byte.insert(0, x >> (8 - mod)) # # result.size = self.size + other.size # result.byte = bytes(format_bytes(result.byte, result.size)) # # return result # # def __bytes__(self): # return self.byte # # def __repr__(self): # return "Value(%s, %d)" % (self.byte, self.size) # # def __len__(self): # return self.size # # def __eq__(self, other): # if not isinstance(other, Value): # return False # return self.byte == other.byte and self.size == other.size , which may include functions, classes, or code. Output only the next line.
self.assertEqual(f.name, "test")
Here is a snippet: <|code_start|># Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class TestRegex(TestCase): def test_init(self): f = Regex("test", "[0-9a-f]{1,2}\.[a-g]") <|code_end|> . Write the next line using the current file imports: from unittest import TestCase, main from dizzy.objects.regex import Regex from dizzy.value import Value and context from other files: # Path: dizzy/objects/regex.py # class Regex: # def __init__(self, name, regex, limit=20): # if isinstance(name, str) and name: # self.name = name # else: # raise DizzyParseException("Name must be str and not empty.") # # if isinstance(regex, str): # self.regex = regex # else: # raise DizzyParseException("regex must be str.") # # if isinstance(limit, int): # self.limit = limit # else: # raise DizzyParseException("limit must be int.") # # self.len = count(self.regex, self.limit) # # def __iter__(self): # for string in generate(self.regex, self.limit): # value = bytes(string, encoding=CONFIG["GLOBALS"]["CODEC"]) # yield Value(value, len(value) * 8) # # def length(self): # return self.len # # Path: dizzy/value.py # class Value(object): # def __init__(self, byte=b'', size=None): # if isinstance(byte, str): # from dizzy.config import CONFIG # byte = byte.encode(CONFIG["GLOBALS"]["CODEC"]) # if isinstance(byte, bytes): # if size is None: # self.byte = byte # self.size = len(self.byte) * 8 # elif isinstance(size, int): # self.byte = format_bytes(byte, size) # self.size = size # else: # raise TypeError() # else: # raise TypeError() # # def __add__(self, other): # result = Value() # # if self.size == 0: # result.byte = format_bytes(copy(other.byte), other.size) # result.size = other.size # elif other.size == 0: # result.byte = format_bytes(copy(self.byte), self.size) # result.size = self.size # else: # result.byte = bytearray(format_bytes(other.byte, other.size)) # mod = other.size % 8 # # if mod == 0: # result.byte = self.byte + result.byte # else: # for x in reversed(self.byte): # result.byte[0] |= (x << mod) & 0xff # result.byte.insert(0, x >> (8 - mod)) # # result.size = self.size + other.size # result.byte = bytes(format_bytes(result.byte, result.size)) # # return result # # def __bytes__(self): # return self.byte # # def __repr__(self): # return "Value(%s, %d)" % (self.byte, self.size) # # def __len__(self): # return self.size # # def __eq__(self, other): # if not isinstance(other, Value): # return False # return self.byte == other.byte and self.size == other.size , which may include functions, classes, or code. Output only the next line.
self.assertEqual(f.name, "test")
Using the snippet: <|code_start|> {'ip': self.equipment.ip, 'index': port}) else: # Refresh port nport = self.equipment.ports[port] # We ask PostgreSQL to compare MAC addresses for us txn.execute("SELECT 1 WHERE %(mac1)s::macaddr = %(mac2)s::macaddr", {'mac1': mac, 'mac2': nport.mac}) if not(txn.fetchall()) or \ name != nport.name or \ alias != nport.alias or \ cstate != nport.state or \ speed != nport.speed or \ duplex != nport.duplex or \ autoneg != nport.autoneg: # Delete the old one txn.execute("UPDATE port SET deleted=CURRENT_TIMESTAMP " "WHERE equipment = %(ip)s " "AND index = %(index)s AND deleted='infinity'", {'ip': self.equipment.ip, 'index': port}) else: # We don't need to update it, it is up-to-date uptodate.append(port) for port in self.equipment.ports: if port in uptodate: continue # Add port nport = self.equipment.ports[port] txn.execute(""" <|code_end|> , determine the next line of code. You have imports: from wiremaps.collector.datastore import ILocalVlan, IRemoteVlan and context (class names, function names, or code) available: # Path: wiremaps/collector/datastore.py # class ILocalVlan(IVlan): # """Interface for a local VLAN""" # # class IRemoteVlan(IVlan): # """Interface for a remote VLAN""" . Output only the next line.
INSERT INTO port
Given the code snippet: <|code_start|> else: # Refresh port nport = self.equipment.ports[port] # We ask PostgreSQL to compare MAC addresses for us txn.execute("SELECT 1 WHERE %(mac1)s::macaddr = %(mac2)s::macaddr", {'mac1': mac, 'mac2': nport.mac}) if not(txn.fetchall()) or \ name != nport.name or \ alias != nport.alias or \ cstate != nport.state or \ speed != nport.speed or \ duplex != nport.duplex or \ autoneg != nport.autoneg: # Delete the old one txn.execute("UPDATE port SET deleted=CURRENT_TIMESTAMP " "WHERE equipment = %(ip)s " "AND index = %(index)s AND deleted='infinity'", {'ip': self.equipment.ip, 'index': port}) else: # We don't need to update it, it is up-to-date uptodate.append(port) for port in self.equipment.ports: if port in uptodate: continue # Add port nport = self.equipment.ports[port] txn.execute(""" INSERT INTO port (equipment, index, name, alias, cstate, mac, speed, duplex, autoneg) <|code_end|> , generate the next line using the imports in this file: from wiremaps.collector.datastore import ILocalVlan, IRemoteVlan and context (functions, classes, or occasionally code) from other files: # Path: wiremaps/collector/datastore.py # class ILocalVlan(IVlan): # """Interface for a local VLAN""" # # class IRemoteVlan(IVlan): # """Interface for a remote VLAN""" . Output only the next line.
VALUES (%(ip)s, %(port)s, %(name)s, %(alias)s, %(state)s, %(address)s,
Based on the snippet: <|code_start|> COMPLETE_LIMIT = 10 class CompleteResource(rend.Page): addSlash = True docFactory = loaders.stan(T.html [ T.body [ T.p [ "Nothing here" ] ] ]) <|code_end|> , predict the immediate next line with the help of imports: import re from nevow import rend, tags as T, loaders from wiremaps.web.json import JsonPage and context (classes, functions, sometimes code) from other files: # Path: wiremaps/web/json.py # class JsonPage(rend.Page): # # flattenFactory = lambda self, *args: flat.flattenFactory(*args) # addSlash = True # # def renderHTTP(self, ctx): # request = inevow.IRequest(ctx) # if inevow.ICurrentSegments(ctx)[-1] != '': # request.redirect(request.URLPath().child('')) # return '' # request.setHeader("Content-Type", # "application/json; charset=UTF-8") # d = defer.maybeDeferred(self.data_json, ctx, None) # d.addCallback(lambda x: self.render_json(ctx, x)) # return d # # def render_json(self, ctx, data): # """Render the given data in a proper JSON string""" # # def sanitize(data, d=None): # """Nevow JSON serializer is not able to handle some types. # # We convert those types in proper types: # - string to unicode string # - PgSQL result set into list # - handling of deferreds # """ # if type(data) in [list, tuple] or \ # (PgSQL and isinstance(data, PgSQL.PgResultSet)): # return [sanitize(x, d) for x in data] # if PgSQL and isinstance(data, PgSQL.PgBooleanType): # if data: # return u"true" # return u"false" # if type(data) == str: # return unicode(data, errors='ignore') # if isinstance(data, rend.Fragment): # io = StringIO() # writer = io.write # finisher = lambda result: io.getvalue() # newctx = context.PageContext(parent=ctx, tag=data) # data.rememberStuff(newctx) # doc = data.docFactory.load() # newctx = context.WovenContext(newctx, T.invisible[doc]) # fl = self.flattenFactory(doc, newctx, writer, finisher) # fl.addCallback(sanitize, None) # d.append(fl) # return fl # if isinstance(data, defer.Deferred): # if data.called: # return sanitize(data.result) # return data # if isinstance(data, failure.Failure): # return unicode( # "<span class='error'>An error occured (%s)</span>" % data.getErrorMessage(), # errors='ignore') # return data # # def serialize(data): # return json.serialize(sanitize(data)) # # d = [] # data = sanitize(data, d) # d = defer.DeferredList(d) # d.addCallback(lambda x: serialize(data)) # return d . Output only the next line.
def __init__(self, dbpool):
Here is a snippet: <|code_start|> class MainPage(rend.Page): docFactory = loaders.xmlstr(resource_string(__name__, "main.xhtml")) def __init__(self, config, dbpool, collector): self.config = config['web'] self.dbpool = dbpool self.collector = collector rend.Page.__init__(self) <|code_end|> . Write the next line using the current file imports: import os from pkg_resources import resource_string, resource_filename from twisted.python import util from zope.interface import implements from nevow import rend, loaders from nevow import tags as T from nevow import static, inevow from wiremaps.web.api import ApiResource and context from other files: # Path: wiremaps/web/api.py # class ApiResource(rend.Page): # """Web service for Wiremaps. # """ # # addSlash = True # versions = [ "1.0", "1.1" ] # Valid versions # docFactory = loaders.stan(T.html [ T.body [ T.p [ "Valid versions are:" ], # T.ul [ [ T.li[v] for v in versions ] ] ] ]) # # def __init__(self, config, dbpool, collector): # self.config = config # self.dbpool = dbpool # self.collector = collector # rend.Page.__init__(self) # # def childFactory(self, ctx, version): # if version in ApiResource.versions: # version = tuple([int(i) for i in version.split(".")]) # ctx.remember(version, IApiVersion) # return ApiVersionedResource(self.config, self.dbpool, self.collector) # return None , which may include functions, classes, or code. Output only the next line.
def render_logo(self, ctx, data):
Using the snippet: <|code_start|> def render(self, data): return [("%s / Host" % self.discovery_name, T.invisible(data=data[0][2], render=T.directive("hostname")), data[0][2]), ("%s / IP" % self.discovery_name, T.invisible(data=data[0][0], render=T.directive("ip")), data[0][0]), ("%s / Description" % self.discovery_name, data[0][1], None), ("%s / Port" % self.discovery_name, data[0][3], None)] class PortDetailsLldp(PortDetailsDiscovery): discovery_name = "LLDP" query = """ SELECT DISTINCT mgmtip, sysdesc, sysname, portdesc FROM lldp_full WHERE equipment=%(ip)s AND port=%(port)s AND deleted='infinity' """ class PortDetailsCdp(PortDetailsDiscovery): discovery_name = "CDP" query = """ SELECT DISTINCT mgmtip, platform, sysname, portname <|code_end|> , determine the next line of code. You have imports: from twisted.internet import defer from nevow import loaders, rend from nevow import tags as T from wiremaps.web.json import JsonPage from wiremaps.web.common import FragmentMixIn and context (class names, function names, or code) available: # Path: wiremaps/web/json.py # class JsonPage(rend.Page): # # flattenFactory = lambda self, *args: flat.flattenFactory(*args) # addSlash = True # # def renderHTTP(self, ctx): # request = inevow.IRequest(ctx) # if inevow.ICurrentSegments(ctx)[-1] != '': # request.redirect(request.URLPath().child('')) # return '' # request.setHeader("Content-Type", # "application/json; charset=UTF-8") # d = defer.maybeDeferred(self.data_json, ctx, None) # d.addCallback(lambda x: self.render_json(ctx, x)) # return d # # def render_json(self, ctx, data): # """Render the given data in a proper JSON string""" # # def sanitize(data, d=None): # """Nevow JSON serializer is not able to handle some types. # # We convert those types in proper types: # - string to unicode string # - PgSQL result set into list # - handling of deferreds # """ # if type(data) in [list, tuple] or \ # (PgSQL and isinstance(data, PgSQL.PgResultSet)): # return [sanitize(x, d) for x in data] # if PgSQL and isinstance(data, PgSQL.PgBooleanType): # if data: # return u"true" # return u"false" # if type(data) == str: # return unicode(data, errors='ignore') # if isinstance(data, rend.Fragment): # io = StringIO() # writer = io.write # finisher = lambda result: io.getvalue() # newctx = context.PageContext(parent=ctx, tag=data) # data.rememberStuff(newctx) # doc = data.docFactory.load() # newctx = context.WovenContext(newctx, T.invisible[doc]) # fl = self.flattenFactory(doc, newctx, writer, finisher) # fl.addCallback(sanitize, None) # d.append(fl) # return fl # if isinstance(data, defer.Deferred): # if data.called: # return sanitize(data.result) # return data # if isinstance(data, failure.Failure): # return unicode( # "<span class='error'>An error occured (%s)</span>" % data.getErrorMessage(), # errors='ignore') # return data # # def serialize(data): # return json.serialize(sanitize(data)) # # d = [] # data = sanitize(data, d) # d = defer.DeferredList(d) # d.addCallback(lambda x: serialize(data)) # return d # # Path: wiremaps/web/common.py # class FragmentMixIn(rend.Fragment, RenderMixIn): # def __init__(self, dbpool, *args, **kwargs): # self.dbpool = dbpool # rend.Fragment.__init__(self, *args, **kwargs) . Output only the next line.
FROM cdp_full WHERE equipment=%(ip)s
Next line prediction: <|code_start|> vlanlist.append(str(row[0])) vid = T.td[T.span(data=row[0], render=T.directive("vlan"))] if row[1] is None: r.append(T.tr(_class=(i%2) and "odd" or "even")[ vid, notpresent, T.td[row[2]]]) elif row[2] is None: r.append(T.tr(_class=(i%2) and "odd" or "even") [vid, T.td[row[1]], notpresent]) elif row[1] == row[2]: r.append(T.tr(_class=(i%2) and "odd" or "even") [vid, T.td(colspan=2)[row[1]]]) else: r.append(T.tr(_class=(i%2) and "odd" or "even") [vid, T.td[row[1]], T.td[row[2]]]) i += 1 vlantable = T.table(_class="vlan")[ T.thead[T.td["VID"], T.td["Local"], T.td["Remote"]], r] return [('VLAN', [[ [T.span(data=v, render=T.directive("vlan")), " "] for v in vlanlist ], T.span(render=T.directive("tooltip"), data=vlantable)], ", ".join(vlanlist))] class PortDetailsFdb(PortRelatedDetails): query = """ SELECT DISTINCT f.mac, MIN(a.ip::text)::inet AS minip FROM fdb_full f LEFT OUTER JOIN arp_full a <|code_end|> . Use current file imports: (from twisted.internet import defer from nevow import loaders, rend from nevow import tags as T from wiremaps.web.json import JsonPage from wiremaps.web.common import FragmentMixIn) and context including class names, function names, or small code snippets from other files: # Path: wiremaps/web/json.py # class JsonPage(rend.Page): # # flattenFactory = lambda self, *args: flat.flattenFactory(*args) # addSlash = True # # def renderHTTP(self, ctx): # request = inevow.IRequest(ctx) # if inevow.ICurrentSegments(ctx)[-1] != '': # request.redirect(request.URLPath().child('')) # return '' # request.setHeader("Content-Type", # "application/json; charset=UTF-8") # d = defer.maybeDeferred(self.data_json, ctx, None) # d.addCallback(lambda x: self.render_json(ctx, x)) # return d # # def render_json(self, ctx, data): # """Render the given data in a proper JSON string""" # # def sanitize(data, d=None): # """Nevow JSON serializer is not able to handle some types. # # We convert those types in proper types: # - string to unicode string # - PgSQL result set into list # - handling of deferreds # """ # if type(data) in [list, tuple] or \ # (PgSQL and isinstance(data, PgSQL.PgResultSet)): # return [sanitize(x, d) for x in data] # if PgSQL and isinstance(data, PgSQL.PgBooleanType): # if data: # return u"true" # return u"false" # if type(data) == str: # return unicode(data, errors='ignore') # if isinstance(data, rend.Fragment): # io = StringIO() # writer = io.write # finisher = lambda result: io.getvalue() # newctx = context.PageContext(parent=ctx, tag=data) # data.rememberStuff(newctx) # doc = data.docFactory.load() # newctx = context.WovenContext(newctx, T.invisible[doc]) # fl = self.flattenFactory(doc, newctx, writer, finisher) # fl.addCallback(sanitize, None) # d.append(fl) # return fl # if isinstance(data, defer.Deferred): # if data.called: # return sanitize(data.result) # return data # if isinstance(data, failure.Failure): # return unicode( # "<span class='error'>An error occured (%s)</span>" % data.getErrorMessage(), # errors='ignore') # return data # # def serialize(data): # return json.serialize(sanitize(data)) # # d = [] # data = sanitize(data, d) # d = defer.DeferredList(d) # d.addCallback(lambda x: serialize(data)) # return d # # Path: wiremaps/web/common.py # class FragmentMixIn(rend.Fragment, RenderMixIn): # def __init__(self, dbpool, *args, **kwargs): # self.dbpool = dbpool # rend.Fragment.__init__(self, *args, **kwargs) . Output only the next line.
ON a.mac = f.mac AND a.deleted='infinity'
Given snippet: <|code_start|> self.input_faa_2 = resource_filename(__name__, 'data/target_fasta.faa') self.input_gb_1 = resource_filename(__name__, 'data/query_genbank.gb') self.input_gb_2 = resource_filename(__name__, 'data/target_genbank.gb') self.outdir = tempfile.mkdtemp(prefix='test_pypaswas_aligner') def test_pypaswas_aligner_invalid_options(self): ''' This test checks the raised exception when arguments are missing or incorrect ''' # Missing arguments, this should raise an InvalidOptionException sys.argv = [__name__] self.assertRaises(InvalidOptionException, self.instance.run) # Trying to get output using the unsupported BAM output format sys.argv = [__name__, self.input_faa_1, self.input_faa_2, '--outputformat=BAM'] self.assertRaises(InvalidOptionException, self.instance.run) def _defunct_test_pypaswas_aligner_basic(self): ''' Input two FASTA files and align them using all default settings. Compares the output alignment with the included reference file. ''' # Expected output reference = resource_filename(__name__, 'data/reference/aligner_basic_output.txt') # Most basic alignment (default settings, default alignment output format) outfile = '{}/basic_alignment.txt'.format(self.outdir) sys.argv = [__name__, self.input_faa_1, self.input_faa_2, '-o', outfile] # Start pyPaSWAS using defined arguments in sys.argv <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import unittest import tempfile import shutil from pkg_resources import resource_filename #@UnresolvedImport from pyPaSWAS.Core.Exceptions import InvalidOptionException from pyPaSWAS import pypaswasall and context: # Path: pyPaSWAS/Core/Exceptions.py # class InvalidOptionException(Exception): # ''' # This class is used to give a consistent user interface to exceptions that are specific for pyPaSWAS. # ''' # # Path: pyPaSWAS/pypaswasall.py # class Pypaswas(object): # def __init__(self, config=None): # def _get_default_logger(self): # def _get_formatter(self, results): # def _set_outfile(self): # def _get_query_sequences(self, queryfile, start =0, end=None): # def _get_target_sequences(self, databasefile, start =0, end=None): # def _set_scoring_matrix(self): # def _set_output_format(self): # def _set_program(self): # def run(self): which might include code, classes, or functions. Output only the next line.
self.instance.run()
Based on the snippet: <|code_start|>''' Created on March 13, 2013 @author: tbeek ''' class Test(unittest.TestCase): ''' Runs the application as the end-user would, testing for correct exception handling as well as final output checks comparing generated output to reference (curated) output. ''' def setUp(self): # Create pyPaSWAS instance self.instance = pypaswasall.Pypaswas() # Input files self.input_faa_1 = resource_filename(__name__, 'data/query_fasta.faa') <|code_end|> , predict the immediate next line with the help of imports: import sys import unittest import tempfile import shutil from pkg_resources import resource_filename #@UnresolvedImport from pyPaSWAS.Core.Exceptions import InvalidOptionException from pyPaSWAS import pypaswasall and context (classes, functions, sometimes code) from other files: # Path: pyPaSWAS/Core/Exceptions.py # class InvalidOptionException(Exception): # ''' # This class is used to give a consistent user interface to exceptions that are specific for pyPaSWAS. # ''' # # Path: pyPaSWAS/pypaswasall.py # class Pypaswas(object): # def __init__(self, config=None): # def _get_default_logger(self): # def _get_formatter(self, results): # def _set_outfile(self): # def _get_query_sequences(self, queryfile, start =0, end=None): # def _get_target_sequences(self, databasefile, start =0, end=None): # def _set_scoring_matrix(self): # def _set_output_format(self): # def _set_program(self): # def run(self): . Output only the next line.
self.input_faa_2 = resource_filename(__name__, 'data/target_fasta.faa')
Given snippet: <|code_start|>'''This module contains the different readers used to parse both the target and the query records from files.''' class Reader(object): '''The generic reader from which other readers inherit some common functionalities. Each reader should implement ''' def __init__(self, logger, path, filetype, limitlength=5000): '''path: the absolute path to the file that contains the records limitlength: the maximimum length of the records that will be used for the alignment ''' self.logger = logger self.logger.debug('Initializing reader\n\tpath = {0}\n\tlimitlength = {1}...'.format(path, limitlength)) self.rc_string = "_RC" self.path = '' self.filetype = filetype self.records = None self.limitlength = limitlength self._set_path(path) self._set_limit_length(limitlength) <|code_end|> , continue by predicting the next line. Consider current file imports: import os.path from itertools import islice from Bio import SeqIO from Bio.Seq import Seq from pyPaSWAS.Core.SWSeqRecord import SWSeqRecord from pyPaSWAS.Core.Exceptions import InvalidOptionException from pyPaSWAS.Core.Exceptions import ReaderException and context: # Path: pyPaSWAS/Core/SWSeqRecord.py # class SWSeqRecord(SeqRecord): # ''' # TODO: Docstring # ''' # # start_position = 0 # distance = 0 # original_length = 0 # # def __init__(self, seq, identifier, start_position=0, original_length = None, distance = 0, refID = None): # super(SWSeqRecord, self).__init__(seq.upper(), identifier) # self.start_position = start_position # if original_length ==None: # self.original_length = len(seq) # else: # self.original_length = original_length # self.distance = distance # self.refID = refID # # def _compare(self, other): # ''' # TODO: Docstring # :param other: # ''' # self.distance = math.sqrt((self.count[0] - other.count[0]) ** 2 + (self.count[1] - other.count[1]) ** 2 + # (self.count[2] - other.count[2]) ** 2 + (self.count[3] - other.count[3]) ** 2 + # (self.count[4] - other.count[4]) ** 2) # other.distance = self.distance # return self.distance # # Path: pyPaSWAS/Core/Exceptions.py # class InvalidOptionException(Exception): # ''' # This class is used to give a consistent user interface to exceptions that are specific for pyPaSWAS. # ''' # # Path: pyPaSWAS/Core/Exceptions.py # class ReaderException(Exception): # ''' # This class is used to indicate no sequences left in file. # ''' which might include code, classes, or functions. Output only the next line.
self.logger.debug('Initializing reader finished.')
Based on the snippet: <|code_start|>'''This module contains the different readers used to parse both the target and the query records from files.''' class Reader(object): '''The generic reader from which other readers inherit some common functionalities. Each reader should implement ''' def __init__(self, logger, path, filetype, limitlength=5000): '''path: the absolute path to the file that contains the records limitlength: the maximimum length of the records that will be used for the alignment ''' self.logger = logger self.logger.debug('Initializing reader\n\tpath = {0}\n\tlimitlength = {1}...'.format(path, limitlength)) self.rc_string = "_RC" self.path = '' self.filetype = filetype self.records = None <|code_end|> , predict the immediate next line with the help of imports: import os.path from itertools import islice from Bio import SeqIO from Bio.Seq import Seq from pyPaSWAS.Core.SWSeqRecord import SWSeqRecord from pyPaSWAS.Core.Exceptions import InvalidOptionException from pyPaSWAS.Core.Exceptions import ReaderException and context (classes, functions, sometimes code) from other files: # Path: pyPaSWAS/Core/SWSeqRecord.py # class SWSeqRecord(SeqRecord): # ''' # TODO: Docstring # ''' # # start_position = 0 # distance = 0 # original_length = 0 # # def __init__(self, seq, identifier, start_position=0, original_length = None, distance = 0, refID = None): # super(SWSeqRecord, self).__init__(seq.upper(), identifier) # self.start_position = start_position # if original_length ==None: # self.original_length = len(seq) # else: # self.original_length = original_length # self.distance = distance # self.refID = refID # # def _compare(self, other): # ''' # TODO: Docstring # :param other: # ''' # self.distance = math.sqrt((self.count[0] - other.count[0]) ** 2 + (self.count[1] - other.count[1]) ** 2 + # (self.count[2] - other.count[2]) ** 2 + (self.count[3] - other.count[3]) ** 2 + # (self.count[4] - other.count[4]) ** 2) # other.distance = self.distance # return self.distance # # Path: pyPaSWAS/Core/Exceptions.py # class InvalidOptionException(Exception): # ''' # This class is used to give a consistent user interface to exceptions that are specific for pyPaSWAS. # ''' # # Path: pyPaSWAS/Core/Exceptions.py # class ReaderException(Exception): # ''' # This class is used to indicate no sequences left in file. # ''' . Output only the next line.
self.limitlength = limitlength
Given the following code snippet before the placeholder: <|code_start|> pushed = restore_organization_to_ckan(self.catalog, 'owner_org', 'portal', 'apikey', identifiers) self.assertEqual([identifiers[1]], pushed) mock_push_thm.assert_called_with(self.catalog, 'portal', 'apikey') mock_push_dst.assert_called_with(self.catalog, 'owner_org', identifiers[1], 'portal', 'apikey', catalog_id=None, demote_superThemes=False, demote_themes=False, download_strategy=None, generate_new_access_url=None, origin_tz=DEFAULT_TIMEZONE, dst_tz=DEFAULT_TIMEZONE) @patch('pydatajson.federation.push_new_themes') @patch('ckanapi.remoteckan.ActionShortcut') def test_restore_catalog_to_ckan(self, mock_action, mock_push_thm, mock_push_dst): identifiers = [ds['identifier'] for ds in self.catalog.datasets] mock_action.return_value.organization_list.return_value = \ ['org_1', 'org_2'] mock_action.return_value.organization_show.side_effect = [ {'packages': [{'id': identifiers[0]}]}, {'packages': [{'id': identifiers[1]}]}, ] mock_push_dst.side_effect = (lambda *args, **kwargs: args[2]) pushed = restore_catalog_to_ckan(self.catalog, 'origin', 'destination', 'apikey') mock_push_dst.assert_any_call(self.catalog, 'org_1', identifiers[0], 'destination', 'apikey', <|code_end|> , predict the next line using imports from the current file: import unittest import os import re import json from mock import patch, MagicMock, ANY from unittest.mock import patch, MagicMock, ANY from .context import pydatajson from pydatajson.federation import * from pydatajson.helpers import is_local_andino_resource from ckanapi.errors import NotFound, CKANAPIError and context including class names, function names, and sometimes code from other files: # Path: tests/context.py # # Path: pydatajson/helpers.py # def is_local_andino_resource(catalog, distribution): # dist_type = distribution.get('type') # if dist_type is not None: # return dist_type == 'file.upload' # homepage = catalog.get('homepage') # if homepage is not None: # return distribution.get('downloadURL', '').startswith(homepage) # return False . Output only the next line.
catalog_id=None,
Next line prediction: <|code_start|> 'url': 'otherlicense.com', 'id': '2'}] elif action == 'package_update': self.assertEqual('notspecified', data_dict['license_id']) return data_dict else: return [] mock_portal.return_value.call_action = mock_call_action push_dataset_to_ckan(self.catalog, 'owner', self.dataset_id, 'portal', 'key', catalog_id=self.catalog_id) def test_dataset_without_license_sets_notspecified(self, mock_portal): def mock_call_action(action, data_dict=None): if action == 'license_list': return [{'title': 'somelicense', 'url': 'somelicense.com', 'id': '1'}, {'title': 'otherlicense', 'url': 'otherlicense.com', 'id': '2'}] elif action == 'package_update': self.assertEqual('notspecified', data_dict['license_id']) return data_dict else: return [] mock_portal.return_value.call_action = mock_call_action push_dataset_to_ckan( self.minimum_catalog, 'owner', self.minimum_dataset['identifier'], 'portal', 'key', <|code_end|> . Use current file imports: (import unittest import os import re import json from mock import patch, MagicMock, ANY from unittest.mock import patch, MagicMock, ANY from .context import pydatajson from pydatajson.federation import * from pydatajson.helpers import is_local_andino_resource from ckanapi.errors import NotFound, CKANAPIError) and context including class names, function names, or small code snippets from other files: # Path: tests/context.py # # Path: pydatajson/helpers.py # def is_local_andino_resource(catalog, distribution): # dist_type = distribution.get('type') # if dist_type is not None: # return dist_type == 'file.upload' # homepage = catalog.get('homepage') # if homepage is not None: # return distribution.get('downloadURL', '').startswith(homepage) # return False . Output only the next line.
catalog_id=self.minimum_catalog_id)
Given snippet: <|code_start|> class DistributionUrlsValidator(UrlValidator): def validate(self): datasets = self.catalog.get('dataset') metadata = [] urls = [] for dataset_idx, dataset in enumerate(datasets): distributions = dataset.get('distribution') for distribution_idx, distribution in enumerate(distributions): distribution_title = distribution.get('title') access_url = distribution.get('accessURL') download_url = distribution.get('downloadURL') metadata.append({ "dataset_idx": dataset_idx, "dist_idx": distribution_idx, "dist_title": distribution_title }) urls += [access_url, download_url] sync_res = threading_helper \ .apply_threading(urls, self.is_working_url, self.threads_count) for i in range(len(metadata)): actual_metadata = metadata[i] <|code_end|> , continue by predicting the next line. Consider current file imports: import pydatajson.custom_exceptions as ce from pydatajson import threading_helper from pydatajson.validators.url_validator import UrlValidator and context: # Path: pydatajson/threading_helper.py # def apply_threading(l, function, cant_threads, **kwargs): # # Path: pydatajson/validators/url_validator.py # class UrlValidator(SimpleValidator): # # def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count): # super(UrlValidator, self).__init__(catalog) # self.verify_ssl = verify_ssl # self.url_check_timeout = url_check_timeout # self.threads_count = threads_count # # def validate(self): # raise NotImplementedError # # def is_working_url(self, url): # try: # response = requests.head(url, # timeout=self.url_check_timeout, # verify=self.verify_ssl) # matches = [] # if response.status_code not in EXCEPTION_STATUS_CODES: # matches = \ # [re.match(pattern, str(response.status_code)) is not None # for pattern in INVALID_STATUS_CODES_REGEX] # return True not in matches, response.status_code # except Timeout: # return False, 408 # except (RequestException, Exception): # return False, None which might include code, classes, or functions. Output only the next line.
dataset_idx = actual_metadata["dataset_idx"]
Continue the code snippet: <|code_start|> "dist_title": distribution_title }) urls += [access_url, download_url] sync_res = threading_helper \ .apply_threading(urls, self.is_working_url, self.threads_count) for i in range(len(metadata)): actual_metadata = metadata[i] dataset_idx = actual_metadata["dataset_idx"] distribution_idx = actual_metadata["dist_idx"] distribution_title = actual_metadata["dist_title"] k = i * 2 access_url = urls[k] download_url = urls[k + 1] access_url_is_valid, access_url_status_code = sync_res[k] download_url_is_valid, download_url_status_code = sync_res[k + 1] if not access_url_is_valid: yield ce.BrokenAccessUrlError(dataset_idx, distribution_idx, distribution_title, access_url, access_url_status_code) if not download_url_is_valid: yield ce.BrokenDownloadUrlError(dataset_idx, <|code_end|> . Use current file imports: import pydatajson.custom_exceptions as ce from pydatajson import threading_helper from pydatajson.validators.url_validator import UrlValidator and context (classes, functions, or code) from other files: # Path: pydatajson/threading_helper.py # def apply_threading(l, function, cant_threads, **kwargs): # # Path: pydatajson/validators/url_validator.py # class UrlValidator(SimpleValidator): # # def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count): # super(UrlValidator, self).__init__(catalog) # self.verify_ssl = verify_ssl # self.url_check_timeout = url_check_timeout # self.threads_count = threads_count # # def validate(self): # raise NotImplementedError # # def is_working_url(self, url): # try: # response = requests.head(url, # timeout=self.url_check_timeout, # verify=self.verify_ssl) # matches = [] # if response.status_code not in EXCEPTION_STATUS_CODES: # matches = \ # [re.match(pattern, str(response.status_code)) is not None # for pattern in INVALID_STATUS_CODES_REGEX] # return True not in matches, response.status_code # except Timeout: # return False, 408 # except (RequestException, Exception): # return False, None . Output only the next line.
distribution_idx,
Here is a snippet: <|code_start|> class LandingPagesValidator(UrlValidator): def validate(self): datasets = self.catalog.get('dataset') datasets = filter(lambda x: x.get('landingPage'), datasets) metadata = [] urls = [] for dataset_idx, dataset in enumerate(datasets): metadata.append({ "dataset_idx": dataset_idx, "dataset_title": dataset.get('title'), "landing_page": dataset.get('landingPage'), }) urls.append(dataset.get('landingPage')) sync_res = threading_helper \ .apply_threading(urls, self.is_working_url, self.threads_count) for i in range(len(sync_res)): valid, status_code = sync_res[i] act_metadata = metadata[i] dataset_idx = act_metadata["dataset_idx"] dataset_title = act_metadata["dataset_title"] <|code_end|> . Write the next line using the current file imports: import pydatajson.custom_exceptions as ce from pydatajson import threading_helper from pydatajson.validators.url_validator import UrlValidator and context from other files: # Path: pydatajson/threading_helper.py # def apply_threading(l, function, cant_threads, **kwargs): # # Path: pydatajson/validators/url_validator.py # class UrlValidator(SimpleValidator): # # def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count): # super(UrlValidator, self).__init__(catalog) # self.verify_ssl = verify_ssl # self.url_check_timeout = url_check_timeout # self.threads_count = threads_count # # def validate(self): # raise NotImplementedError # # def is_working_url(self, url): # try: # response = requests.head(url, # timeout=self.url_check_timeout, # verify=self.verify_ssl) # matches = [] # if response.status_code not in EXCEPTION_STATUS_CODES: # matches = \ # [re.match(pattern, str(response.status_code)) is not None # for pattern in INVALID_STATUS_CODES_REGEX] # return True not in matches, response.status_code # except Timeout: # return False, 408 # except (RequestException, Exception): # return False, None , which may include functions, classes, or code. Output only the next line.
landing_page = act_metadata["landing_page"]
Here is a snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- class LandingPagesValidator(UrlValidator): def validate(self): datasets = self.catalog.get('dataset') datasets = filter(lambda x: x.get('landingPage'), datasets) metadata = [] urls = [] for dataset_idx, dataset in enumerate(datasets): metadata.append({ "dataset_idx": dataset_idx, "dataset_title": dataset.get('title'), "landing_page": dataset.get('landingPage'), }) urls.append(dataset.get('landingPage')) sync_res = threading_helper \ .apply_threading(urls, self.is_working_url, <|code_end|> . Write the next line using the current file imports: import pydatajson.custom_exceptions as ce from pydatajson import threading_helper from pydatajson.validators.url_validator import UrlValidator and context from other files: # Path: pydatajson/threading_helper.py # def apply_threading(l, function, cant_threads, **kwargs): # # Path: pydatajson/validators/url_validator.py # class UrlValidator(SimpleValidator): # # def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count): # super(UrlValidator, self).__init__(catalog) # self.verify_ssl = verify_ssl # self.url_check_timeout = url_check_timeout # self.threads_count = threads_count # # def validate(self): # raise NotImplementedError # # def is_working_url(self, url): # try: # response = requests.head(url, # timeout=self.url_check_timeout, # verify=self.verify_ssl) # matches = [] # if response.status_code not in EXCEPTION_STATUS_CODES: # matches = \ # [re.match(pattern, str(response.status_code)) is not None # for pattern in INVALID_STATUS_CODES_REGEX] # return True not in matches, response.status_code # except Timeout: # return False, 408 # except (RequestException, Exception): # return False, None , which may include functions, classes, or code. Output only the next line.
self.threads_count)
Given the code snippet: <|code_start|> """Convierte el resultado de action.status_show() en metadata a nivel de catálogo.""" catalog = dict() catalog_mapping = { "site_title": "title", "site_description": "description" } for status_key, catalog_key in iteritems(catalog_mapping): try: catalog[catalog_key] = status[status_key] except BaseException: logger.exception(""" La clave '%s' no está en el endpoint de status. No se puede completar catalog['%s'].""", status_key, catalog_key) publisher_mapping = { "site_title": "name", "error_emails_to": "mbox" } if any([k in status for k in publisher_mapping.keys()]): catalog["publisher"] = dict() for status_key, publisher_key in iteritems(publisher_mapping): try: catalog['publisher'][publisher_key] = status[status_key] except BaseException: logger.exception(""" La clave '%s' no está en el endpoint de status. No se puede <|code_end|> , generate the next line using the imports in this file: import os.path import logging import json import time import urllib3 from six.moves.urllib_parse import urljoin from six import iteritems from requests.exceptions import RequestException from ckanapi import RemoteCKAN from ckanapi.errors import CKANAPIError from .helpers import clean_str, title_to_name from .custom_exceptions import NonParseableCatalog and context (functions, classes, or occasionally code) from other files: # Path: pydatajson/helpers.py # def clean_str(s): # replacements = {"á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u", # ":": "", ".": ""} # for old, new in iteritems(replacements): # s = s.replace(old, new) # return s.lower().strip() # # def title_to_name(title, decode=True, max_len=None, use_complete_words=True): # """Convierte un título en un nombre normalizado para generar urls.""" # # decodifica y pasa a minúsculas # if decode: # title = unidecode(title) # title = title.lower() # # # remueve caracteres no permitidos # filtered_title = re.sub(r'[^a-z0-9- ]+', '', title) # # # remueve stop words y espacios y une palabras sólo con un "-" # normalized_title = '-'.join([word for word in filtered_title.split() # if word not in STOP_WORDS]) # # # recorto el titulo normalizado si excede la longitud máxima # if max_len and len(normalized_title) > max_len: # # # busco la última palabra completa # if use_complete_words: # last_word_index = normalized_title.rindex("-", 0, max_len) # normalized_title = normalized_title[:last_word_index] # # # corto en el último caracter # else: # normalized_title = normalized_title[:max_len] # # return normalized_title # # Path: pydatajson/custom_exceptions.py # class NonParseableCatalog(ValueError): # """No se puede leer un data.json a partir del parámetro pasado""" # def __init__(self, catalog, error): # msg = "Error parseando el datajson {}: {}".format(catalog, error) # super(NonParseableCatalog, self).__init__(msg) . Output only the next line.
completar catalog['publisher'['%s'].""",
Based on the snippet: <|code_start|> )) # tiempo de espera padra evitar baneos time.sleep(0.2) # itera leyendo todos los temas del portal groups = [portal.call_action( 'group_show', {'id': grp}, requests_kwargs={"verify": False}) for grp in groups_list] catalog = map_status_to_catalog(status) catalog["dataset"] = map_packages_to_datasets( packages, portal_url) catalog["themeTaxonomy"] = map_groups_to_themes(groups) except (CKANAPIError, RequestException) as e: logger.exception( 'Error al procesar el portal %s', portal_url, exc_info=True) raise NonParseableCatalog(portal_url, e) return catalog def map_status_to_catalog(status): """Convierte el resultado de action.status_show() en metadata a nivel de catálogo.""" catalog = dict() catalog_mapping = { <|code_end|> , predict the immediate next line with the help of imports: import os.path import logging import json import time import urllib3 from six.moves.urllib_parse import urljoin from six import iteritems from requests.exceptions import RequestException from ckanapi import RemoteCKAN from ckanapi.errors import CKANAPIError from .helpers import clean_str, title_to_name from .custom_exceptions import NonParseableCatalog and context (classes, functions, sometimes code) from other files: # Path: pydatajson/helpers.py # def clean_str(s): # replacements = {"á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u", # ":": "", ".": ""} # for old, new in iteritems(replacements): # s = s.replace(old, new) # return s.lower().strip() # # def title_to_name(title, decode=True, max_len=None, use_complete_words=True): # """Convierte un título en un nombre normalizado para generar urls.""" # # decodifica y pasa a minúsculas # if decode: # title = unidecode(title) # title = title.lower() # # # remueve caracteres no permitidos # filtered_title = re.sub(r'[^a-z0-9- ]+', '', title) # # # remueve stop words y espacios y une palabras sólo con un "-" # normalized_title = '-'.join([word for word in filtered_title.split() # if word not in STOP_WORDS]) # # # recorto el titulo normalizado si excede la longitud máxima # if max_len and len(normalized_title) > max_len: # # # busco la última palabra completa # if use_complete_words: # last_word_index = normalized_title.rindex("-", 0, max_len) # normalized_title = normalized_title[:last_word_index] # # # corto en el último caracter # else: # normalized_title = normalized_title[:max_len] # # return normalized_title # # Path: pydatajson/custom_exceptions.py # class NonParseableCatalog(ValueError): # """No se puede leer un data.json a partir del parámetro pasado""" # def __init__(self, catalog, error): # msg = "Error parseando el datajson {}: {}".format(catalog, error) # super(NonParseableCatalog, self).__init__(msg) . Output only the next line.
"site_title": "title",
Next line prediction: <|code_start|> for grp in groups_list] catalog = map_status_to_catalog(status) catalog["dataset"] = map_packages_to_datasets( packages, portal_url) catalog["themeTaxonomy"] = map_groups_to_themes(groups) except (CKANAPIError, RequestException) as e: logger.exception( 'Error al procesar el portal %s', portal_url, exc_info=True) raise NonParseableCatalog(portal_url, e) return catalog def map_status_to_catalog(status): """Convierte el resultado de action.status_show() en metadata a nivel de catálogo.""" catalog = dict() catalog_mapping = { "site_title": "title", "site_description": "description" } for status_key, catalog_key in iteritems(catalog_mapping): try: catalog[catalog_key] = status[status_key] except BaseException: logger.exception(""" <|code_end|> . Use current file imports: (import os.path import logging import json import time import urllib3 from six.moves.urllib_parse import urljoin from six import iteritems from requests.exceptions import RequestException from ckanapi import RemoteCKAN from ckanapi.errors import CKANAPIError from .helpers import clean_str, title_to_name from .custom_exceptions import NonParseableCatalog) and context including class names, function names, or small code snippets from other files: # Path: pydatajson/helpers.py # def clean_str(s): # replacements = {"á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u", # ":": "", ".": ""} # for old, new in iteritems(replacements): # s = s.replace(old, new) # return s.lower().strip() # # def title_to_name(title, decode=True, max_len=None, use_complete_words=True): # """Convierte un título en un nombre normalizado para generar urls.""" # # decodifica y pasa a minúsculas # if decode: # title = unidecode(title) # title = title.lower() # # # remueve caracteres no permitidos # filtered_title = re.sub(r'[^a-z0-9- ]+', '', title) # # # remueve stop words y espacios y une palabras sólo con un "-" # normalized_title = '-'.join([word for word in filtered_title.split() # if word not in STOP_WORDS]) # # # recorto el titulo normalizado si excede la longitud máxima # if max_len and len(normalized_title) > max_len: # # # busco la última palabra completa # if use_complete_words: # last_word_index = normalized_title.rindex("-", 0, max_len) # normalized_title = normalized_title[:last_word_index] # # # corto en el último caracter # else: # normalized_title = normalized_title[:max_len] # # return normalized_title # # Path: pydatajson/custom_exceptions.py # class NonParseableCatalog(ValueError): # """No se puede leer un data.json a partir del parámetro pasado""" # def __init__(self, catalog, error): # msg = "Error parseando el datajson {}: {}".format(catalog, error) # super(NonParseableCatalog, self).__init__(msg) . Output only the next line.
La clave '%s' no está en el endpoint de status. No se puede
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class ThreadingTests(TestCase): def test_threading(self): elements = [1, 2, 3, 4] def function(x): <|code_end|> , generate the next line using the imports in this file: from unittest import TestCase from pydatajson.threading_helper import apply_threading and context (functions, classes, or occasionally code) from other files: # Path: pydatajson/threading_helper.py # def apply_threading(l, function, cant_threads, **kwargs): # if cant_threads == 1: # return [function(x, **kwargs) for x in l] # pool = ThreadPool(processes=cant_threads) # results = pool.map(function, l) # pool.close() # pool.join() # return results . Output only the next line.
return x ** 2
Next line prediction: <|code_start|> }) def malformed_accrualperiodicity(): return dataset_error({ 'message': "%s is not valid under any of the given schemas" % jsonschema_str('RP1Y'), }) def malformed_temporal(): return dataset_error({ "instance": "2015-01-1/2015-12-31", "validator": "anyOf", "path": [ "dataset", 0, "temporal" ], "message": "%s is not valid under any of the given schemas" % jsonschema_str('2015-01-1/2015-12-31'), "error_code": 2, "validator_value": [ { "pattern": "^(\\d{4}-\\d\\d-\\d\\d(T\\d\\d:\\d\\d:\\d\\d(\\.\\d+)?)" "?(([+-]\\d\\d:\\d\\d)|Z)?)\\/(\\d{4}-\\d\\d-\\d\\" "d(T\\d\\d:\\d\\d:\\d\\d(\\.\\d+)?)" "?(([+-]\\d\\d:\\d\\d)|Z)?)$", "type": "string" <|code_end|> . Use current file imports: (from tests.support.utils import jsonschema_str) and context including class names, function names, or small code snippets from other files: # Path: tests/support/utils.py # def jsonschema_str(string): # return repr(string) . Output only the next line.
},
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- class DistributionDownloadUrlsValidator(UrlValidator): def validate(self): async_results = [] for dataset in self.catalog.get('dataset', []): distribution_urls = \ <|code_end|> , generate the next line using the imports in this file: from pydatajson import threading_helper from pydatajson.validators.url_validator import UrlValidator and context (functions, classes, or occasionally code) from other files: # Path: pydatajson/threading_helper.py # def apply_threading(l, function, cant_threads, **kwargs): # # Path: pydatajson/validators/url_validator.py # class UrlValidator(SimpleValidator): # # def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count): # super(UrlValidator, self).__init__(catalog) # self.verify_ssl = verify_ssl # self.url_check_timeout = url_check_timeout # self.threads_count = threads_count # # def validate(self): # raise NotImplementedError # # def is_working_url(self, url): # try: # response = requests.head(url, # timeout=self.url_check_timeout, # verify=self.verify_ssl) # matches = [] # if response.status_code not in EXCEPTION_STATUS_CODES: # matches = \ # [re.match(pattern, str(response.status_code)) is not None # for pattern in INVALID_STATUS_CODES_REGEX] # return True not in matches, response.status_code # except Timeout: # return False, 408 # except (RequestException, Exception): # return False, None . Output only the next line.
[distribution.get('downloadURL', '')
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- class DistributionDownloadUrlsValidator(UrlValidator): def validate(self): async_results = [] for dataset in self.catalog.get('dataset', []): distribution_urls = \ [distribution.get('downloadURL', '') for distribution in dataset.get('distribution', [])] async_results += threading_helper \ .apply_threading(distribution_urls, self.is_working_url, self.threads_count) <|code_end|> , continue by predicting the next line. Consider current file imports: from pydatajson import threading_helper from pydatajson.validators.url_validator import UrlValidator and context: # Path: pydatajson/threading_helper.py # def apply_threading(l, function, cant_threads, **kwargs): # # Path: pydatajson/validators/url_validator.py # class UrlValidator(SimpleValidator): # # def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count): # super(UrlValidator, self).__init__(catalog) # self.verify_ssl = verify_ssl # self.url_check_timeout = url_check_timeout # self.threads_count = threads_count # # def validate(self): # raise NotImplementedError # # def is_working_url(self, url): # try: # response = requests.head(url, # timeout=self.url_check_timeout, # verify=self.verify_ssl) # matches = [] # if response.status_code not in EXCEPTION_STATUS_CODES: # matches = \ # [re.match(pattern, str(response.status_code)) is not None # for pattern in INVALID_STATUS_CODES_REGEX] # return True not in matches, response.status_code # except Timeout: # return False, 408 # except (RequestException, Exception): # return False, None which might include code, classes, or functions. Output only the next line.
result = 0
Using the snippet: <|code_start|> catalog = os.path.join(self.SAMPLES_DIR, "full_data.json") self.dj.generate_datasets_report(catalog, export_path="una ruta") pydatajson.writers.write_table.assert_called_once() def test_generate_harvester_config_freq_none(self): """generate_harvester_config() debe filtrar el resultado de generate_datasets_report() a únicamente los 3 campos requeridos, y conservar el accrualPeriodicity original.""" datasets_report = [ { "catalog_metadata_url": 1, "dataset_identifier": 1, "dataset_accrualPeriodicity": 1, "otra key": 1, "catalog_federation_org": "organizacion-en-ckan", "catalog_federation_id": "organismo", "harvest": 0 }, { "catalog_metadata_url": 2, "dataset_identifier": 2, "dataset_accrualPeriodicity": 2, "otra key": 2, "catalog_federation_org": "organizacion-en-ckan", "catalog_federation_id": "organismo", "harvest": 1 <|code_end|> , determine the next line of code. You have imports: import os.path import nose import requests_mock import vcr import mock from collections import OrderedDict from pprint import pprint from nose.tools import assert_false, assert_equal from nose.tools import assert_list_equal, assert_raises from six import iteritems from unittest import mock from .context import pydatajson from .support.decorators import load_expected_result, RESULTS_DIR and context (class names, function names, or code) available: # Path: tests/context.py # # Path: tests/support/decorators.py # def load_expected_result(): # def case_decorator(test): # case_filename = test.__name__.split("test_")[-1] # # @wraps(test) # def decorated_test(*args, **kwargs): # result_path = os.path.join(RESULTS_DIR, case_filename + ".json") # # with io.open(result_path, encoding='utf8') as result_file: # expected_result = json.load(result_file) # # kwargs["expected_result"] = expected_result # test(*args, **kwargs) # # return decorated_test # # return case_decorator # # RESULTS_DIR = os.path.join("tests", "results") . Output only the next line.
},
Given snippet: <|code_start|> "dataset_accrualPeriodicity": "eventual", "harvest": 1 }, { "catalog_metadata_url": "URL Catalogo B", "dataset_title": "Dataset Invalido", "dataset_accrualPeriodicity": "eventual", "harvest": 0 } ] @mock.patch('pydatajson.DataJson.generate_datasets_report', return_value=REPORT) @mock.patch('pydatajson.readers.read_catalog', return_value=CATALOG.copy()) def test_generate_harvestable_catalogs_valid(self, mock_read_catalog, mock_gen_dsets_report): catalogs = ["URL Catalogo A", "URL Catalogo B"] expected_catalog = { "title": "Micro Catalogo", "dataset": [ { "title": "Dataset Valido", "description": "Descripción valida", "distribution": [] } ] } <|code_end|> , continue by predicting the next line. Consider current file imports: import os.path import nose import requests_mock import vcr import mock from collections import OrderedDict from pprint import pprint from nose.tools import assert_false, assert_equal from nose.tools import assert_list_equal, assert_raises from six import iteritems from unittest import mock from .context import pydatajson from .support.decorators import load_expected_result, RESULTS_DIR and context: # Path: tests/context.py # # Path: tests/support/decorators.py # def load_expected_result(): # def case_decorator(test): # case_filename = test.__name__.split("test_")[-1] # # @wraps(test) # def decorated_test(*args, **kwargs): # result_path = os.path.join(RESULTS_DIR, case_filename + ".json") # # with io.open(result_path, encoding='utf8') as result_file: # expected_result = json.load(result_file) # # kwargs["expected_result"] = expected_result # test(*args, **kwargs) # # return decorated_test # # return case_decorator # # RESULTS_DIR = os.path.join("tests", "results") which might include code, classes, or functions. Output only the next line.
expected = [expected_catalog, expected_catalog]
Based on the snippet: <|code_start|> "dataset_organization": "organizacion-en-ckan", "catalog_id": "organismo", } ] self.dj.generate_datasets_report = mock.MagicMock( return_value=datasets_report) actual_config = self.dj.generate_harvester_config( catalogs="un catalogo", harvest='valid') assert_list_equal(actual_config, expected_config) # TESTS DE GENERATE_HARVESTABLE_CATALOGS CATALOG = { "title": "Micro Catalogo", "dataset": [ { "title": "Dataset Valido", "description": "Descripción valida", "distribution": [] }, { "title": "Dataset Invalido" } ] } @mock.patch('pydatajson.readers.read_catalog', <|code_end|> , predict the immediate next line with the help of imports: import os.path import nose import requests_mock import vcr import mock from collections import OrderedDict from pprint import pprint from nose.tools import assert_false, assert_equal from nose.tools import assert_list_equal, assert_raises from six import iteritems from unittest import mock from .context import pydatajson from .support.decorators import load_expected_result, RESULTS_DIR and context (classes, functions, sometimes code) from other files: # Path: tests/context.py # # Path: tests/support/decorators.py # def load_expected_result(): # def case_decorator(test): # case_filename = test.__name__.split("test_")[-1] # # @wraps(test) # def decorated_test(*args, **kwargs): # result_path = os.path.join(RESULTS_DIR, case_filename + ".json") # # with io.open(result_path, encoding='utf8') as result_file: # expected_result = json.load(result_file) # # kwargs["expected_result"] = expected_result # test(*args, **kwargs) # # return decorated_test # # return case_decorator # # RESULTS_DIR = os.path.join("tests", "results") . Output only the next line.
return_value=CATALOG.copy())
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- try: except ImportError: EXTENSIONS_EXCEPTIONS = ["zip", "php", "asp", "aspx"] class ConsistentDistributionFieldsValidator(SimpleValidator): def validate(self): for dataset_idx, dataset in enumerate(self.catalog["dataset"]): for distribution_idx, distribution in enumerate( dataset["distribution"]): for attribute in ['downloadURL', 'fileName']: if not self._format_matches_extension(distribution, attribute): yield ce.ExtensionError(dataset_idx, distribution_idx, distribution, attribute) <|code_end|> . Use current file imports: import mimetypes import os import pydatajson.custom_exceptions as ce from urlparse import urlparse from urllib.parse import urlparse from pydatajson.validators.simple_validator import SimpleValidator and context (classes, functions, or code) from other files: # Path: pydatajson/validators/simple_validator.py # class SimpleValidator(object): # # def __init__(self, catalog): # self.catalog = catalog # # def validate(self): # raise NotImplementedError . Output only the next line.
@staticmethod
Here is a snippet: <|code_start|> for value in valid_values: datajson["dataset"][0]["accrualPeriodicity"] = value res = self.dj.is_valid_catalog(datajson) assert_true(res, msg=value) invalid_values = ['RP10Y', 'R/PY', 'R/P3', 'RR/P2Y', 'R/PnY', 'R/P6MT', 'R/PT', 'R/T1M', 'R/P0.M', '/P0.33M', 'R/P1Week', 'R/P.5W', 'R/P', 'R/T', 'R/PT1H3M', 'eventual ', ''] for value in invalid_values: datajson["dataset"][0]["accrualPeriodicity"] = value res = self.dj.is_valid_catalog(datajson) assert_false(res, msg=value) def test_valid_catalog_list_format(self): report_list = self.dj.validate_catalog(fmt='list') assert_true(len(report_list['catalog']) == 1) assert_true(report_list['catalog'][0]['catalog_status'] == 'OK') assert_true(len(report_list['dataset']) == 2) for report in report_list['dataset']: assert_true(report['dataset_status'] == 'OK') def test_invalid_catalog_list_format(self): catalog = pydatajson.DataJson( self.get_sample("several_assorted_errors.json")) report_list = catalog.validate_catalog(fmt='list') report_dict = catalog.validate_catalog() for error in report_dict['error']['catalog']['errors']: <|code_end|> . Write the next line using the current file imports: import json import os.path import re import requests_mock import vcr import mock import io from nose.tools import assert_true, assert_false, assert_dict_equal, \ assert_regexp_matches from six import iteritems, text_type from tests.support.factories.core_files import TEST_FILE_RESPONSES from .support.constants import BAD_DATAJSON_URL, BAD_DATAJSON_URL2 from .support.utils import jsonschema_str from unittest import mock from .context import pydatajson from .support.decorators import RESULTS_DIR and context from other files: # Path: tests/support/factories/core_files.py # TEST_FILE_RESPONSES = {} # # Path: tests/support/constants.py # BAD_DATAJSON_URL = "http://104.131.35.253/data.json" # # BAD_DATAJSON_URL2 = "http://181.209.63.71/data.json" # # Path: tests/support/utils.py # def jsonschema_str(string): # return repr(string) # # Path: tests/context.py # # Path: tests/support/decorators.py # RESULTS_DIR = os.path.join("tests", "results") , which may include functions, classes, or code. Output only the next line.
assert_true(
Based on the snippet: <|code_start|> def setUp(self): self.dj = pydatajson.DataJson(self.get_sample("full_data.json")) self.catalog = pydatajson.readers.read_catalog( self.get_sample("full_data.json")) self.maxDiff = None self.longMessage = True self.requests_mock = requests_mock.Mocker() self.requests_mock.start() self.requests_mock.get(requests_mock.ANY, real_http=True) self.requests_mock.head(requests_mock.ANY, status_code=200) def tearDown(self): del self.dj self.requests_mock.stop() def run_case(self, case_filename, expected_dict=None): sample_path = os.path.join(self.SAMPLES_DIR, case_filename + ".json") result_path = os.path.join(self.RESULTS_DIR, case_filename + ".json") if expected_dict is None: with io.open(result_path, encoding='utf8') as result_file: expected_dict = json.load(result_file) response_bool = self.dj.is_valid_catalog(sample_path) response_dict = self.dj.validate_catalog(sample_path) print(text_type(json.dumps( response_dict, indent=4, separators=(",", ": "), <|code_end|> , predict the immediate next line with the help of imports: import json import os.path import re import requests_mock import vcr import mock import io from nose.tools import assert_true, assert_false, assert_dict_equal, \ assert_regexp_matches from six import iteritems, text_type from tests.support.factories.core_files import TEST_FILE_RESPONSES from .support.constants import BAD_DATAJSON_URL, BAD_DATAJSON_URL2 from .support.utils import jsonschema_str from unittest import mock from .context import pydatajson from .support.decorators import RESULTS_DIR and context (classes, functions, sometimes code) from other files: # Path: tests/support/factories/core_files.py # TEST_FILE_RESPONSES = {} # # Path: tests/support/constants.py # BAD_DATAJSON_URL = "http://104.131.35.253/data.json" # # BAD_DATAJSON_URL2 = "http://181.209.63.71/data.json" # # Path: tests/support/utils.py # def jsonschema_str(string): # return repr(string) # # Path: tests/context.py # # Path: tests/support/decorators.py # RESULTS_DIR = os.path.join("tests", "results") . Output only the next line.
ensure_ascii=False
Given the following code snippet before the placeholder: <|code_start|> errors = [( ['error', 'catalog', 'errors', ], "%s is too short" % jsonschema_str('') )] for path, regex in errors: with my_vcr.use_cassette('test_validate_bad_remote_datajson'): yield self.validate_contains_message, BAD_DATAJSON_URL,\ path, regex # Tests contra una URL REMOTA @my_vcr.use_cassette('test_validate_bad_remote_datajson2') def test_validate_invalid_remote_datajson_is_invalid2(self): """ Testea `is_valid_catalog` contra un data.json remoto invalido.""" res = self.dj.is_valid_catalog(BAD_DATAJSON_URL2) assert_false(res) def test_validate_invalid_remote_datajson_has_errors2(self): """ Testea `validate_catalog` contra un data.json remoto invalido.""" errors = [(['error', 'catalog', 'errors', ], "%s is too short" % jsonschema_str(''))] for path, regex in errors: with my_vcr.use_cassette('test_validate_bad_remote_datajson2'): yield self.validate_contains_message, BAD_DATAJSON_URL2,\ path, regex def test_correctness_of_accrualPeriodicity_regex(self): """Prueba que la regex de validación de dataset["accrualPeriodicity"] sea correcta.""" <|code_end|> , predict the next line using imports from the current file: import json import os.path import re import requests_mock import vcr import mock import io from nose.tools import assert_true, assert_false, assert_dict_equal, \ assert_regexp_matches from six import iteritems, text_type from tests.support.factories.core_files import TEST_FILE_RESPONSES from .support.constants import BAD_DATAJSON_URL, BAD_DATAJSON_URL2 from .support.utils import jsonschema_str from unittest import mock from .context import pydatajson from .support.decorators import RESULTS_DIR and context including class names, function names, and sometimes code from other files: # Path: tests/support/factories/core_files.py # TEST_FILE_RESPONSES = {} # # Path: tests/support/constants.py # BAD_DATAJSON_URL = "http://104.131.35.253/data.json" # # BAD_DATAJSON_URL2 = "http://181.209.63.71/data.json" # # Path: tests/support/utils.py # def jsonschema_str(string): # return repr(string) # # Path: tests/context.py # # Path: tests/support/decorators.py # RESULTS_DIR = os.path.join("tests", "results") . Output only the next line.
datajson_path = "tests/samples/full_data.json"