Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Using the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import division class BroadcastDetailView(DetailView): model = Broadcast slug_field = 'number' class BroadcastListView(ListView): model = Broadcast def calculate_highlights_per_episode(self, **kwargs): episodes = Broadcast.objects.count() <|code_end|> , determine the next line of code. You have imports: from django.shortcuts import render from django.views.generic import ListView, DetailView, TemplateView from apps.games.models import Game from .models import Broadcast, Highlight, Raid and context (class names, function names, or code) available: # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) . Output only the next line.
highlights = Highlight.objects.count()
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import division class BroadcastDetailView(DetailView): model = Broadcast slug_field = 'number' class BroadcastListView(ListView): model = Broadcast def calculate_highlights_per_episode(self, **kwargs): episodes = Broadcast.objects.count() highlights = Highlight.objects.count() return round((highlights / episodes), 2) def calculate_raids_per_episode(self, **kwargs): # Subtract 50 from the total number of episodes, since we only started # recording raids at episode 51. episodes = Broadcast.objects.count() - 50 <|code_end|> . Write the next line using the current file imports: from django.shortcuts import render from django.views.generic import ListView, DetailView, TemplateView from apps.games.models import Game from .models import Broadcast, Highlight, Raid and context from other files: # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) , which may include functions, classes, or code. Output only the next line.
raids = Raid.objects.count()
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class Quote(models.Model): text = models.TextField() timestamp = models.DateField(default=timezone.now) subject = models.CharField(blank=True, max_length=200, help_text='The person that was quoted.') creator = models.CharField(blank=True, max_length=200, help_text='The person that created the quote.') <|code_end|> , determine the next line of code. You have imports: from django.db import models from django.utils import timezone from apps.broadcasts.models import Broadcast from apps.games.models import Game and context (class names, function names, or code) available: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='quotes')
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- class Quote(models.Model): text = models.TextField() timestamp = models.DateField(default=timezone.now) subject = models.CharField(blank=True, max_length=200, help_text='The person that was quoted.') creator = models.CharField(blank=True, max_length=200, help_text='The person that created the quote.') broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='quotes') <|code_end|> , predict the immediate next line with the help of imports: from django.db import models from django.utils import timezone from apps.broadcasts.models import Broadcast from apps.games.models import Game and context (classes, functions, sometimes code) from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
game = models.ForeignKey(Game, blank=True, null=True, related_name='quoted_on')
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class GameAdmin(admin.ModelAdmin): list_display = ['name', 'platform', 'is_abandoned', 'is_completed'] list_editable = ['is_abandoned', 'is_completed'] ordering = ['name'] raw_id_fields = ['platform'] autocomplete_lookup_fields = { 'fk': ['platform'] } <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from .models import Game, Platform and context (class names, function names, or code) available: # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') # # class Platform(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
admin.site.register(Game, GameAdmin)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class GameAdmin(admin.ModelAdmin): list_display = ['name', 'platform', 'is_abandoned', 'is_completed'] list_editable = ['is_abandoned', 'is_completed'] ordering = ['name'] raw_id_fields = ['platform'] autocomplete_lookup_fields = { 'fk': ['platform'] } admin.site.register(Game, GameAdmin) class PlatformAdmin(admin.ModelAdmin): pass <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from .models import Game, Platform and context including class names, function names, and sometimes code from other files: # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') # # class Platform(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
admin.site.register(Platform, PlatformAdmin)
Given the following code snippet before the placeholder: <|code_start|> class HighlightInline(admin.StackedInline): extra = 1 model = Highlight class HostInline(admin.TabularInline): extra = 1 model = Host class RaidInline(admin.TabularInline): extra = 1 model = Raid class BroadcastAdmin(admin.ModelAdmin): inlines = [RaidInline, HostInline, HighlightInline] list_display = ['number', 'airdate', 'status', 'series', 'game_list'] list_display_links = ['number'] raw_id_fields = ['games', 'series'] autocomplete_lookup_fields = { 'fk': ['series'], 'm2m': ['games'] } def game_list(self, obj): return ", ".join([g.name for g in obj.games.all()]) <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from .models import Broadcast, Highlight, Host, Raid, Series and context including class names, function names, and sometimes code from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
admin.site.register(Broadcast, BroadcastAdmin)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class HighlightInline(admin.StackedInline): extra = 1 model = Highlight class HostInline(admin.TabularInline): extra = 1 <|code_end|> . Write the next line using the current file imports: from django.contrib import admin from .models import Broadcast, Highlight, Host, Raid, Series and context from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') , which may include functions, classes, or code. Output only the next line.
model = Host
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class HighlightInline(admin.StackedInline): extra = 1 model = Highlight class HostInline(admin.TabularInline): extra = 1 model = Host class RaidInline(admin.TabularInline): extra = 1 <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from .models import Broadcast, Highlight, Host, Raid, Series and context including class names, function names, and sometimes code from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
model = Raid
Predict the next line for this snippet: <|code_start|> def game_list(self, obj): return ", ".join([g.name for g in obj.games.all()]) admin.site.register(Broadcast, BroadcastAdmin) class HighlightAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': (('broadcast', 'twid'),)}), ('Details', {'fields': ('title', 'description', 'game', 'url')}) ) list_display = ['title', 'broadcast', 'game', 'twid', 'url'] list_display_links = ['title', 'broadcast'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Highlight, HighlightAdmin) class HostAdmin(admin.ModelAdmin): list_display = ['timestamp', 'username', 'broadcast'] admin.site.register(Host, HostAdmin) class RaidAdmin(admin.ModelAdmin): list_display = ['timestamp', 'broadcast', 'username', 'game'] admin.site.register(Raid, RaidAdmin) class SeriesAdmin(admin.ModelAdmin): pass <|code_end|> with the help of current file imports: from django.contrib import admin from .models import Broadcast, Highlight, Host, Raid, Series and context from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') , which may contain function names, class names, or code. Output only the next line.
admin.site.register(Series, SeriesAdmin)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_game_factory(): factory = GameFactory() assert isinstance(factory, Game) def test_platform_factory(): <|code_end|> , generate the next line using the imports in this file: import pytest from .factories import GameFactory, PlatformFactory from ..models import Game, Platform and context (functions, classes, or occasionally code) from other files: # Path: apps/games/tests/factories.py # class GameFactory(factory.django.DjangoModelFactory): # class Meta: # model = Game # # platform = factory.SubFactory(PlatformFactory) # # class PlatformFactory(factory.django.DjangoModelFactory): # class Meta: # model = Platform # # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') # # class Platform(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
factory = PlatformFactory()
Given snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_game_factory(): factory = GameFactory() <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from .factories import GameFactory, PlatformFactory from ..models import Game, Platform and context: # Path: apps/games/tests/factories.py # class GameFactory(factory.django.DjangoModelFactory): # class Meta: # model = Game # # platform = factory.SubFactory(PlatformFactory) # # class PlatformFactory(factory.django.DjangoModelFactory): # class Meta: # model = Platform # # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') # # class Platform(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') which might include code, classes, or functions. Output only the next line.
assert isinstance(factory, Game)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_game_factory(): factory = GameFactory() assert isinstance(factory, Game) def test_platform_factory(): factory = PlatformFactory() <|code_end|> , generate the next line using the imports in this file: import pytest from .factories import GameFactory, PlatformFactory from ..models import Game, Platform and context (functions, classes, or occasionally code) from other files: # Path: apps/games/tests/factories.py # class GameFactory(factory.django.DjangoModelFactory): # class Meta: # model = Game # # platform = factory.SubFactory(PlatformFactory) # # class PlatformFactory(factory.django.DjangoModelFactory): # class Meta: # model = Platform # # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') # # class Platform(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
assert isinstance(factory, Platform)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- class StatusView(JSONResponseMixin, View): def get(self, request, *args, **kwargs): broadcast = Broadcast.objects.latest() context = { 'is_episodic': is_episodic(), <|code_end|> with the help of current file imports: from django.views.generic import View from braces.views import JSONResponseMixin from apps.broadcasts.models import Broadcast from .utils import fetch_stream, is_episodic and context from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # Path: apps/live/utils.py # def fetch_stream(): # endpoint = 'https://api.twitch.tv/kraken/streams/avalonstar' # json = requests.get(endpoint).json() # return json.get('stream', {}) # # def is_episodic(): # # Let's use the stream's title to determine if a stream is an episode # # or not. We use the stream's status to determine this as follows: # # # # - "A☆###": A numbered episode. # # - (Anything else.): A casual episode. # # # # Because Python is weird, it doesn't detect the white star. We're not # # going to bother looking for it. # pattern = r'^A.\d{3}' # status = fetch_status() # return bool(re.match(pattern, status, re.UNICODE)) , which may contain function names, class names, or code. Output only the next line.
'is_live': bool(fetch_stream()),
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- class StatusView(JSONResponseMixin, View): def get(self, request, *args, **kwargs): broadcast = Broadcast.objects.latest() context = { <|code_end|> , predict the immediate next line with the help of imports: from django.views.generic import View from braces.views import JSONResponseMixin from apps.broadcasts.models import Broadcast from .utils import fetch_stream, is_episodic and context (classes, functions, sometimes code) from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # Path: apps/live/utils.py # def fetch_stream(): # endpoint = 'https://api.twitch.tv/kraken/streams/avalonstar' # json = requests.get(endpoint).json() # return json.get('stream', {}) # # def is_episodic(): # # Let's use the stream's title to determine if a stream is an episode # # or not. We use the stream's status to determine this as follows: # # # # - "A☆###": A numbered episode. # # - (Anything else.): A casual episode. # # # # Because Python is weird, it doesn't detect the white star. We're not # # going to bother looking for it. # pattern = r'^A.\d{3}' # status = fetch_status() # return bool(re.match(pattern, status, re.UNICODE)) . Output only the next line.
'is_episodic': is_episodic(),
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class PlatformFactory(factory.django.DjangoModelFactory): class Meta: model = Platform class GameFactory(factory.django.DjangoModelFactory): class Meta: <|code_end|> , determine the next line of code. You have imports: import factory from ..models import Game, Platform and context (class names, function names, or code) available: # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') # # class Platform(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
model = Game
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_ticket_factory(): factory = TicketFactory() <|code_end|> , predict the next line using imports from the current file: import pytest from .factories import TicketFactory from ..models import Ticket and context including class names, function names, and sometimes code from other files: # Path: apps/subscribers/tests/factories.py # class TicketFactory(factory.django.DjangoModelFactory): # class Meta: # model = Ticket # # Path: apps/subscribers/models.py # class Ticket(models.Model): # twid = models.CharField(blank=True, max_length=40) # name = models.CharField(max_length=200) # display_name = models.CharField(blank=True, max_length=200) # created = models.DateTimeField(default=timezone.now) # updated = models.DateTimeField(default=timezone.now) # # # Store the months if there's a substreak (defaults to 1 month). # streak = models.IntegerField(default=1) # # # Is this subscription active? # is_active = models.BooleanField(default=True, # help_text='Is this subscription active?') # is_paid = models.BooleanField(default=True, # help_text='Is this a paid subscription? (e.g., Not a bot.)') # # # Custom manager. # objects = TicketManager() # # class Meta: # ordering = ['updated'] # get_latest_by = 'updated' # # def __str__(self): # return '{}'.format(self.name) # # def update(self, **kwargs): # allowed_attributes = {'twid', 'display_name', 'updated', 'is_active'} # for name, value in kwargs.items(): # assert name in allowed_attributes # setattr(self, name, value) # self.save() . Output only the next line.
assert isinstance(factory, Ticket)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db class TestBroadcasts: def test_factory(self): <|code_end|> , predict the next line using imports from the current file: import pytest from .factories import (BroadcastFactory) from ..models import Broadcast and context including class names, function names, and sometimes code from other files: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) . Output only the next line.
factory = BroadcastFactory()
Given snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db class TestBroadcasts: def test_factory(self): factory = BroadcastFactory() <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from .factories import (BroadcastFactory) from ..models import Broadcast and context: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) which might include code, classes, or functions. Output only the next line.
assert isinstance(factory, Broadcast)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_broadcast_factory(): factory = BroadcastFactory() assert isinstance(factory, Broadcast) def test_host_factory(): <|code_end|> , determine the next line of code. You have imports: import pytest from .factories import (BroadcastFactory, HighlightFactory, HostFactory, RaidFactory, SeriesFactory) from ..models import Broadcast, Highlight, Host, Raid, Series and context (class names, function names, or code) available: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # class HighlightFactory(factory.django.DjangoModelFactory): # class Meta: # model = Highlight # # broadcast = factory.SubFactory(BroadcastFactory) # twid = 'c4136304' # # class HostFactory(factory.django.DjangoModelFactory): # class Meta: # model = Host # # broadcast = factory.SubFactory(BroadcastFactory) # # class RaidFactory(factory.django.DjangoModelFactory): # class Meta: # model = Raid # # broadcast = factory.SubFactory(BroadcastFactory) # # class SeriesFactory(factory.django.DjangoModelFactory): # class Meta: # model = Series # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
factory = HostFactory()
Given snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_broadcast_factory(): factory = BroadcastFactory() assert isinstance(factory, Broadcast) def test_host_factory(): factory = HostFactory() assert isinstance(factory, Host) def test_raid_factory(): <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from .factories import (BroadcastFactory, HighlightFactory, HostFactory, RaidFactory, SeriesFactory) from ..models import Broadcast, Highlight, Host, Raid, Series and context: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # class HighlightFactory(factory.django.DjangoModelFactory): # class Meta: # model = Highlight # # broadcast = factory.SubFactory(BroadcastFactory) # twid = 'c4136304' # # class HostFactory(factory.django.DjangoModelFactory): # class Meta: # model = Host # # broadcast = factory.SubFactory(BroadcastFactory) # # class RaidFactory(factory.django.DjangoModelFactory): # class Meta: # model = Raid # # broadcast = factory.SubFactory(BroadcastFactory) # # class SeriesFactory(factory.django.DjangoModelFactory): # class Meta: # model = Series # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') which might include code, classes, or functions. Output only the next line.
factory = RaidFactory()
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_broadcast_factory(): factory = BroadcastFactory() assert isinstance(factory, Broadcast) def test_host_factory(): factory = HostFactory() assert isinstance(factory, Host) def test_raid_factory(): factory = RaidFactory() assert isinstance(factory, Raid) def test_series_factory(): <|code_end|> , predict the next line using imports from the current file: import pytest from .factories import (BroadcastFactory, HighlightFactory, HostFactory, RaidFactory, SeriesFactory) from ..models import Broadcast, Highlight, Host, Raid, Series and context including class names, function names, and sometimes code from other files: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # class HighlightFactory(factory.django.DjangoModelFactory): # class Meta: # model = Highlight # # broadcast = factory.SubFactory(BroadcastFactory) # twid = 'c4136304' # # class HostFactory(factory.django.DjangoModelFactory): # class Meta: # model = Host # # broadcast = factory.SubFactory(BroadcastFactory) # # class RaidFactory(factory.django.DjangoModelFactory): # class Meta: # model = Raid # # broadcast = factory.SubFactory(BroadcastFactory) # # class SeriesFactory(factory.django.DjangoModelFactory): # class Meta: # model = Series # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
factory = SeriesFactory()
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_broadcast_factory(): factory = BroadcastFactory() <|code_end|> , predict the next line using imports from the current file: import pytest from .factories import (BroadcastFactory, HighlightFactory, HostFactory, RaidFactory, SeriesFactory) from ..models import Broadcast, Highlight, Host, Raid, Series and context including class names, function names, and sometimes code from other files: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # class HighlightFactory(factory.django.DjangoModelFactory): # class Meta: # model = Highlight # # broadcast = factory.SubFactory(BroadcastFactory) # twid = 'c4136304' # # class HostFactory(factory.django.DjangoModelFactory): # class Meta: # model = Host # # broadcast = factory.SubFactory(BroadcastFactory) # # class RaidFactory(factory.django.DjangoModelFactory): # class Meta: # model = Raid # # broadcast = factory.SubFactory(BroadcastFactory) # # class SeriesFactory(factory.django.DjangoModelFactory): # class Meta: # model = Series # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
assert isinstance(factory, Broadcast)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_broadcast_factory(): factory = BroadcastFactory() assert isinstance(factory, Broadcast) def test_host_factory(): factory = HostFactory() <|code_end|> with the help of current file imports: import pytest from .factories import (BroadcastFactory, HighlightFactory, HostFactory, RaidFactory, SeriesFactory) from ..models import Broadcast, Highlight, Host, Raid, Series and context from other files: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # class HighlightFactory(factory.django.DjangoModelFactory): # class Meta: # model = Highlight # # broadcast = factory.SubFactory(BroadcastFactory) # twid = 'c4136304' # # class HostFactory(factory.django.DjangoModelFactory): # class Meta: # model = Host # # broadcast = factory.SubFactory(BroadcastFactory) # # class RaidFactory(factory.django.DjangoModelFactory): # class Meta: # model = Raid # # broadcast = factory.SubFactory(BroadcastFactory) # # class SeriesFactory(factory.django.DjangoModelFactory): # class Meta: # model = Series # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') , which may contain function names, class names, or code. Output only the next line.
assert isinstance(factory, Host)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_broadcast_factory(): factory = BroadcastFactory() assert isinstance(factory, Broadcast) def test_host_factory(): factory = HostFactory() assert isinstance(factory, Host) def test_raid_factory(): factory = RaidFactory() <|code_end|> with the help of current file imports: import pytest from .factories import (BroadcastFactory, HighlightFactory, HostFactory, RaidFactory, SeriesFactory) from ..models import Broadcast, Highlight, Host, Raid, Series and context from other files: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # class HighlightFactory(factory.django.DjangoModelFactory): # class Meta: # model = Highlight # # broadcast = factory.SubFactory(BroadcastFactory) # twid = 'c4136304' # # class HostFactory(factory.django.DjangoModelFactory): # class Meta: # model = Host # # broadcast = factory.SubFactory(BroadcastFactory) # # class RaidFactory(factory.django.DjangoModelFactory): # class Meta: # model = Raid # # broadcast = factory.SubFactory(BroadcastFactory) # # class SeriesFactory(factory.django.DjangoModelFactory): # class Meta: # model = Series # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') , which may contain function names, class names, or code. Output only the next line.
assert isinstance(factory, Raid)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_broadcast_factory(): factory = BroadcastFactory() assert isinstance(factory, Broadcast) def test_host_factory(): factory = HostFactory() assert isinstance(factory, Host) def test_raid_factory(): factory = RaidFactory() assert isinstance(factory, Raid) def test_series_factory(): factory = SeriesFactory() <|code_end|> . Use current file imports: import pytest from .factories import (BroadcastFactory, HighlightFactory, HostFactory, RaidFactory, SeriesFactory) from ..models import Broadcast, Highlight, Host, Raid, Series and context (classes, functions, or code) from other files: # Path: apps/broadcasts/tests/factories.py # class BroadcastFactory(factory.django.DjangoModelFactory): # class Meta: # model = Broadcast # # class HighlightFactory(factory.django.DjangoModelFactory): # class Meta: # model = Highlight # # broadcast = factory.SubFactory(BroadcastFactory) # twid = 'c4136304' # # class HostFactory(factory.django.DjangoModelFactory): # class Meta: # model = Host # # broadcast = factory.SubFactory(BroadcastFactory) # # class RaidFactory(factory.django.DjangoModelFactory): # class Meta: # model = Raid # # broadcast = factory.SubFactory(BroadcastFactory) # # class SeriesFactory(factory.django.DjangoModelFactory): # class Meta: # model = Series # # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
assert isinstance(factory, Series)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- class Command(NoArgsCommand): help = 'Counts and saves the total number of subscriptions for the current day.' def handle_noargs(self, **options): <|code_end|> . Use current file imports: from django.core.management.base import NoArgsCommand from apps.subscribers.models import Count and context (classes, functions, or code) from other files: # Path: apps/subscribers/models.py # class Count(models.Model): # active = models.IntegerField() # total = models.IntegerField() # timestamp = models.DateTimeField(default=timezone.now) # # # Custom manager. # objects = CountManager() # # class Meta: # get_latest_by = 'timestamp' # ordering = ['timestamp'] # # def __str__(self): # return '{}/{} on {}'.format(self.active, self.total, self.timestamp) . Output only the next line.
count = Count.objects.create_count()
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- urlpatterns = [ # Temporary redirect to Twitch channel. url(r'^$', name='site-home', view=RedirectView.as_view(url='http://twitch.tv/avalonstar', permanent=False)), # Core Modules. url(r'^', include('apps.broadcasts.urls')), url(r'^', include('apps.games.urls')), url(r'^api/', include('apps.api.urls', namespace='api')), url(r'^live/', include('apps.live.urls', namespace='live')), # Administration Modules. url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', include(admin.site.urls)), # Sitemaps, Favicons, Robots, and Humans. url(r'^favicon.ico$', name='favicon', view=RedirectView.as_view(url=settings.STATIC_URL + 'images/favicon.ico', permanent=True)), <|code_end|> , generate the next line using the imports in this file: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import RedirectView from apps.views import PlainTextView and context (functions, classes, or occasionally code) from other files: # Path: apps/views.py # class PlainTextView(TemplateView): # def render_to_response(self, context, **kwargs): # return super().render_to_response(context, content_type='text/plain', **kwargs) . Output only the next line.
url(r'^robots.txt$', name='robots', view=PlainTextView.as_view(template_name='robots.txt'))
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context from other files: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) , which may include functions, classes, or code. Output only the next line.
router.register(r'hosts', HostViewSet)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) router.register(r'platforms', PlatformViewSet) router.register(r'quotes', QuoteViewSet) <|code_end|> with the help of current file imports: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context from other files: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) , which may contain function names, class names, or code. Output only the next line.
router.register(r'raids', RaidViewSet)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context from other files: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) , which may include functions, classes, or code. Output only the next line.
router.register(r'platforms', PlatformViewSet)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) router.register(r'platforms', PlatformViewSet) <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context from other files: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) , which may include functions, classes, or code. Output only the next line.
router.register(r'quotes', QuoteViewSet)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) router.register(r'platforms', PlatformViewSet) router.register(r'quotes', QuoteViewSet) router.register(r'raids', RaidViewSet) <|code_end|> , generate the next line using the imports in this file: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context (functions, classes, or occasionally code) from other files: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) . Output only the next line.
router.register(r'tickets', TicketViewSet)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) router.register(r'platforms', PlatformViewSet) router.register(r'quotes', QuoteViewSet) router.register(r'raids', RaidViewSet) router.register(r'tickets', TicketViewSet) urlpatterns = [ # Pusher. <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context (class names, function names, or code) available: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) . Output only the next line.
url(r'^pusher/donation/$', name='pusher-donation', view=PusherDonationView.as_view()),
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) router.register(r'platforms', PlatformViewSet) router.register(r'quotes', QuoteViewSet) router.register(r'raids', RaidViewSet) router.register(r'tickets', TicketViewSet) urlpatterns = [ # Pusher. url(r'^pusher/donation/$', name='pusher-donation', view=PusherDonationView.as_view()), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context (classes, functions, sometimes code) from other files: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) . Output only the next line.
url(r'^pusher/host/$', name='pusher-host', view=PusherHostView.as_view()),
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) router.register(r'platforms', PlatformViewSet) router.register(r'quotes', QuoteViewSet) router.register(r'raids', RaidViewSet) router.register(r'tickets', TicketViewSet) urlpatterns = [ # Pusher. url(r'^pusher/donation/$', name='pusher-donation', view=PusherDonationView.as_view()), url(r'^pusher/host/$', name='pusher-host', view=PusherHostView.as_view()), <|code_end|> . Use current file imports: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context (classes, functions, or code) from other files: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) . Output only the next line.
url(r'^pusher/resubscription/$', name='pusher-resubscription', view=PusherResubscriptionView.as_view()),
Given snippet: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) router.register(r'platforms', PlatformViewSet) router.register(r'quotes', QuoteViewSet) router.register(r'raids', RaidViewSet) router.register(r'tickets', TicketViewSet) urlpatterns = [ # Pusher. url(r'^pusher/donation/$', name='pusher-donation', view=PusherDonationView.as_view()), url(r'^pusher/host/$', name='pusher-host', view=PusherHostView.as_view()), url(r'^pusher/resubscription/$', name='pusher-resubscription', view=PusherResubscriptionView.as_view()), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView) and context: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) which might include code, classes, or functions. Output only the next line.
url(r'^pusher/subscription/$', name='pusher-subscription', view=PusherSubscriptionView.as_view()),
Next line prediction: <|code_start|># -*- coding: utf-8 -*- router = routers.DefaultRouter() router.register(r'broadcasts', BroadcastViewSet) router.register(r'games', GameViewSet) router.register(r'hosts', HostViewSet) router.register(r'platforms', PlatformViewSet) router.register(r'quotes', QuoteViewSet) router.register(r'raids', RaidViewSet) router.register(r'tickets', TicketViewSet) urlpatterns = [ # Pusher. url(r'^pusher/donation/$', name='pusher-donation', view=PusherDonationView.as_view()), url(r'^pusher/host/$', name='pusher-host', view=PusherHostView.as_view()), url(r'^pusher/resubscription/$', name='pusher-resubscription', view=PusherResubscriptionView.as_view()), url(r'^pusher/subscription/$', name='pusher-subscription', view=PusherSubscriptionView.as_view()), <|code_end|> . Use current file imports: (from django.conf.urls import url, include from rest_framework import routers from .views import (BroadcastViewSet, GameViewSet, HostViewSet, RaidViewSet, PlatformViewSet, QuoteViewSet, TicketViewSet, PusherDonationView, PusherHostView, PusherResubscriptionView, PusherSubscriptionView, PusherSubstreakView)) and context including class names, function names, or small code snippets from other files: # Path: apps/api/views.py # class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Broadcast.objects.order_by('-number') # serializer_class = BroadcastSerializer # # class GameViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Game.objects.all() # serializer_class = GameSerializer # # class HostViewSet(viewsets.ModelViewSet): # queryset = Host.objects.order_by('-timestamp') # serializer_class = HostSerializer # # def create(self, request, *args, **kwargs): # notify('host', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class RaidViewSet(viewsets.ModelViewSet): # queryset = Raid.objects.order_by('-timestamp') # serializer_class = RaidSerializer # # def create(self, request, *args, **kwargs): # notify('raid', {'username': request.data['username']}) # return super().create(request, *args, **kwargs) # # class PlatformViewSet(viewsets.ReadOnlyModelViewSet): # queryset = Platform.objects.all() # serializer_class = PlatformSerializer # # class QuoteViewSet(viewsets.ModelViewSet): # queryset = Quote.objects.all() # serializer_class = QuoteSerializer # # def retrieve(self, request, pk=None): # if pk == '0': # quote = Quote.objects.order_by('?').first() # serializer = QuoteSerializer(quote) # return Response(serializer.data) # else: # return super().retrieve(request, pk) # # class TicketViewSet(viewsets.ModelViewSet): # queryset = Ticket.objects.order_by('-updated') # serializer_class = TicketSerializer # # def create(self, request, *args, **kwargs): # # TODO: Somehow sync the use of "name" and "username" across methods. # notify('subscription', {'username': request.data['name']}) # return super().create(request, *args, **kwargs) # # def retrieve(self, request, pk=None): # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # serializer = TicketSerializer(ticket) # return Response(serializer.data) # # def update(self, request, pk=None): # data = request.data.copy() # queryset = Ticket.objects.all() # ticket = get_object_or_404(queryset, name=pk) # # data['name'] = ticket.name # serializer = TicketSerializer(ticket, data=data) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) # # # If 'streak' is included in the payload, then we consider it a # # "substreak" and should notify() as such. # if 'streak' in request.data: # notify('substreak', { # 'length': data['streak'], # 'username': ticket.name}) # else: # notify('resubscription', {'username': ticket.name}) # return Response(serializer.data) # # class PusherDonationView(views.APIView): # def post(self, request): # notify('donation', request.data) # return Response(status=202) # # class PusherHostView(views.APIView): # def post(self, request): # notify('host', request.data) # return Response(status=202) # # class PusherResubscriptionView(views.APIView): # def post(self, request): # notify('resubscription', request.data) # return Response(status=202) # # class PusherSubscriptionView(views.APIView): # def post(self, request): # notify('subscription', request.data) # return Response(status=202) # # class PusherSubstreakView(views.APIView): # def post(self, request): # notify('substreak', request.data) # return Response(status=202) . Output only the next line.
url(r'^pusher/substreak/$', name='pusher-substreak', view=PusherSubstreakView.as_view()),
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class Series(models.Model): name = models.CharField(max_length=200) class Meta: ordering = ['name'] verbose_name_plural = 'series' def __str__(self): return '{}'.format(self.name) @staticmethod def autocomplete_search_fields(): return ('name__exact', 'name__icontains') class Broadcast(models.Model): # Metadata. number = models.IntegerField(blank=True, null=True) airdate = models.DateField(default=timezone.now) status = models.CharField(blank=True, max_length=200, help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') notes = models.TextField(blank=True) # Connections. <|code_end|> , determine the next line of code. You have imports: from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone from apps.games.models import Game import requests and context (class names, function names, or code) available: # Path: apps/games/models.py # class Game(models.Model): # # Metadata. # name = models.CharField(max_length=200) # platform = models.ForeignKey(Platform, null=True, related_name='games') # # # Imagery. # image_art = models.ImageField('art', blank=True, upload_to='games', # help_text='16:9 art. Used for backgrounds, etc. Minimum size should be 1280x720.') # image_boxart = models.ImageField('boxart', blank=True, upload_to='games', # help_text='8:11 art akin to Twitch. Used for supplimentary display, lists, etc.') # # # Statuses. # is_abandoned = models.BooleanField('is abandoned?', default=False, # help_text='Has this game been abandoned for good?') # is_completed = models.BooleanField('is completed?', default=False, # help_text='Has this game been completed (if applicable).' ) # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
games = models.ManyToManyField(Game, related_name='appears_on')
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- class TicketAdmin(admin.ModelAdmin): list_display = ['name', 'display_name', 'created', 'updated', 'streak', 'is_active', 'is_paid', 'twid'] list_editable = ['is_active', 'is_paid'] ordering = ['-updated'] <|code_end|> using the current file's imports: from django.contrib import admin from .models import Ticket and any relevant context from other files: # Path: apps/subscribers/models.py # class Ticket(models.Model): # twid = models.CharField(blank=True, max_length=40) # name = models.CharField(max_length=200) # display_name = models.CharField(blank=True, max_length=200) # created = models.DateTimeField(default=timezone.now) # updated = models.DateTimeField(default=timezone.now) # # # Store the months if there's a substreak (defaults to 1 month). # streak = models.IntegerField(default=1) # # # Is this subscription active? # is_active = models.BooleanField(default=True, # help_text='Is this subscription active?') # is_paid = models.BooleanField(default=True, # help_text='Is this a paid subscription? (e.g., Not a bot.)') # # # Custom manager. # objects = TicketManager() # # class Meta: # ordering = ['updated'] # get_latest_by = 'updated' # # def __str__(self): # return '{}'.format(self.name) # # def update(self, **kwargs): # allowed_attributes = {'twid', 'display_name', 'updated', 'is_active'} # for name, value in kwargs.items(): # assert name in allowed_attributes # setattr(self, name, value) # self.save() . Output only the next line.
admin.site.register(Ticket, TicketAdmin)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- pytestmark = pytest.mark.django_db def test_quote_factory(): factory = QuoteFactory() <|code_end|> . Write the next line using the current file imports: import pytest from .factories import QuoteFactory from ..models import Quote and context from other files: # Path: apps/quotes/tests/factories.py # class QuoteFactory(factory.django.DjangoModelFactory): # class Meta: # model = Quote # # Path: apps/quotes/models.py # class Quote(models.Model): # text = models.TextField() # timestamp = models.DateField(default=timezone.now) # subject = models.CharField(blank=True, max_length=200, # help_text='The person that was quoted.') # creator = models.CharField(blank=True, max_length=200, # help_text='The person that created the quote.') # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='quotes') # game = models.ForeignKey(Game, blank=True, null=True, related_name='quoted_on') # # class Meta: # ordering = ['-timestamp'] # # def __str__(self): # return '{}'.format(self.text) , which may include functions, classes, or code. Output only the next line.
assert isinstance(factory, Quote)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class SeriesFactory(factory.django.DjangoModelFactory): class Meta: model = Series class BroadcastFactory(factory.django.DjangoModelFactory): class Meta: <|code_end|> , determine the next line of code. You have imports: import factory from ..models import Broadcast, Highlight, Host, Raid, Series and context (class names, function names, or code) available: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
model = Broadcast
Next line prediction: <|code_start|># -*- coding: utf-8 -*- class SeriesFactory(factory.django.DjangoModelFactory): class Meta: model = Series class BroadcastFactory(factory.django.DjangoModelFactory): class Meta: model = Broadcast class HighlightFactory(factory.django.DjangoModelFactory): class Meta: <|code_end|> . Use current file imports: (import factory from ..models import Broadcast, Highlight, Host, Raid, Series) and context including class names, function names, or small code snippets from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') . Output only the next line.
model = Highlight
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class SeriesFactory(factory.django.DjangoModelFactory): class Meta: model = Series class BroadcastFactory(factory.django.DjangoModelFactory): class Meta: model = Broadcast class HighlightFactory(factory.django.DjangoModelFactory): class Meta: model = Highlight broadcast = factory.SubFactory(BroadcastFactory) twid = 'c4136304' class HostFactory(factory.django.DjangoModelFactory): class Meta: <|code_end|> . Write the next line using the current file imports: import factory from ..models import Broadcast, Highlight, Host, Raid, Series and context from other files: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') , which may include functions, classes, or code. Output only the next line.
model = Host
Given snippet: <|code_start|> class SeriesFactory(factory.django.DjangoModelFactory): class Meta: model = Series class BroadcastFactory(factory.django.DjangoModelFactory): class Meta: model = Broadcast class HighlightFactory(factory.django.DjangoModelFactory): class Meta: model = Highlight broadcast = factory.SubFactory(BroadcastFactory) twid = 'c4136304' class HostFactory(factory.django.DjangoModelFactory): class Meta: model = Host broadcast = factory.SubFactory(BroadcastFactory) class RaidFactory(factory.django.DjangoModelFactory): class Meta: <|code_end|> , continue by predicting the next line. Consider current file imports: import factory from ..models import Broadcast, Highlight, Host, Raid, Series and context: # Path: apps/broadcasts/models.py # class Broadcast(models.Model): # # Metadata. # number = models.IntegerField(blank=True, null=True) # airdate = models.DateField(default=timezone.now) # status = models.CharField(blank=True, max_length=200, # help_text='Loosely related to Twitch\'s status field. Does not need to match. Will display on overlays.') # notes = models.TextField(blank=True) # # # Connections. # games = models.ManyToManyField(Game, related_name='appears_on') # series = models.ForeignKey(Series, blank=True, null=True, related_name='broadcasts', # help_text='Is this episode part of an ongoing series (i.e., "Whatever Wednesdays", etc.)?') # # # Statuses. # is_charity = models.BooleanField('is for charity?', default=False, # help_text='Is a charity fundraiser involved in this episode?') # is_marathon = models.BooleanField('is a marathon?', default=False, # help_text='Is this a marathon episode (longer than 12 hours)?') # # class Meta: # get_latest_by = 'airdate' # ordering = ['-airdate'] # # def __str__(self): # return 'Episode {}'.format(self.number) # # def get_absolute_url(self): # return reverse('broadcast-detail', kwargs={'slug': self.number}) # # class Highlight(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='highlights') # twid = models.CharField('Twitch ID', max_length=200, # help_text='The highlight\'s ID on Twitch; used for API calls, etc.') # # # Silly metadata (filled out by an API call). # title = models.CharField(blank=True, max_length=200) # description = models.TextField(blank=True) # url = models.URLField('URL', blank=True) # game = models.ForeignKey(Game, blank=True, null=True, related_name='highlited_on') # # class Meta: # ordering = ['-twid'] # order_with_respect_to = 'broadcast' # # def save(self, *args, **kwargs): # # Grab our new highlight ID and run an API call. # import requests # endpoint = 'https://api.twitch.tv/kraken/videos/{}'.format(self.twid) # json = requests.get(endpoint).json() # # # Take the response and save it to the instance. # # But first, find the game, so we can save that. # if json['game']: # game = Game.objects.get(name=json['game']) # self.game = game # self.description = json['description'] # self.title = json['title'] # self.url = json['url'] # super().save(*args, **kwargs) # # def __str__(self): # if not self.title: # return 'Highlight for {}'.format(self.broadcast) # return self.title # # class Host(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='hosts') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Raid(models.Model): # broadcast = models.ForeignKey(Broadcast, blank=True, null=True, related_name='raids') # timestamp = models.DateTimeField(default=timezone.now, # help_text='When did it happen?') # username = models.CharField(blank=True, max_length=200) # # # Silly metadata. # game = models.CharField(blank=True, max_length=200, # help_text='The game the raider was playing at the time of raiding.') # # class Meta: # order_with_respect_to = 'broadcast' # ordering = ['timestamp'] # # def __str__(self): # return '{}'.format(self.username) # # class Series(models.Model): # name = models.CharField(max_length=200) # # class Meta: # ordering = ['name'] # verbose_name_plural = 'series' # # def __str__(self): # return '{}'.format(self.name) # # @staticmethod # def autocomplete_search_fields(): # return ('name__exact', 'name__icontains') which might include code, classes, or functions. Output only the next line.
model = Raid
Predict the next line after this snippet: <|code_start|>def main(args=None): # parse command-line options parser = argparse.ArgumentParser( description='description: convert JSON file with refined multislit ' 'parameters to new JSON format' ) # required arguments parser.add_argument("input_json", help="Input JSON with refined boundary parameters", type=argparse.FileType('rt')) parser.add_argument("output_json", help="Output JSON with fitted boundary parameters", type=lambda x: arg_file_is_new(parser, x, mode='wt')) # optional arguments parser.add_argument("--echo", help="Display full command line", action="store_true") args = parser.parse_args(args) if args.echo: print('\033[1m\033[31m% ' + ' '.join(sys.argv) + '\033[0m\n') # --- # read input JSON file input_json = json.loads(open(args.input_json.name).read()) # generate object of type RefinedBoundaryModelParam from input JSON file <|code_end|> using the current file's imports: import argparse import json import sys import numina.types.qc from numina.tools.arg_file_is_new import arg_file_is_new from numina.tools.check_setstate_getstate import check_setstate_getstate from emirdrp.products import RefinedBoundaryModelParam and any relevant context from other files: # Path: emirdrp/products.py # class RefinedBoundaryModelParam(numina.types.structured.BaseStructuredCalibration): # """Refined parameters of MOS model # """ # def __init__(self, instrument='unknown'): # super(RefinedBoundaryModelParam, self).__init__(instrument) # self.tags = { # 'grism': "unknown", # 'filter': "unknown" # } # self.contents = [] # # def __getstate__(self): # state = super(RefinedBoundaryModelParam, self).__getstate__() # if six.PY2: # state['contents'] = copy.copy(self.contents) # else: # state['contents'] = self.contents.copy() # return state # # def __setstate__(self, state): # super(RefinedBoundaryModelParam, self).__setstate__(state) # if six.PY2: # self.contents = copy.copy(state['contents']) # else: # self.contents = state['contents'].copy() # # def tag_names(self): # return ['grism', 'filter'] . Output only the next line.
refined_boundary_model = RefinedBoundaryModelParam(instrument='EMIR')
Continue the code snippet: <|code_start|># (at your option) any later version. # # PyEmir is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PyEmir. If not, see <http://www.gnu.org/licenses/>. # '''Test the procedures module''' def test_encloses_annulus(): a = numpy.zeros((100, 100)) r_in = 6 r_out = 15.5 xc = 51.4 yc = 52.9 x_min = -0.5 - xc x_max = a.shape[1] - 0.5 - xc y_min = -0.5 - yc y_max = a.shape[1] - 0.5 - yc <|code_end|> . Use current file imports: import pytest import numpy from numpy.testing import assert_allclose from ..procedures import encloses_annulus and context (classes, functions, or code) from other files: # Path: emirdrp/recipes/aiv/procedures.py # def encloses_annulus(x_min, x_max, y_min, y_max, nx, ny, r_in, r_out): # '''Encloses function backported from old photutils''' # # gout = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_out, 1, 1) # gin = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_in, 1, 1) # return gout - gin . Output only the next line.
aa = encloses_annulus(x_min, x_max, y_min, y_max,
Given the following code snippet before the placeholder: <|code_start|># # Copyright 2015-2019 Universidad Complutense de Madrid # # This file is part of PyEmir # # SPDX-License-Identifier: GPL-3.0+ # License-Filename: LICENSE.txt # """Test the AIV pinhole mask recipe""" BASE_URL = 'https://guaix.fis.ucm.es/data/pyemir/test/' @pytest.mark.remote_data def _test_mode_TEST6_set0(numinatpldir): <|code_end|> , predict the next line using imports from the current file: import pytest from emirdrp.tests.runrecipe import run_recipe and context including class names, function names, and sometimes code from other files: # Path: emirdrp/tests/runrecipe.py # def run_recipe(): # main(['run', 'obsrun.yaml', '-r', 'control.yaml']) . Output only the next line.
run_recipe()
Next line prediction: <|code_start|>"""Recipe for the reduction of gain calibration frames.""" _logger = logging.getLogger('numina.recipes.emir') class GainRecipe1(EmirRecipe): """Detector Gain Recipe. Recipe to calibrate the detector gain. """ obresult = ObservationResultRequirement() region = Parameter('channel', 'Region used to compute: ' '(full|quadrant|channel)', choices=['full', 'quadrant', 'channel'] ) gain = Result(MasterGainMap(None, None, None)) ron = Result(MasterRONMap(None, None)) def region(self, reqs): mm = reqs['region'].tolower() if mm == 'full': return ((slice(0, 2048), slice(0, 2048))) elif mm == 'quadrant': <|code_end|> . Use current file imports: (import logging import math import numpy import scipy.stats from astropy.io import fits from numina.core.requirements import ObservationResultRequirement from numina.core import Parameter, DataFrame from numina.exceptions import RecipeError from numina.core import Result from emirdrp.core.recipe import EmirRecipe from emirdrp.instrument.channels import QUADRANTS from emirdrp.instrument.channels import CHANNELS from emirdrp.products import MasterGainMap, MasterRONMap) and context including class names, function names, or small code snippets from other files: # Path: emirdrp/core/recipe.py # class EmirRecipe(recipes.BaseRecipe): # """Base clase for all EMIR Recipes # # # Attributes # ---------- # logger : # recipe logger # # datamodel : EmirDataModel # # """ # logger = logging.getLogger(__name__) # datamodel = emirdrp.datamodel.EmirDataModel() # # def types_getter(self): # imgtypes = [prods.MasterBadPixelMask, # prods.MasterBias, # prods.MasterDark, # prods.MasterIntensityFlat, # prods.MasterSpectralFlat, # prods.MasterSky # ] # getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d, # [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s] # # return imgtypes, getters # # def get_filters(self): # import collections # imgtypes, getters = self.types_getter() # used_getters = [] # for rtype, getter in zip(imgtypes, getters): # self.logger.debug('get_filters, %s %s', rtype, getter) # if rtype is None: # # Unconditional # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # else: # # Search # for key, val in self.RecipeInput.stored().items(): # if isinstance(val.type, rtype): # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # break # else: # pass # return used_getters # # def init_filters_generic(self, rinput, getters, ins): # # with BPM, bias, dark, flat and sky # if numina.ext.gtc.check_gtc(): # self.logger.debug('running in GTC environment') # else: # self.logger.debug('running outside of GTC environment') # # meta = emirdrp.processing.info.gather_info(rinput) # self.logger.debug('obresult info') # for entry in meta['obresult']: # self.logger.debug('frame info is %s', entry) # correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters] # flow = flowmod.SerialFlow(correctors) # return flow # # def init_filters(self, rinput, ins='EMIR'): # getters = self.get_filters() # return self.init_filters_generic(rinput, getters, ins) # # def aggregate_result(self, result, rinput): # return result # # Path: emirdrp/instrument/channels.py # QUADRANTS = [(_P2, _P1), (_P1, _P1), (_P1, _P2), (_P2, _P2)] # # Path: emirdrp/instrument/channels.py # CHANNELS = [chan for chans in [_CH1, _CH2, _CH3, _CH4] for chan in chans] # # Path: emirdrp/products.py # class MasterGainMap(DataProductType): # def __init__(self, mean, var, frame): # self.mean = mean # self.var = var # self.frame = frame # # def __getstate__(self): # gmean = list(map(float, self.mean.flat)) # gvar = list(map(float, self.var.flat)) # return {'frame': self.frame, 'mean': gmean, 'var': gvar} # # class MasterRONMap(DataProductType): # def __init__(self, mean, var): # self.mean = mean # self.var = var # # def __getstate__(self): # gmean = map(float, self.mean.flat) # gvar = map(float, self.var.flat) # return {'mean': gmean, 'var': gvar} . Output only the next line.
return QUADRANTS
Given snippet: <|code_start|> _logger = logging.getLogger('numina.recipes.emir') class GainRecipe1(EmirRecipe): """Detector Gain Recipe. Recipe to calibrate the detector gain. """ obresult = ObservationResultRequirement() region = Parameter('channel', 'Region used to compute: ' '(full|quadrant|channel)', choices=['full', 'quadrant', 'channel'] ) gain = Result(MasterGainMap(None, None, None)) ron = Result(MasterRONMap(None, None)) def region(self, reqs): mm = reqs['region'].tolower() if mm == 'full': return ((slice(0, 2048), slice(0, 2048))) elif mm == 'quadrant': return QUADRANTS elif mm == 'channel': <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import math import numpy import scipy.stats from astropy.io import fits from numina.core.requirements import ObservationResultRequirement from numina.core import Parameter, DataFrame from numina.exceptions import RecipeError from numina.core import Result from emirdrp.core.recipe import EmirRecipe from emirdrp.instrument.channels import QUADRANTS from emirdrp.instrument.channels import CHANNELS from emirdrp.products import MasterGainMap, MasterRONMap and context: # Path: emirdrp/core/recipe.py # class EmirRecipe(recipes.BaseRecipe): # """Base clase for all EMIR Recipes # # # Attributes # ---------- # logger : # recipe logger # # datamodel : EmirDataModel # # """ # logger = logging.getLogger(__name__) # datamodel = emirdrp.datamodel.EmirDataModel() # # def types_getter(self): # imgtypes = [prods.MasterBadPixelMask, # prods.MasterBias, # prods.MasterDark, # prods.MasterIntensityFlat, # prods.MasterSpectralFlat, # prods.MasterSky # ] # getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d, # [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s] # # return imgtypes, getters # # def get_filters(self): # import collections # imgtypes, getters = self.types_getter() # used_getters = [] # for rtype, getter in zip(imgtypes, getters): # self.logger.debug('get_filters, %s %s', rtype, getter) # if rtype is None: # # Unconditional # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # else: # # Search # for key, val in self.RecipeInput.stored().items(): # if isinstance(val.type, rtype): # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # break # else: # pass # return used_getters # # def init_filters_generic(self, rinput, getters, ins): # # with BPM, bias, dark, flat and sky # if numina.ext.gtc.check_gtc(): # self.logger.debug('running in GTC environment') # else: # self.logger.debug('running outside of GTC environment') # # meta = emirdrp.processing.info.gather_info(rinput) # self.logger.debug('obresult info') # for entry in meta['obresult']: # self.logger.debug('frame info is %s', entry) # correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters] # flow = flowmod.SerialFlow(correctors) # return flow # # def init_filters(self, rinput, ins='EMIR'): # getters = self.get_filters() # return self.init_filters_generic(rinput, getters, ins) # # def aggregate_result(self, result, rinput): # return result # # Path: emirdrp/instrument/channels.py # QUADRANTS = [(_P2, _P1), (_P1, _P1), (_P1, _P2), (_P2, _P2)] # # Path: emirdrp/instrument/channels.py # CHANNELS = [chan for chans in [_CH1, _CH2, _CH3, _CH4] for chan in chans] # # Path: emirdrp/products.py # class MasterGainMap(DataProductType): # def __init__(self, mean, var, frame): # self.mean = mean # self.var = var # self.frame = frame # # def __getstate__(self): # gmean = list(map(float, self.mean.flat)) # gvar = list(map(float, self.var.flat)) # return {'frame': self.frame, 'mean': gmean, 'var': gvar} # # class MasterRONMap(DataProductType): # def __init__(self, mean, var): # self.mean = mean # self.var = var # # def __getstate__(self): # gmean = map(float, self.mean.flat) # gvar = map(float, self.var.flat) # return {'mean': gmean, 'var': gvar} which might include code, classes, or functions. Output only the next line.
return CHANNELS
Predict the next line for this snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PyEmir. If not, see <http://www.gnu.org/licenses/>. # """Recipe for the reduction of gain calibration frames.""" _logger = logging.getLogger('numina.recipes.emir') class GainRecipe1(EmirRecipe): """Detector Gain Recipe. Recipe to calibrate the detector gain. """ obresult = ObservationResultRequirement() region = Parameter('channel', 'Region used to compute: ' '(full|quadrant|channel)', choices=['full', 'quadrant', 'channel'] ) <|code_end|> with the help of current file imports: import logging import math import numpy import scipy.stats from astropy.io import fits from numina.core.requirements import ObservationResultRequirement from numina.core import Parameter, DataFrame from numina.exceptions import RecipeError from numina.core import Result from emirdrp.core.recipe import EmirRecipe from emirdrp.instrument.channels import QUADRANTS from emirdrp.instrument.channels import CHANNELS from emirdrp.products import MasterGainMap, MasterRONMap and context from other files: # Path: emirdrp/core/recipe.py # class EmirRecipe(recipes.BaseRecipe): # """Base clase for all EMIR Recipes # # # Attributes # ---------- # logger : # recipe logger # # datamodel : EmirDataModel # # """ # logger = logging.getLogger(__name__) # datamodel = emirdrp.datamodel.EmirDataModel() # # def types_getter(self): # imgtypes = [prods.MasterBadPixelMask, # prods.MasterBias, # prods.MasterDark, # prods.MasterIntensityFlat, # prods.MasterSpectralFlat, # prods.MasterSky # ] # getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d, # [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s] # # return imgtypes, getters # # def get_filters(self): # import collections # imgtypes, getters = self.types_getter() # used_getters = [] # for rtype, getter in zip(imgtypes, getters): # self.logger.debug('get_filters, %s %s', rtype, getter) # if rtype is None: # # Unconditional # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # else: # # Search # for key, val in self.RecipeInput.stored().items(): # if isinstance(val.type, rtype): # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # break # else: # pass # return used_getters # # def init_filters_generic(self, rinput, getters, ins): # # with BPM, bias, dark, flat and sky # if numina.ext.gtc.check_gtc(): # self.logger.debug('running in GTC environment') # else: # self.logger.debug('running outside of GTC environment') # # meta = emirdrp.processing.info.gather_info(rinput) # self.logger.debug('obresult info') # for entry in meta['obresult']: # self.logger.debug('frame info is %s', entry) # correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters] # flow = flowmod.SerialFlow(correctors) # return flow # # def init_filters(self, rinput, ins='EMIR'): # getters = self.get_filters() # return self.init_filters_generic(rinput, getters, ins) # # def aggregate_result(self, result, rinput): # return result # # Path: emirdrp/instrument/channels.py # QUADRANTS = [(_P2, _P1), (_P1, _P1), (_P1, _P2), (_P2, _P2)] # # Path: emirdrp/instrument/channels.py # CHANNELS = [chan for chans in [_CH1, _CH2, _CH3, _CH4] for chan in chans] # # Path: emirdrp/products.py # class MasterGainMap(DataProductType): # def __init__(self, mean, var, frame): # self.mean = mean # self.var = var # self.frame = frame # # def __getstate__(self): # gmean = list(map(float, self.mean.flat)) # gvar = list(map(float, self.var.flat)) # return {'frame': self.frame, 'mean': gmean, 'var': gvar} # # class MasterRONMap(DataProductType): # def __init__(self, mean, var): # self.mean = mean # self.var = var # # def __getstate__(self): # gmean = map(float, self.mean.flat) # gvar = map(float, self.var.flat) # return {'mean': gmean, 'var': gvar} , which may contain function names, class names, or code. Output only the next line.
gain = Result(MasterGainMap(None, None, None))
Given the code snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PyEmir. If not, see <http://www.gnu.org/licenses/>. # """Recipe for the reduction of gain calibration frames.""" _logger = logging.getLogger('numina.recipes.emir') class GainRecipe1(EmirRecipe): """Detector Gain Recipe. Recipe to calibrate the detector gain. """ obresult = ObservationResultRequirement() region = Parameter('channel', 'Region used to compute: ' '(full|quadrant|channel)', choices=['full', 'quadrant', 'channel'] ) gain = Result(MasterGainMap(None, None, None)) <|code_end|> , generate the next line using the imports in this file: import logging import math import numpy import scipy.stats from astropy.io import fits from numina.core.requirements import ObservationResultRequirement from numina.core import Parameter, DataFrame from numina.exceptions import RecipeError from numina.core import Result from emirdrp.core.recipe import EmirRecipe from emirdrp.instrument.channels import QUADRANTS from emirdrp.instrument.channels import CHANNELS from emirdrp.products import MasterGainMap, MasterRONMap and context (functions, classes, or occasionally code) from other files: # Path: emirdrp/core/recipe.py # class EmirRecipe(recipes.BaseRecipe): # """Base clase for all EMIR Recipes # # # Attributes # ---------- # logger : # recipe logger # # datamodel : EmirDataModel # # """ # logger = logging.getLogger(__name__) # datamodel = emirdrp.datamodel.EmirDataModel() # # def types_getter(self): # imgtypes = [prods.MasterBadPixelMask, # prods.MasterBias, # prods.MasterDark, # prods.MasterIntensityFlat, # prods.MasterSpectralFlat, # prods.MasterSky # ] # getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d, # [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s] # # return imgtypes, getters # # def get_filters(self): # import collections # imgtypes, getters = self.types_getter() # used_getters = [] # for rtype, getter in zip(imgtypes, getters): # self.logger.debug('get_filters, %s %s', rtype, getter) # if rtype is None: # # Unconditional # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # else: # # Search # for key, val in self.RecipeInput.stored().items(): # if isinstance(val.type, rtype): # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # break # else: # pass # return used_getters # # def init_filters_generic(self, rinput, getters, ins): # # with BPM, bias, dark, flat and sky # if numina.ext.gtc.check_gtc(): # self.logger.debug('running in GTC environment') # else: # self.logger.debug('running outside of GTC environment') # # meta = emirdrp.processing.info.gather_info(rinput) # self.logger.debug('obresult info') # for entry in meta['obresult']: # self.logger.debug('frame info is %s', entry) # correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters] # flow = flowmod.SerialFlow(correctors) # return flow # # def init_filters(self, rinput, ins='EMIR'): # getters = self.get_filters() # return self.init_filters_generic(rinput, getters, ins) # # def aggregate_result(self, result, rinput): # return result # # Path: emirdrp/instrument/channels.py # QUADRANTS = [(_P2, _P1), (_P1, _P1), (_P1, _P2), (_P2, _P2)] # # Path: emirdrp/instrument/channels.py # CHANNELS = [chan for chans in [_CH1, _CH2, _CH3, _CH4] for chan in chans] # # Path: emirdrp/products.py # class MasterGainMap(DataProductType): # def __init__(self, mean, var, frame): # self.mean = mean # self.var = var # self.frame = frame # # def __getstate__(self): # gmean = list(map(float, self.mean.flat)) # gvar = list(map(float, self.var.flat)) # return {'frame': self.frame, 'mean': gmean, 'var': gvar} # # class MasterRONMap(DataProductType): # def __init__(self, mean, var): # self.mean = mean # self.var = var # # def __getstate__(self): # gmean = map(float, self.mean.flat) # gvar = map(float, self.var.flat) # return {'mean': gmean, 'var': gvar} . Output only the next line.
ron = Result(MasterRONMap(None, None))
Using the snippet: <|code_start|> def useful_mos_xpixels(reduced_mos_data, base_header, vpix_region, npix_removed_near_ohlines=0, list_valid_wvregions=None, debugplot=0): """Useful X-axis pixels removing +/- npixaround pixels around each OH line """ # get wavelength calibration from image header naxis1 = base_header['naxis1'] naxis2 = base_header['naxis2'] crpix1 = base_header['crpix1'] crval1 = base_header['crval1'] cdelt1 = base_header['cdelt1'] # check vertical region nsmin = int(vpix_region[0] + 0.5) nsmax = int(vpix_region[1] + 0.5) if nsmin > nsmax: raise ValueError('vpix_region values in wrong order') elif nsmin < 1 or nsmax > naxis2: raise ValueError('vpix_region outside valid range') # minimum and maximum pixels in the wavelength direction <|code_end|> , determine the next line of code. You have imports: import numpy as np import pkgutil from six import StringIO from numina.array.display.ximshow import ximshow from numina.array.display.pause_debugplot import pause_debugplot from emirdrp.processing.wavecal.get_islitlet import get_islitlet and context (class names, function names, or code) available: # Path: emirdrp/processing/wavecal/get_islitlet.py # def get_islitlet(ipixel): # """Return islilet (from 1 to EMIR_NBARS) from Y-pixel coordinate # # Parameters # ---------- # ipixel : int # Y-pixel coordinate in the rectified image. # # Returns # ------- # islitlet : int # Slitlet number (from 1 to EMIR_NBARS). # # """ # # if ipixel < 1: # raise ValueError('ipixel={} cannot be < 1'.format(ipixel)) # # if ipixel > EMIR_NPIXPERSLIT_RECTIFIED * EMIR_NBARS: # raise ValueError('ipixel={} cannot be > {}'.format( # ipixel, EMIR_NPIXPERSLIT_RECTIFIED * EMIR_NBARS # )) # # islitlet = int(ipixel / EMIR_NPIXPERSLIT_RECTIFIED) + 1 # # if ipixel % EMIR_NPIXPERSLIT_RECTIFIED == 0: # islitlet -= 1 # # return islitlet . Output only the next line.
islitlet_min = get_islitlet(nsmin)
Given snippet: <|code_start|># License-Filename: LICENSE.txt # """Twilight Flat Recipe for a list of frames in different filters""" class MultiTwilightFlatRecipe(EmirRecipe): """Create a list of twilight flats""" obresult = reqs.ObservationResultRequirement() master_bpm = reqs.MasterBadPixelMaskRequirement() master_bias = reqs.MasterBiasRequirement() master_dark = reqs.MasterDarkRequirement() twflatframes = Result(dt.ListOfType(prods.MasterIntensityFlat)) def run(self, rinput): results = [] self.logger.info('starting multiflat flat reduction') # Uncomment this line # to revert to non-ramp # flow = self.init_filters(rinput) saturation = 45000.0 <|code_end|> , continue by predicting the next line. Consider current file imports: import uuid import datetime import numpy import astropy.io.fits as fits import numina.types.datatype as dt import emirdrp.products as prods import emirdrp.requirements as reqs from numina.array.combine import median from numina.array.robustfit import fit_theil_sen from numina.core import Result from numina.frame.utils import copy_img from numina.processing.combine import basic_processing_with_combination_frames from emirdrp.processing.info import gather_info_frames from emirdrp.core.recipe import EmirRecipe and context: # Path: emirdrp/processing/info.py # def gather_info_frames(framelist): # iinfo = [] # for frame in framelist: # with frame.open() as hdulist: # iinfo.append(gather_info_hdu(hdulist)) # return iinfo # # Path: emirdrp/core/recipe.py # class EmirRecipe(recipes.BaseRecipe): # """Base clase for all EMIR Recipes # # # Attributes # ---------- # logger : # recipe logger # # datamodel : EmirDataModel # # """ # logger = logging.getLogger(__name__) # datamodel = emirdrp.datamodel.EmirDataModel() # # def types_getter(self): # imgtypes = [prods.MasterBadPixelMask, # prods.MasterBias, # prods.MasterDark, # prods.MasterIntensityFlat, # prods.MasterSpectralFlat, # prods.MasterSky # ] # getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d, # [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s] # # return imgtypes, getters # # def get_filters(self): # import collections # imgtypes, getters = self.types_getter() # used_getters = [] # for rtype, getter in zip(imgtypes, getters): # self.logger.debug('get_filters, %s %s', rtype, getter) # if rtype is None: # # Unconditional # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # else: # # Search # for key, val in self.RecipeInput.stored().items(): # if isinstance(val.type, rtype): # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # break # else: # pass # return used_getters # # def init_filters_generic(self, rinput, getters, ins): # # with BPM, bias, dark, flat and sky # if numina.ext.gtc.check_gtc(): # self.logger.debug('running in GTC environment') # else: # self.logger.debug('running outside of GTC environment') # # meta = emirdrp.processing.info.gather_info(rinput) # self.logger.debug('obresult info') # for entry in meta['obresult']: # self.logger.debug('frame info is %s', entry) # correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters] # flow = flowmod.SerialFlow(correctors) # return flow # # def init_filters(self, rinput, ins='EMIR'): # getters = self.get_filters() # return self.init_filters_generic(rinput, getters, ins) # # def aggregate_result(self, result, rinput): # return result which might include code, classes, or functions. Output only the next line.
iinfo = gather_info_frames(rinput.obresult.frames)
Given the following code snippet before the placeholder: <|code_start|> m, s = np.mean(data_sub), np.std(data_sub) ax.imshow(data_sub, interpolation='nearest', cmap='gray', vmin=m - s, vmax=m + s, origin='lower', extent=bounding_box.extent) if plot_reference: e = Ellipse(xy=(plot_reference[0], plot_reference[1]), width=6, height=6, angle=0) e.set_facecolor('none') e.set_edgecolor('green') ax.add_artist(e) # plot an ellipse for each object for idx, obj in enumerate(objects): e = Ellipse(xy=(obj['x'] + ref_x, obj['y'] + ref_y), width=6 * obj['a'], height=6 * obj['b'], angle=obj['theta'] * 180. / np.pi) e.set_facecolor('none') if idx == iadx: e.set_edgecolor('blue') else: e.set_edgecolor('red') ax.add_artist(e) return maxflux['x'], maxflux['y'], ax else: return maxflux['x'], maxflux['y'] <|code_end|> , predict the next line using imports from the current file: import sys import math import logging import itertools import numpy as np import matplotlib.pyplot as plt import sep import astropy.units as u import astropy.wcs import skimage.filters as filt import skimage.feature as feat import numina.types.array as tarray import numina.core.query as qmod import emirdrp.instrument.constants as cons import emirdrp.requirements as reqs import emirdrp.products as prods import emirdrp.instrument.distortions as dist import emirdrp.instrument.csuconf as csuconf from scipy import ndimage as ndi from numina.array.utils import coor_to_pix_1d from numina.array.bbox import BoundingBox from numina.array.offrot import fit_offset_and_rotation from numina.array.peaks.peakdet import refine_peaks from numina.core import Requirement, Result from numina.types.qc import QC from numina.core.requirements import ObservationResultRequirement from emirdrp.core.recipe import EmirRecipe from emirdrp.core.utils import create_rot2d from emirdrp.processing.combine import basic_processing_, combine_images from emirdrp.processing.combine import process_ab, process_abba from emirdrp.instrument.csuconf import TargetType from matplotlib.patches import Ellipse from emirdrp.instrument.dtuconf import DtuConf and context including class names, function names, and sometimes code from other files: # Path: emirdrp/core/recipe.py # class EmirRecipe(recipes.BaseRecipe): # """Base clase for all EMIR Recipes # # # Attributes # ---------- # logger : # recipe logger # # datamodel : EmirDataModel # # """ # logger = logging.getLogger(__name__) # datamodel = emirdrp.datamodel.EmirDataModel() # # def types_getter(self): # imgtypes = [prods.MasterBadPixelMask, # prods.MasterBias, # prods.MasterDark, # prods.MasterIntensityFlat, # prods.MasterSpectralFlat, # prods.MasterSky # ] # getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d, # [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s] # # return imgtypes, getters # # def get_filters(self): # import collections # imgtypes, getters = self.types_getter() # used_getters = [] # for rtype, getter in zip(imgtypes, getters): # self.logger.debug('get_filters, %s %s', rtype, getter) # if rtype is None: # # Unconditional # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # else: # # Search # for key, val in self.RecipeInput.stored().items(): # if isinstance(val.type, rtype): # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # break # else: # pass # return used_getters # # def init_filters_generic(self, rinput, getters, ins): # # with BPM, bias, dark, flat and sky # if numina.ext.gtc.check_gtc(): # self.logger.debug('running in GTC environment') # else: # self.logger.debug('running outside of GTC environment') # # meta = emirdrp.processing.info.gather_info(rinput) # self.logger.debug('obresult info') # for entry in meta['obresult']: # self.logger.debug('frame info is %s', entry) # correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters] # flow = flowmod.SerialFlow(correctors) # return flow # # def init_filters(self, rinput, ins='EMIR'): # getters = self.get_filters() # return self.init_filters_generic(rinput, getters, ins) # # def aggregate_result(self, result, rinput): # return result # # Path: emirdrp/core/utils.py # def create_rot2d(angle): # """Create 2D rotation matrix""" # ca = math.cos(angle) # sa = math.sin(angle) # return numpy.array([[ca, -sa], [sa, ca]]) # # Path: emirdrp/instrument/csuconf.py # class TargetType(enum.Enum): # """Possible targets in a slit""" # UNASSIGNED = 0 # SOURCE = 1 # REFERENCE = 2 # SKY = 3 # UNKNOWN = 4 . Output only the next line.
class MaskCheckRecipe(EmirRecipe):
Using the snippet: <|code_start|> if not csu_conf.is_open(): #self.logger.info('CSU is configured, detecting slits') # slits_bb = self.compute_slits(hdulist_slit, csu_conf) # Not detecting slits. We trust the model slits_bb = None image_sep = hdulist_object[0].data.astype('float32') self.logger.debug('center of rotation (from CRPIX) is %s', wcs.wcs.crpix) self.logger.debug('create adapted WCS from header WCS') wcsa = dist.adapt_wcs(wcs, ipa_deg=ipa_deg.value, rotang_deg=rotoff_deg.value) self.logger.debug('CD matrix of WCS %s', wcs.wcs.cd) self.logger.debug('CD matrix of adapted WCS %s', wcsa.wcs.cd) # angle in deg, offset in pixels on the CSU offset, angle, qc, coords = compute_off_rotation( image_sep, wcsa, csu_conf, slits_bb, rotaxis=rotaxis, logger=self.logger, debug_plot=False, intermediate_results=self.intermediate_results ) else: self.logger.info('CSU is open, not detecting slits') offset = [0.0, 0.0] angle = 0.0 coords = ([], [], [], [], []) qc = QC.GOOD pixsize_na = cons.EMIR_PIXSCALE / cons.GTC_NASMYTH_A_PLATESCALE self.logger.debug('Pixel size in NASMYTH_A %s mm', pixsize_na) # Offset is returned without units o_mm = ((offset * u.pixel) * pixsize_na).to(u.mm) <|code_end|> , determine the next line of code. You have imports: import sys import math import logging import itertools import numpy as np import matplotlib.pyplot as plt import sep import astropy.units as u import astropy.wcs import skimage.filters as filt import skimage.feature as feat import numina.types.array as tarray import numina.core.query as qmod import emirdrp.instrument.constants as cons import emirdrp.requirements as reqs import emirdrp.products as prods import emirdrp.instrument.distortions as dist import emirdrp.instrument.csuconf as csuconf from scipy import ndimage as ndi from numina.array.utils import coor_to_pix_1d from numina.array.bbox import BoundingBox from numina.array.offrot import fit_offset_and_rotation from numina.array.peaks.peakdet import refine_peaks from numina.core import Requirement, Result from numina.types.qc import QC from numina.core.requirements import ObservationResultRequirement from emirdrp.core.recipe import EmirRecipe from emirdrp.core.utils import create_rot2d from emirdrp.processing.combine import basic_processing_, combine_images from emirdrp.processing.combine import process_ab, process_abba from emirdrp.instrument.csuconf import TargetType from matplotlib.patches import Ellipse from emirdrp.instrument.dtuconf import DtuConf and context (class names, function names, or code) available: # Path: emirdrp/core/recipe.py # class EmirRecipe(recipes.BaseRecipe): # """Base clase for all EMIR Recipes # # # Attributes # ---------- # logger : # recipe logger # # datamodel : EmirDataModel # # """ # logger = logging.getLogger(__name__) # datamodel = emirdrp.datamodel.EmirDataModel() # # def types_getter(self): # imgtypes = [prods.MasterBadPixelMask, # prods.MasterBias, # prods.MasterDark, # prods.MasterIntensityFlat, # prods.MasterSpectralFlat, # prods.MasterSky # ] # getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d, # [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s] # # return imgtypes, getters # # def get_filters(self): # import collections # imgtypes, getters = self.types_getter() # used_getters = [] # for rtype, getter in zip(imgtypes, getters): # self.logger.debug('get_filters, %s %s', rtype, getter) # if rtype is None: # # Unconditional # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # else: # # Search # for key, val in self.RecipeInput.stored().items(): # if isinstance(val.type, rtype): # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # break # else: # pass # return used_getters # # def init_filters_generic(self, rinput, getters, ins): # # with BPM, bias, dark, flat and sky # if numina.ext.gtc.check_gtc(): # self.logger.debug('running in GTC environment') # else: # self.logger.debug('running outside of GTC environment') # # meta = emirdrp.processing.info.gather_info(rinput) # self.logger.debug('obresult info') # for entry in meta['obresult']: # self.logger.debug('frame info is %s', entry) # correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters] # flow = flowmod.SerialFlow(correctors) # return flow # # def init_filters(self, rinput, ins='EMIR'): # getters = self.get_filters() # return self.init_filters_generic(rinput, getters, ins) # # def aggregate_result(self, result, rinput): # return result # # Path: emirdrp/core/utils.py # def create_rot2d(angle): # """Create 2D rotation matrix""" # ca = math.cos(angle) # sa = math.sin(angle) # return numpy.array([[ca, -sa], [sa, ca]]) # # Path: emirdrp/instrument/csuconf.py # class TargetType(enum.Enum): # """Possible targets in a slit""" # UNASSIGNED = 0 # SOURCE = 1 # REFERENCE = 2 # SKY = 3 # UNKNOWN = 4 . Output only the next line.
ipa_rot = create_rot2d(ipa_deg.to('', equivalencies=u.dimensionless_angles()))
Predict the next line after this snippet: <|code_start|> trans3 = [[0, -1, 0], [1, 0, 0], [0, 0, 1]] # T3 = T2 * T1 vec = np.dot(trans3, dtuconf.coor_r) * u.micron/ cons.EMIR_PIXSIZE self.logger.debug('DTU shift is %s', vec) self.logger.debug('create bar model') barmodel = csuconf.create_bar_models(bars_nominal_positions) csu_conf = csuconf.CSUConf(barmodel) csu_conf.set_state_from_img(hdulist) self.logger.info('loaded CSU named: %s', csu_conf.conf_f) if self.intermediate_results: # FIXME: coordinates are in VIRT pixels self.logger.debug('create bar mask from predictions') mask = np.ones_like(hdulist[0].data) for i in itertools.chain(csu_conf.LBARS, csu_conf.RBARS): bar = csu_conf.bars[i] mask[bar.bbox().slice] = 0 self.save_intermediate_array(mask, 'mask_bars.fits') self.logger.debug('create slit mask from predictions') mask = np.zeros_like(hdulist[0].data) for slit in csu_conf.slits.values(): mask[slit.bbox().slice] = slit.idx self.save_intermediate_array(mask, 'mask_slit.fits') self.logger.debug('create slit reference mask from predictions') mask1 = np.zeros_like(hdulist[0].data) for slit in csu_conf.slits.values(): <|code_end|> using the current file's imports: import sys import math import logging import itertools import numpy as np import matplotlib.pyplot as plt import sep import astropy.units as u import astropy.wcs import skimage.filters as filt import skimage.feature as feat import numina.types.array as tarray import numina.core.query as qmod import emirdrp.instrument.constants as cons import emirdrp.requirements as reqs import emirdrp.products as prods import emirdrp.instrument.distortions as dist import emirdrp.instrument.csuconf as csuconf from scipy import ndimage as ndi from numina.array.utils import coor_to_pix_1d from numina.array.bbox import BoundingBox from numina.array.offrot import fit_offset_and_rotation from numina.array.peaks.peakdet import refine_peaks from numina.core import Requirement, Result from numina.types.qc import QC from numina.core.requirements import ObservationResultRequirement from emirdrp.core.recipe import EmirRecipe from emirdrp.core.utils import create_rot2d from emirdrp.processing.combine import basic_processing_, combine_images from emirdrp.processing.combine import process_ab, process_abba from emirdrp.instrument.csuconf import TargetType from matplotlib.patches import Ellipse from emirdrp.instrument.dtuconf import DtuConf and any relevant context from other files: # Path: emirdrp/core/recipe.py # class EmirRecipe(recipes.BaseRecipe): # """Base clase for all EMIR Recipes # # # Attributes # ---------- # logger : # recipe logger # # datamodel : EmirDataModel # # """ # logger = logging.getLogger(__name__) # datamodel = emirdrp.datamodel.EmirDataModel() # # def types_getter(self): # imgtypes = [prods.MasterBadPixelMask, # prods.MasterBias, # prods.MasterDark, # prods.MasterIntensityFlat, # prods.MasterSpectralFlat, # prods.MasterSky # ] # getters = [cor.get_corrector_p, cor.get_corrector_b, cor.get_corrector_d, # [cor.get_corrector_f, cor.get_checker], cor.get_corrector_sf, cor.get_corrector_s] # # return imgtypes, getters # # def get_filters(self): # import collections # imgtypes, getters = self.types_getter() # used_getters = [] # for rtype, getter in zip(imgtypes, getters): # self.logger.debug('get_filters, %s %s', rtype, getter) # if rtype is None: # # Unconditional # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # else: # # Search # for key, val in self.RecipeInput.stored().items(): # if isinstance(val.type, rtype): # if isinstance(getter, collections.Iterable): # used_getters.extend(getter) # else: # used_getters.append(getter) # break # else: # pass # return used_getters # # def init_filters_generic(self, rinput, getters, ins): # # with BPM, bias, dark, flat and sky # if numina.ext.gtc.check_gtc(): # self.logger.debug('running in GTC environment') # else: # self.logger.debug('running outside of GTC environment') # # meta = emirdrp.processing.info.gather_info(rinput) # self.logger.debug('obresult info') # for entry in meta['obresult']: # self.logger.debug('frame info is %s', entry) # correctors = [getter(rinput, meta, ins, self.datamodel) for getter in getters] # flow = flowmod.SerialFlow(correctors) # return flow # # def init_filters(self, rinput, ins='EMIR'): # getters = self.get_filters() # return self.init_filters_generic(rinput, getters, ins) # # def aggregate_result(self, result, rinput): # return result # # Path: emirdrp/core/utils.py # def create_rot2d(angle): # """Create 2D rotation matrix""" # ca = math.cos(angle) # sa = math.sin(angle) # return numpy.array([[ca, -sa], [sa, ca]]) # # Path: emirdrp/instrument/csuconf.py # class TargetType(enum.Enum): # """Possible targets in a slit""" # UNASSIGNED = 0 # SOURCE = 1 # REFERENCE = 2 # SKY = 3 # UNKNOWN = 4 . Output only the next line.
if slit.target_type == TargetType.REFERENCE:
Here is a snippet: <|code_start|># the tagger is global, powered by the singleton module in tweedr.ml.ark logger = logging.getLogger(__name__) def pos_tags(document): text = ' '.join(document) <|code_end|> . Write the next line using the current file imports: from tweedr.ark.java.singleton import tagger import logging and context from other files: # Path: tweedr/ark/java/singleton.py , which may include functions, classes, or code. Output only the next line.
tokens_line, tags_line = tagger.tokenize_and_tag(text)
Here is a snippet: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') <|code_end|> . Write the next line using the current file imports: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and context from other files: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' , which may include functions, classes, or code. Output only the next line.
cli_pipeline = pipeline.Pipeline(
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') cli_pipeline = pipeline.Pipeline( <|code_end|> , predict the next line using imports from the current file: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and context including class names, function names, and sometimes code from other files: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' . Output only the next line.
basic.EmptyLineFilter(),
Continue the code snippet: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') cli_pipeline = pipeline.Pipeline( basic.EmptyLineFilter(), basic.JSONParser(), basic.IgnoreMetadata(), basic.TweetStandardizer(), <|code_end|> . Use current file imports: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and context (classes, functions, or code) from other files: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' . Output only the next line.
similar.TextCounter(),
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') cli_pipeline = pipeline.Pipeline( basic.EmptyLineFilter(), basic.JSONParser(), basic.IgnoreMetadata(), basic.TweetStandardizer(), similar.TextCounter(), similar.FuzzyTextCounter(), <|code_end|> , predict the next line using imports from the current file: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and context including class names, function names, and sometimes code from other files: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' . Output only the next line.
nlp.POSTagger(),
Continue the code snippet: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') cli_pipeline = pipeline.Pipeline( basic.EmptyLineFilter(), basic.JSONParser(), basic.IgnoreMetadata(), basic.TweetStandardizer(), similar.TextCounter(), similar.FuzzyTextCounter(), nlp.POSTagger(), nlp.SequenceTagger(), nlp.DBpediaSpotter(), <|code_end|> . Use current file imports: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and context (classes, functions, or code) from other files: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' . Output only the next line.
ml.CorpusClassifier(a126730_datasource(), naive_bayes.MultinomialNB()),
Given the code snippet: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') cli_pipeline = pipeline.Pipeline( basic.EmptyLineFilter(), basic.JSONParser(), basic.IgnoreMetadata(), basic.TweetStandardizer(), similar.TextCounter(), similar.FuzzyTextCounter(), nlp.POSTagger(), nlp.SequenceTagger(), nlp.DBpediaSpotter(), <|code_end|> , generate the next line using the imports in this file: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and context (functions, classes, or occasionally code) from other files: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' . Output only the next line.
ml.CorpusClassifier(a126730_datasource(), naive_bayes.MultinomialNB()),
Predict the next line after this snippet: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') cli_pipeline = pipeline.Pipeline( basic.EmptyLineFilter(), basic.JSONParser(), basic.IgnoreMetadata(), basic.TweetStandardizer(), similar.TextCounter(), similar.FuzzyTextCounter(), nlp.POSTagger(), nlp.SequenceTagger(), nlp.DBpediaSpotter(), ml.CorpusClassifier(a126730_datasource(), naive_bayes.MultinomialNB()), <|code_end|> using the current file's imports: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and any relevant context from other files: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' . Output only the next line.
ml.CorpusClassifier(a121571_datasource(), svm.SVC(gamma=2, C=1)),
Given snippet: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') cli_pipeline = pipeline.Pipeline( basic.EmptyLineFilter(), basic.JSONParser(), basic.IgnoreMetadata(), basic.TweetStandardizer(), similar.TextCounter(), similar.FuzzyTextCounter(), nlp.POSTagger(), nlp.SequenceTagger(), nlp.DBpediaSpotter(), ml.CorpusClassifier(a126730_datasource(), naive_bayes.MultinomialNB()), ml.CorpusClassifier(a121571_datasource(), svm.SVC(gamma=2, C=1)), <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and context: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' which might include code, classes, or functions. Output only the next line.
ml.CorpusClassifier(a126728_datasource(), neighbors.KNeighborsClassifier(3)),
Given the code snippet: <|code_start|> logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description='Run tweets from STDIN through the tweedr pipeline, output to STDOUT.') parser.add_argument('-v', '--verbose', action='store_true', help='Log extra output') opts = parser.parse_args() # bump threshold down to show info=20, debug=10, and silly=5 if --verbose is set if opts.verbose: logger.setLevel('SILLY') if sys.stdin.isatty(): raise IOError('You must provide input via STDIN') cli_pipeline = pipeline.Pipeline( basic.EmptyLineFilter(), basic.JSONParser(), basic.IgnoreMetadata(), basic.TweetStandardizer(), similar.TextCounter(), similar.FuzzyTextCounter(), nlp.POSTagger(), nlp.SequenceTagger(), nlp.DBpediaSpotter(), ml.CorpusClassifier(a126730_datasource(), naive_bayes.MultinomialNB()), ml.CorpusClassifier(a121571_datasource(), svm.SVC(gamma=2, C=1)), ml.CorpusClassifier(a126728_datasource(), neighbors.KNeighborsClassifier(3)), <|code_end|> , generate the next line using the imports in this file: import argparse import sys import logging from tweedr.api import pipeline from tweedr.api.mappers import basic, similar, nlp, ml from tweedr.corpora.qcri import a126730_datasource, a121571_datasource, a126728_datasource, a122047_datasource from sklearn import linear_model, naive_bayes, neighbors, svm and context (functions, classes, or occasionally code) from other files: # Path: tweedr/api/pipeline.py # class Pipeline(object): # def __init__(self, *mappers): # def __call__(self, payload): # # Path: tweedr/api/mappers/basic.py # class EmptyLineFilter(Mapper): # class JSONParser(Mapper): # class IgnoreMetadata(Mapper): # class TweetStandardizer(Mapper): # class LineStream(Mapper): # INPUT = StringProtocol # OUTPUT = StringProtocol # INPUT = StringProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = DictProtocol # INPUT = DictProtocol # OUTPUT = TweetDictProtocol # INPUT = DictProtocol # OUTPUT = None # def __call__(self, line): # def __call__(self, line): # def __call__(self, dict_): # def __call__(self, dict_): # def __init__(self, stream): # def __call__(self, dict_): # # Path: tweedr/api/mappers/similar.py # class TextCounter(Mapper): # class FuzzyTextCounter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, dict_): # def __init__(self, threshold=0.97): # def __call__(self, dict_): # # Path: tweedr/api/mappers/nlp.py # class POSTagger(Mapper): # class SequenceTagger(Mapper): # class DBpediaSpotter(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def __init__(self): # def __call__(self, tweet): # def __init__(self): # def __call__(self, tweet): # def __init__(self, confidence=0.1, support=10): # def __call__(self, tweet): # # Path: tweedr/api/mappers/ml.py # class CorpusClassifier(Mapper): # INPUT = TweetDictProtocol # OUTPUT = TweetDictProtocol # def tokenizer(self, text): # def __init__(self, datasource, classifier): # def __call__(self, tweet): # # Path: tweedr/corpora/qcri.py # class a126730_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 1 Both people and infrastructure # 1 People: injured # 2 People: injured and dead # 12 Not damage-related # 17 Infrastructure (building, bridge, road, etc.) damaged # 47 Not specified (maybe people or infrastructure) # 58 People: dead # ''' # filepath = globfirst('**/a126730.csv', root=corpora_root) # label_column = 'people_or_infrastructure' # text_column = 'text' # # class a121571_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 46 People missing, found or seen # 130 Unknown # 137 Casualties and damage # 204 Donations of money, goods or services # 280 Information source # 436 Caution and advice # ''' # # TODO: come up with a better name # filepath = globfirst('**/a121571.csv', root=corpora_root) # label_column = 'choose_one' # text_column = 'text' # # class a126728_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 2 Discount (rebate/special offer) # 3 Blood # 3 Equipment (machine/generator/pump/etc.) # 6 Food # 7 Shelter # 11 Volunteers/work # 53 Money # 119 Other, or not specified # ''' # filepath = globfirst('**/a126728.csv', root=corpora_root) # label_column = 'type_of_donation' # text_column = 'text' # # class a122047_datasource(CSVDatasouce): # # from joplin/ # ''' # Counts: # # 3 A shelter is open or available # 27 A siren has been heard # 99 A tornado sighting/touchdown has been reported # 102 Other # 207 A tornado/thunderstorm warning has been issued or has been lifted # ''' # filepath = globfirst('**/a122047.csv', root=corpora_root) # label_column = 'type_of_advice_or_caution' # text_column = 'text' . Output only the next line.
ml.CorpusClassifier(a122047_datasource(), linear_model.LogisticRegression()),
Predict the next line after this snippet: <|code_start|> DamageClassification, TokenizedLabel, UniformSample, Label, KeywordSample, Tweet, ) ''' class BaseMixin(object): def __json__(self): '''This method serves to both clone the record (copying its values) as well as filter out the special sqlalchemy key (_sa_instance_state) ''' return dict((k, v) for k, v in self.__dict__.items() if k != '_sa_instance_state') def __unicode__(self): type_name = self.__class__.__name__ pairs = [u'%s=%s' % (k, v) for k, v in self.__json__().items()] return u'<{type_name} {pairs}>'.format(type_name=type_name, pairs=u' '.join(pairs)) def __str__(self): return unicode(self).encode('utf-8') def __repr__(self): return str(self) <|code_end|> using the current file's imports: from sqlalchemy import Column from sqlalchemy.dialects import mysql from sqlalchemy.ext.declarative import declarative_base from tweedr.models.metadata import metadata and any relevant context from other files: # Path: tweedr/models/metadata.py . Output only the next line.
Base = declarative_base(metadata=metadata, cls=BaseMixin)
Using the snippet: <|code_start|> crf_feature_functions = [ ngrams.unigrams, characters.plural, lexicons.is_transportation, lexicons.is_building, characters.capitalized, characters.numeric, ngrams.unique, lexicons.hypernyms, <|code_end|> , determine the next line of code. You have imports: from tweedr.ml.features import characters, dbpedia, lexicons, ngrams and context (class names, function names, or code) available: # Path: tweedr/ml/features/characters.py # def capitalized(document): # def plural(document): # def numeric(document): # def includes_numeric(document): # # Path: tweedr/ml/features/dbpedia.py # def get_pos(offset, document): # def features(document): # def spotlight(document, confidence=0.1, support=10): # # Path: tweedr/ml/features/lexicons.py # def is_transportation(document): # def is_building(document): # def hypernyms(document, recursive=True, depth=1): # # Path: tweedr/ml/features/ngrams.py # def unigrams(document): # def rbigrams(document): # def lbigrams(document): # def ctrigrams(document): # def unique(document): . Output only the next line.
dbpedia.features,
Predict the next line for this snippet: <|code_start|> crf_feature_functions = [ ngrams.unigrams, characters.plural, <|code_end|> with the help of current file imports: from tweedr.ml.features import characters, dbpedia, lexicons, ngrams and context from other files: # Path: tweedr/ml/features/characters.py # def capitalized(document): # def plural(document): # def numeric(document): # def includes_numeric(document): # # Path: tweedr/ml/features/dbpedia.py # def get_pos(offset, document): # def features(document): # def spotlight(document, confidence=0.1, support=10): # # Path: tweedr/ml/features/lexicons.py # def is_transportation(document): # def is_building(document): # def hypernyms(document, recursive=True, depth=1): # # Path: tweedr/ml/features/ngrams.py # def unigrams(document): # def rbigrams(document): # def lbigrams(document): # def ctrigrams(document): # def unique(document): , which may contain function names, class names, or code. Output only the next line.
lexicons.is_transportation,
Here is a snippet: <|code_start|> def main(): '''This is called by the package's console_scripts entry point "tweedr-ui" The reloader is slow and only handles python module changes. I recommend using 3rd party restarter, say, node_restarter: node_restarter **/*.py **/*.css **/*.mako 'python tweedr/cli/ui.py' ''' <|code_end|> . Write the next line using the current file imports: from bottle import run from tweedr.ui import middleware, crf and context from other files: # Path: tweedr/ui/middleware.py # def add_duration_header(app): # def call(environ, start_response): # def wrapped_start_response(status, headers): # # Path: tweedr/ui/crf.py # GLOBALS = dict(tagger=CRF.default(crf_feature_functions)) # def root(): # def index(): # def tokenized_labels_sample(): # def tagger_tag(): # def tagger_retrain(): # def serve_static_file(filepath): # def serve_templates_file(filepath): , which may include functions, classes, or code. Output only the next line.
app = middleware.add_duration_header(crf.app)
Given the code snippet: <|code_start|> def main(): '''This is called by the package's console_scripts entry point "tweedr-ui" The reloader is slow and only handles python module changes. I recommend using 3rd party restarter, say, node_restarter: node_restarter **/*.py **/*.css **/*.mako 'python tweedr/cli/ui.py' ''' <|code_end|> , generate the next line using the imports in this file: from bottle import run from tweedr.ui import middleware, crf and context (functions, classes, or occasionally code) from other files: # Path: tweedr/ui/middleware.py # def add_duration_header(app): # def call(environ, start_response): # def wrapped_start_response(status, headers): # # Path: tweedr/ui/crf.py # GLOBALS = dict(tagger=CRF.default(crf_feature_functions)) # def root(): # def index(): # def tokenized_labels_sample(): # def tagger_tag(): # def tagger_retrain(): # def serve_static_file(filepath): # def serve_templates_file(filepath): . Output only the next line.
app = middleware.add_duration_header(crf.app)
Given snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @ddt.ddt class ShellTestCase(test.TestCase): TRACE_ID = "c598094d-bbee-40b6-b317-d76003b679d3" def setUp(self): super(ShellTestCase, self).setUp() self.old_environment = os.environ.copy() def tearDown(self): super(ShellTestCase, self).tearDown() os.environ = self.old_environment def _trace_show_cmd(self, format_=None): cmd = "trace show --connection-string redis:// %s" % self.TRACE_ID return cmd if format_ is None else "%s --%s" % (cmd, format_) @mock.patch("sys.stdout", io.StringIO()) @mock.patch("osprofiler.cmd.shell.OSProfilerShell") def test_shell_main(self, mock_shell): mock_shell.side_effect = exc.CommandError("some_message") <|code_end|> , continue by predicting the next line. Consider current file imports: import io import json import os import sys import ddt from unittest import mock from osprofiler.cmd import shell from osprofiler import exc from osprofiler.tests import test and context: # Path: osprofiler/cmd/shell.py # class OSProfilerShell(object): # def __init__(self, argv): # def _get_base_parser(self): # def _append_subcommands(self, parent_parser): # def _no_project_and_domain_set(self, args): # def main(args=None): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): which might include code, classes, or functions. Output only the next line.
shell.main()
Predict the next line after this snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @ddt.ddt class ShellTestCase(test.TestCase): TRACE_ID = "c598094d-bbee-40b6-b317-d76003b679d3" def setUp(self): super(ShellTestCase, self).setUp() self.old_environment = os.environ.copy() def tearDown(self): super(ShellTestCase, self).tearDown() os.environ = self.old_environment def _trace_show_cmd(self, format_=None): cmd = "trace show --connection-string redis:// %s" % self.TRACE_ID return cmd if format_ is None else "%s --%s" % (cmd, format_) @mock.patch("sys.stdout", io.StringIO()) @mock.patch("osprofiler.cmd.shell.OSProfilerShell") def test_shell_main(self, mock_shell): <|code_end|> using the current file's imports: import io import json import os import sys import ddt from unittest import mock from osprofiler.cmd import shell from osprofiler import exc from osprofiler.tests import test and any relevant context from other files: # Path: osprofiler/cmd/shell.py # class OSProfilerShell(object): # def __init__(self, argv): # def _get_base_parser(self): # def _append_subcommands(self, parent_parser): # def _no_project_and_domain_set(self, args): # def main(args=None): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): . Output only the next line.
mock_shell.side_effect = exc.CommandError("some_message")
Given the following code snippet before the placeholder: <|code_start|># Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class BaseCommand(object): group_name = None class TraceCommands(BaseCommand): group_name = "trace" <|code_end|> , predict the next line using imports from the current file: import json import os import prettytable import graphviz from oslo_utils import encodeutils from oslo_utils import uuidutils from osprofiler.cmd import cliutils from osprofiler.drivers import base from osprofiler import exc and context including class names, function names, and sometimes code from other files: # Path: osprofiler/cmd/cliutils.py # def env(*args, **kwargs): # def arg(*args, **kwargs): # def _decorator(func): # def add_arg(func, *args, **kwargs): # # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): . Output only the next line.
@cliutils.arg("trace", help="File with trace or trace id")
Given the code snippet: <|code_start|> "only), e.g. rabbit://user:password@host:5672/") @cliutils.arg("--idle-timeout", dest="idle_timeout", type=int, default=1, help="How long to wait for the trace to finish, in seconds " "(for messaging:// driver only)") @cliutils.arg("--json", dest="use_json", action="store_true", help="show trace in JSON") @cliutils.arg("--html", dest="use_html", action="store_true", help="show trace in HTML") @cliutils.arg("--local-libs", dest="local_libs", action="store_true", help="use local static files of html in /libs/") @cliutils.arg("--dot", dest="use_dot", action="store_true", help="show trace in DOT language") @cliutils.arg("--render-dot", dest="render_dot_filename", help="filename for rendering the dot graph in pdf format") @cliutils.arg("--out", dest="file_name", help="save output in file") def show(self, args): """Display trace results in HTML, JSON or DOT format.""" if not args.conn_str: raise exc.CommandError( "You must provide connection string via" " either --connection-string or " "via env[OSPROFILER_CONNECTION_STRING]") trace = None if not uuidutils.is_uuid_like(args.trace): trace = json.load(open(args.trace)) else: try: <|code_end|> , generate the next line using the imports in this file: import json import os import prettytable import graphviz from oslo_utils import encodeutils from oslo_utils import uuidutils from osprofiler.cmd import cliutils from osprofiler.drivers import base from osprofiler import exc and context (functions, classes, or occasionally code) from other files: # Path: osprofiler/cmd/cliutils.py # def env(*args, **kwargs): # def arg(*args, **kwargs): # def _decorator(func): # def add_arg(func, *args, **kwargs): # # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): . Output only the next line.
engine = base.get_driver(args.conn_str, **args.__dict__)
Based on the snippet: <|code_start|> class TraceCommands(BaseCommand): group_name = "trace" @cliutils.arg("trace", help="File with trace or trace id") @cliutils.arg("--connection-string", dest="conn_str", default=(cliutils.env("OSPROFILER_CONNECTION_STRING")), help="Storage driver's connection string. Defaults to " "env[OSPROFILER_CONNECTION_STRING] if set") @cliutils.arg("--transport-url", dest="transport_url", help="Oslo.messaging transport URL (for messaging:// driver " "only), e.g. rabbit://user:password@host:5672/") @cliutils.arg("--idle-timeout", dest="idle_timeout", type=int, default=1, help="How long to wait for the trace to finish, in seconds " "(for messaging:// driver only)") @cliutils.arg("--json", dest="use_json", action="store_true", help="show trace in JSON") @cliutils.arg("--html", dest="use_html", action="store_true", help="show trace in HTML") @cliutils.arg("--local-libs", dest="local_libs", action="store_true", help="use local static files of html in /libs/") @cliutils.arg("--dot", dest="use_dot", action="store_true", help="show trace in DOT language") @cliutils.arg("--render-dot", dest="render_dot_filename", help="filename for rendering the dot graph in pdf format") @cliutils.arg("--out", dest="file_name", help="save output in file") def show(self, args): """Display trace results in HTML, JSON or DOT format.""" if not args.conn_str: <|code_end|> , predict the immediate next line with the help of imports: import json import os import prettytable import graphviz from oslo_utils import encodeutils from oslo_utils import uuidutils from osprofiler.cmd import cliutils from osprofiler.drivers import base from osprofiler import exc and context (classes, functions, sometimes code) from other files: # Path: osprofiler/cmd/cliutils.py # def env(*args, **kwargs): # def arg(*args, **kwargs): # def _decorator(func): # def add_arg(func, *args, **kwargs): # # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): . Output only the next line.
raise exc.CommandError(
Predict the next line for this snippet: <|code_start|># Copyright 2016 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class MessagingTestCase(test.TestCase): @mock.patch("oslo_utils.importutils.try_import") def test_init_no_oslo_messaging(self, try_import_mock): try_import_mock.return_value = None self.assertRaises( <|code_end|> with the help of current file imports: from unittest import mock from osprofiler.drivers import base from osprofiler.tests import test and context from other files: # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): , which may contain function names, class names, or code. Output only the next line.
ValueError, base.get_driver,
Here is a snippet: <|code_start|> def __enter__(self): start(self._name, info=self._info) def __exit__(self, etype, value, traceback): if etype: info = { "etype": reflection.get_class_name(etype), "message": value.args[0] if value.args else None } stop(info=info) else: stop() class _Profiler(object): def __init__(self, hmac_key, base_id=None, parent_id=None): self.hmac_key = hmac_key if not base_id: base_id = str(uuidutils.generate_uuid()) self._trace_stack = collections.deque([base_id, parent_id or base_id]) self._name = collections.deque() self._host = socket.gethostname() def get_shorten_id(self, uuid_id): """Return shorten id of a uuid that will be used in OpenTracing drivers :param uuid_id: A string of uuid that was generated by uuidutils :returns: A shorter 64-bit long id """ <|code_end|> . Write the next line using the current file imports: import collections import datetime import functools import inspect import socket import threading from oslo_utils import reflection from oslo_utils import uuidutils from osprofiler import _utils as utils from osprofiler import notifier and context from other files: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): # # Path: osprofiler/notifier.py # LOG = logging.getLogger(__name__) # def _noop_notifier(info, context=None): # def notify(info): # def get(): # def set(notifier): # def create(connection_string, *args, **kwargs): # def clear_notifier_cache(): , which may include functions, classes, or code. Output only the next line.
return format(utils.shorten_id(uuid_id), "x")
Given snippet: <|code_start|> info = info or {} info["host"] = self._host self._name.append(name) self._trace_stack.append(str(uuidutils.generate_uuid())) self._notify("%s-start" % name, info) def stop(self, info=None): """Finish latest event. Same as a start, but instead of pushing trace_id to stack it pops it. :param info: Dict with useful info. It will be send in notification. """ info = info or {} info["host"] = self._host self._notify("%s-stop" % self._name.pop(), info) self._trace_stack.pop() def _notify(self, name, info): payload = { "name": name, "base_id": self.get_base_id(), "trace_id": self.get_id(), "parent_id": self.get_parent_id(), "timestamp": datetime.datetime.utcnow().strftime( "%Y-%m-%dT%H:%M:%S.%f"), } if info: payload["info"] = info <|code_end|> , continue by predicting the next line. Consider current file imports: import collections import datetime import functools import inspect import socket import threading from oslo_utils import reflection from oslo_utils import uuidutils from osprofiler import _utils as utils from osprofiler import notifier and context: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): # # Path: osprofiler/notifier.py # LOG = logging.getLogger(__name__) # def _noop_notifier(info, context=None): # def notify(info): # def get(): # def set(notifier): # def create(connection_string, *args, **kwargs): # def clear_notifier_cache(): which might include code, classes, or functions. Output only the next line.
notifier.notify(payload)
Next line prediction: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class Redis(base.Driver): @removals.removed_kwarg("db", message="'db' parameter is deprecated " "and will be removed in future. " "Please specify 'db' in " "'connection_string' instead.") def __init__(self, connection_str, db=0, project=None, service=None, host=None, conf=cfg.CONF, **kwargs): """Redis driver for OSProfiler.""" super(Redis, self).__init__(connection_str, project=project, service=service, host=host, conf=conf, **kwargs) try: except ImportError: <|code_end|> . Use current file imports: (from urllib import parse as parser from debtcollector import removals from oslo_config import cfg from oslo_serialization import jsonutils from osprofiler.drivers import base from osprofiler import exc from redis import StrictRedis from redis.sentinel import Sentinel) and context including class names, function names, or small code snippets from other files: # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): . Output only the next line.
raise exc.CommandError(
Using the snippet: <|code_start|> class OSProfilerShell(object): def __init__(self, argv): args = self._get_base_parser().parse_args(argv) opts.set_defaults(cfg.CONF) args.func(args) def _get_base_parser(self): parser = argparse.ArgumentParser( prog="osprofiler", description=__doc__.strip(), add_help=True ) parser.add_argument("-v", "--version", action="version", version=osprofiler.__version__) self._append_subcommands(parser) return parser def _append_subcommands(self, parent_parser): subcommands = parent_parser.add_subparsers(help="<subcommands>") <|code_end|> , determine the next line of code. You have imports: import argparse import inspect import sys import osprofiler from oslo_config import cfg from osprofiler.cmd import commands from osprofiler import exc from osprofiler import opts and context (class names, function names, or code) available: # Path: osprofiler/cmd/commands.py # class BaseCommand(object): # class TraceCommands(BaseCommand): # def show(self, args): # def datetime_json_serialize(obj): # def _create_dot_graph(self, trace): # def _create_node(info): # def _create_sub_graph(root): # def list(self, args): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): # # Path: osprofiler/opts.py # _PROFILER_OPTS = [ # _enabled_opt, # _trace_sqlalchemy_opt, # _hmac_keys_opt, # _connection_string_opt, # _es_doc_type_opt, # _es_scroll_time_opt, # _es_scroll_size_opt, # _socket_timeout_opt, # _sentinel_service_name_opt, # _filter_error_trace # ] # def set_defaults(conf, enabled=None, trace_sqlalchemy=None, hmac_keys=None, # connection_string=None, es_doc_type=None, # es_scroll_time=None, es_scroll_size=None, # socket_timeout=None, sentinel_service_name=None): # def is_trace_enabled(conf=None): # def is_db_trace_enabled(conf=None): # def enable_web_trace(conf=None): # def disable_web_trace(conf=None): # def list_opts(): . Output only the next line.
for group_cls in commands.BaseCommand.__subclasses__():
Continue the code snippet: <|code_start|> subcommand_parser = group_parser.add_subparsers() for name, callback in inspect.getmembers( group_cls(), predicate=inspect.ismethod): command = name.replace("_", "-") desc = callback.__doc__ or "" help_message = desc.strip().split("\n")[0] arguments = getattr(callback, "arguments", []) command_parser = subcommand_parser.add_parser( command, help=help_message, description=desc) for (args, kwargs) in arguments: command_parser.add_argument(*args, **kwargs) command_parser.set_defaults(func=callback) def _no_project_and_domain_set(self, args): if not (args.os_project_id or (args.os_project_name and (args.os_user_domain_name or args.os_user_domain_id)) or (args.os_tenant_id or args.os_tenant_name)): return True else: return False def main(args=None): if args is None: args = sys.argv[1:] try: OSProfilerShell(args) <|code_end|> . Use current file imports: import argparse import inspect import sys import osprofiler from oslo_config import cfg from osprofiler.cmd import commands from osprofiler import exc from osprofiler import opts and context (classes, functions, or code) from other files: # Path: osprofiler/cmd/commands.py # class BaseCommand(object): # class TraceCommands(BaseCommand): # def show(self, args): # def datetime_json_serialize(obj): # def _create_dot_graph(self, trace): # def _create_node(info): # def _create_sub_graph(root): # def list(self, args): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): # # Path: osprofiler/opts.py # _PROFILER_OPTS = [ # _enabled_opt, # _trace_sqlalchemy_opt, # _hmac_keys_opt, # _connection_string_opt, # _es_doc_type_opt, # _es_scroll_time_opt, # _es_scroll_size_opt, # _socket_timeout_opt, # _sentinel_service_name_opt, # _filter_error_trace # ] # def set_defaults(conf, enabled=None, trace_sqlalchemy=None, hmac_keys=None, # connection_string=None, es_doc_type=None, # es_scroll_time=None, es_scroll_size=None, # socket_timeout=None, sentinel_service_name=None): # def is_trace_enabled(conf=None): # def is_db_trace_enabled(conf=None): # def enable_web_trace(conf=None): # def disable_web_trace(conf=None): # def list_opts(): . Output only the next line.
except exc.CommandError as e:
Here is a snippet: <|code_start|># Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Command-line interface to the OpenStack Profiler. """ class OSProfilerShell(object): def __init__(self, argv): args = self._get_base_parser().parse_args(argv) <|code_end|> . Write the next line using the current file imports: import argparse import inspect import sys import osprofiler from oslo_config import cfg from osprofiler.cmd import commands from osprofiler import exc from osprofiler import opts and context from other files: # Path: osprofiler/cmd/commands.py # class BaseCommand(object): # class TraceCommands(BaseCommand): # def show(self, args): # def datetime_json_serialize(obj): # def _create_dot_graph(self, trace): # def _create_node(info): # def _create_sub_graph(root): # def list(self, args): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): # # Path: osprofiler/opts.py # _PROFILER_OPTS = [ # _enabled_opt, # _trace_sqlalchemy_opt, # _hmac_keys_opt, # _connection_string_opt, # _es_doc_type_opt, # _es_scroll_time_opt, # _es_scroll_size_opt, # _socket_timeout_opt, # _sentinel_service_name_opt, # _filter_error_trace # ] # def set_defaults(conf, enabled=None, trace_sqlalchemy=None, hmac_keys=None, # connection_string=None, es_doc_type=None, # es_scroll_time=None, es_scroll_size=None, # socket_timeout=None, sentinel_service_name=None): # def is_trace_enabled(conf=None): # def is_db_trace_enabled(conf=None): # def enable_web_trace(conf=None): # def disable_web_trace(conf=None): # def list_opts(): , which may include functions, classes, or code. Output only the next line.
opts.set_defaults(cfg.CONF)
Given snippet: <|code_start|> if es_scroll_size is not None: conf.set_default("es_scroll_size", es_scroll_size, group=_profiler_opt_group.name) if socket_timeout is not None: conf.set_default("socket_timeout", socket_timeout, group=_profiler_opt_group.name) if sentinel_service_name is not None: conf.set_default("sentinel_service_name", sentinel_service_name, group=_profiler_opt_group.name) def is_trace_enabled(conf=None): if conf is None: conf = cfg.CONF return conf.profiler.enabled def is_db_trace_enabled(conf=None): if conf is None: conf = cfg.CONF return conf.profiler.enabled and conf.profiler.trace_sqlalchemy def enable_web_trace(conf=None): if conf is None: conf = cfg.CONF if conf.profiler.enabled: <|code_end|> , continue by predicting the next line. Consider current file imports: from oslo_config import cfg from osprofiler import web and context: # Path: osprofiler/web.py # _REQUIRED_KEYS = ("base_id", "hmac_key") # _OPTIONAL_KEYS = ("parent_id",) # X_TRACE_INFO = "X-Trace-Info" # X_TRACE_HMAC = "X-Trace-HMAC" # _ENABLED = None # _HMAC_KEYS = None # _ENABLED = False # _ENABLED = True # _HMAC_KEYS = utils.split(hmac_keys or "") # def get_trace_id_headers(): # def disable(): # def enable(hmac_keys=None): # def __init__(self, application, hmac_keys=None, enabled=False, **kwargs): # def factory(cls, global_conf, **local_conf): # def filter_(app): # def _trace_is_valid(self, trace_info): # def __call__(self, request): # class WsgiMiddleware(object): which might include code, classes, or functions. Output only the next line.
web.enable(conf.profiler.hmac_keys)
Predict the next line for this snippet: <|code_start|> def get(): """Returns notifier callable.""" return __notifier def set(notifier): """Service that are going to use profiler should set callable notifier. Callable notifier is instance of callable object, that accept exactly one argument "info". "info" - is dictionary of values that contains profiling information. """ global __notifier __notifier = notifier def create(connection_string, *args, **kwargs): """Create notifier based on specified plugin_name :param connection_string: connection string which specifies the storage driver for notifier :param args: args that will be passed to the driver's __init__ method :param kwargs: kwargs that will be passed to the driver's __init__ method :returns: Callable notifier method """ global __notifier_cache if connection_string not in __notifier_cache: try: <|code_end|> with the help of current file imports: import logging from osprofiler.drivers import base and context from other files: # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): , which may contain function names, class names, or code. Output only the next line.
driver = base.get_driver(connection_string, *args, **kwargs)
Predict the next line for this snippet: <|code_start|> LI_OSPROFILER_AGENT_ID = "F52D775B-6017-4787-8C8A-F21AE0AEC057" # API paths SESSIONS_PATH = "api/v1/sessions" CURRENT_SESSIONS_PATH = "api/v1/sessions/current" EVENTS_INGEST_PATH = "api/v1/events/ingest/%s" % LI_OSPROFILER_AGENT_ID QUERY_EVENTS_BASE_PATH = "api/v1/events" def __init__(self, host, username, password, api_port=9000, api_ssl_port=9543, query_timeout=60000): self._host = host self._username = username self._password = password self._api_port = api_port self._api_ssl_port = api_ssl_port self._query_timeout = query_timeout self._session = requests.Session() self._session_id = None def _build_base_url(self, scheme): proto_str = "%s://" % scheme host_str = ("[%s]" % self._host if netaddr.valid_ipv6(self._host) else self._host) port_str = ":%d" % (self._api_ssl_port if scheme == "https" else self._api_port) return proto_str + host_str + port_str def _check_response(self, resp): if resp.status_code == 440: <|code_end|> with the help of current file imports: import json import logging as log import netaddr import requests from urllib import parse as urlparse from oslo_concurrency.lockutils import synchronized from osprofiler.drivers import base from osprofiler import exc and context from other files: # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): , which may contain function names, class names, or code. Output only the next line.
raise exc.LogInsightLoginTimeout()
Given snippet: <|code_start|># Copyright (c) 2016 VMware, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @ddt.ddt class LogInsightDriverTestCase(test.TestCase): BASE_ID = "8d28af1e-acc0-498c-9890-6908e33eff5f" def setUp(self): super(LogInsightDriverTestCase, self).setUp() <|code_end|> , continue by predicting the next line. Consider current file imports: import json import ddt from unittest import mock from osprofiler.drivers import loginsight from osprofiler import exc from osprofiler.tests import test and context: # Path: osprofiler/drivers/loginsight.py # LOG = log.getLogger(__name__) # LI_OSPROFILER_AGENT_ID = "F52D775B-6017-4787-8C8A-F21AE0AEC057" # SESSIONS_PATH = "api/v1/sessions" # CURRENT_SESSIONS_PATH = "api/v1/sessions/current" # EVENTS_INGEST_PATH = "api/v1/events/ingest/%s" % LI_OSPROFILER_AGENT_ID # QUERY_EVENTS_BASE_PATH = "api/v1/events" # class LogInsightDriver(base.Driver): # class LogInsightClient(object): # def __init__( # self, connection_str, project=None, service=None, host=None, # **kwargs): # def get_name(cls): # def notify(self, info): # def _create_field(name, content): # def get_report(self, base_id): # def __init__(self, host, username, password, api_port=9000, # api_ssl_port=9543, query_timeout=60000): # def _build_base_url(self, scheme): # def _check_response(self, resp): # def _send_request( # self, method, scheme, path, headers=None, body=None, params=None): # def _get_auth_header(self): # def _trunc_session_id(self): # def _is_current_session_active(self): # def login(self): # def send_event(self, event): # def query_events(self, params): # def _query_events(): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): which might include code, classes, or functions. Output only the next line.
self._client = mock.Mock(spec=loginsight.LogInsightClient)
Given the following code snippet before the placeholder: <|code_start|> self._driver.get_report(self.BASE_ID) self._client.query_events.assert_called_once_with({"base_id": self.BASE_ID}) append_results.assert_has_calls( [mock.call(start_trace["trace_id"], start_trace["parent_id"], start_trace["name"], start_trace["project"], start_trace["service"], start_trace["info"]["host"], start_trace["timestamp"], start_trace), mock.call(stop_trace["trace_id"], stop_trace["parent_id"], stop_trace["name"], stop_trace["project"], stop_trace["service"], stop_trace["info"]["host"], stop_trace["timestamp"], stop_trace) ]) parse_results.assert_called_once_with() class LogInsightClientTestCase(test.TestCase): def setUp(self): super(LogInsightClientTestCase, self).setUp() self._host = "localhost" self._username = "username" self._password = "password" self._client = loginsight.LogInsightClient( self._host, self._username, self._password) self._client._session_id = "4ff800d1-3175-4b49-9209-39714ea56416" def test_check_response_login_timeout(self): resp = mock.Mock(status_code=440) self.assertRaises( <|code_end|> , predict the next line using imports from the current file: import json import ddt from unittest import mock from osprofiler.drivers import loginsight from osprofiler import exc from osprofiler.tests import test and context including class names, function names, and sometimes code from other files: # Path: osprofiler/drivers/loginsight.py # LOG = log.getLogger(__name__) # LI_OSPROFILER_AGENT_ID = "F52D775B-6017-4787-8C8A-F21AE0AEC057" # SESSIONS_PATH = "api/v1/sessions" # CURRENT_SESSIONS_PATH = "api/v1/sessions/current" # EVENTS_INGEST_PATH = "api/v1/events/ingest/%s" % LI_OSPROFILER_AGENT_ID # QUERY_EVENTS_BASE_PATH = "api/v1/events" # class LogInsightDriver(base.Driver): # class LogInsightClient(object): # def __init__( # self, connection_str, project=None, service=None, host=None, # **kwargs): # def get_name(cls): # def notify(self, info): # def _create_field(name, content): # def get_report(self, base_id): # def __init__(self, host, username, password, api_port=9000, # api_ssl_port=9543, query_timeout=60000): # def _build_base_url(self, scheme): # def _check_response(self, resp): # def _send_request( # self, method, scheme, path, headers=None, body=None, params=None): # def _get_auth_header(self): # def _trunc_session_id(self): # def _is_current_session_active(self): # def login(self): # def send_event(self, event): # def query_events(self, params): # def _query_events(): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): . Output only the next line.
exc.LogInsightLoginTimeout, self._client._check_response, resp)
Next line prediction: <|code_start|> ) parsed_url = parser.urlparse(connection_str) cfg = { "local_agent": { "reporting_host": parsed_url.hostname, "reporting_port": parsed_url.port, } } # Initialize tracer for each profiler service_name = "{}-{}".format(project, service) config = jaeger_client.Config(cfg, service_name=service_name) self.tracer = config.initialize_tracer() self.spans = collections.deque() @classmethod def get_name(cls): return "jaeger" def notify(self, payload): if payload["name"].endswith("start"): timestamp = datetime.datetime.strptime(payload["timestamp"], "%Y-%m-%dT%H:%M:%S.%f") epoch = datetime.datetime.utcfromtimestamp(0) start_time = (timestamp - epoch).total_seconds() # Create parent span child_of = self.jaeger_client.SpanContext( <|code_end|> . Use current file imports: (import collections import datetime import time import jaeger_client from urllib import parse as parser from oslo_config import cfg from oslo_serialization import jsonutils from osprofiler import _utils as utils from osprofiler.drivers import base from osprofiler import exc) and context including class names, function names, or small code snippets from other files: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): # # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): . Output only the next line.
trace_id=utils.shorten_id(payload["base_id"]),
Given snippet: <|code_start|># Copyright 2018 Fujitsu Ltd. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class Jaeger(base.Driver): def __init__(self, connection_str, project=None, service=None, host=None, conf=cfg.CONF, **kwargs): """Jaeger driver for OSProfiler.""" super(Jaeger, self).__init__(connection_str, project=project, service=service, host=host, conf=conf, **kwargs) try: self.jaeger_client = jaeger_client except ImportError: <|code_end|> , continue by predicting the next line. Consider current file imports: import collections import datetime import time import jaeger_client from urllib import parse as parser from oslo_config import cfg from oslo_serialization import jsonutils from osprofiler import _utils as utils from osprofiler.drivers import base from osprofiler import exc and context: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): # # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): which might include code, classes, or functions. Output only the next line.
raise exc.CommandError(
Here is a snippet: <|code_start|># a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Trace keys that are required or optional, any other # keys that are present will cause the trace to be rejected... _REQUIRED_KEYS = ("base_id", "hmac_key") _OPTIONAL_KEYS = ("parent_id",) #: Http header that will contain the needed traces data. X_TRACE_INFO = "X-Trace-Info" #: Http header that will contain the traces data hmac (that will be validated). X_TRACE_HMAC = "X-Trace-HMAC" def get_trace_id_headers(): """Adds the trace id headers (and any hmac) into provided dictionary.""" p = profiler.get() if p and p.hmac_key: data = {"base_id": p.get_base_id(), "parent_id": p.get_id()} <|code_end|> . Write the next line using the current file imports: import webob.dec from osprofiler import _utils as utils from osprofiler import profiler and context from other files: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): # # Path: osprofiler/profiler.py # def clean(): # def _ensure_no_multiple_traced(traceable_attrs): # def init(hmac_key, base_id=None, parent_id=None): # def get(): # def start(name, info=None): # def stop(info=None): # def trace(name, info=None, hide_args=False, hide_result=True, # allow_multiple_trace=True): # def decorator(f): # def wrapper(*args, **kwargs): # def trace_cls(name, info=None, hide_args=False, hide_result=True, # trace_private=False, allow_multiple_trace=True, # trace_class_methods=False, trace_static_methods=False): # def trace_checker(attr_name, to_be_wrapped): # def decorator(cls): # def __init__(cls, cls_name, bases, attrs): # def __init__(self, name, info=None): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def __init__(self, hmac_key, base_id=None, parent_id=None): # def get_shorten_id(self, uuid_id): # def get_base_id(self): # def get_parent_id(self): # def get_id(self): # def start(self, name, info=None): # def stop(self, info=None): # def _notify(self, name, info): # class TracedMeta(type): # class Trace(object): # class _Profiler(object): , which may include functions, classes, or code. Output only the next line.
pack = utils.signed_pack(data, p.hmac_key)
Given the following code snippet before the placeholder: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Trace keys that are required or optional, any other # keys that are present will cause the trace to be rejected... _REQUIRED_KEYS = ("base_id", "hmac_key") _OPTIONAL_KEYS = ("parent_id",) #: Http header that will contain the needed traces data. X_TRACE_INFO = "X-Trace-Info" #: Http header that will contain the traces data hmac (that will be validated). X_TRACE_HMAC = "X-Trace-HMAC" def get_trace_id_headers(): """Adds the trace id headers (and any hmac) into provided dictionary.""" <|code_end|> , predict the next line using imports from the current file: import webob.dec from osprofiler import _utils as utils from osprofiler import profiler and context including class names, function names, and sometimes code from other files: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): # # Path: osprofiler/profiler.py # def clean(): # def _ensure_no_multiple_traced(traceable_attrs): # def init(hmac_key, base_id=None, parent_id=None): # def get(): # def start(name, info=None): # def stop(info=None): # def trace(name, info=None, hide_args=False, hide_result=True, # allow_multiple_trace=True): # def decorator(f): # def wrapper(*args, **kwargs): # def trace_cls(name, info=None, hide_args=False, hide_result=True, # trace_private=False, allow_multiple_trace=True, # trace_class_methods=False, trace_static_methods=False): # def trace_checker(attr_name, to_be_wrapped): # def decorator(cls): # def __init__(cls, cls_name, bases, attrs): # def __init__(self, name, info=None): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def __init__(self, hmac_key, base_id=None, parent_id=None): # def get_shorten_id(self, uuid_id): # def get_base_id(self): # def get_parent_id(self): # def get_id(self): # def start(self, name, info=None): # def stop(self, info=None): # def _notify(self, name, info): # class TracedMeta(type): # class Trace(object): # class _Profiler(object): . Output only the next line.
p = profiler.get()
Using the snippet: <|code_start|> data = info.copy() base_id = data.pop("base_id", None) timestamp = data.pop("timestamp", None) parent_id = data.pop("parent_id", None) trace_id = data.pop("trace_id", None) project = data.pop("project", self.project) host = data.pop("host", self.host) service = data.pop("service", self.service) name = data.pop("name", None) try: ins = self._data_table.insert().values( timestamp=timestamp, base_id=base_id, parent_id=parent_id, trace_id=trace_id, project=project, service=service, host=host, name=name, data=jsonutils.dumps(data) ) self._conn.execute(ins) except Exception: LOG.exception("Can not store osprofiler tracepoint {} " "(base_id {})".format(trace_id, base_id)) def list_traces(self, fields=None): try: except ImportError: <|code_end|> , determine the next line of code. You have imports: import logging from oslo_serialization import jsonutils from osprofiler.drivers import base from osprofiler import exc from sqlalchemy import create_engine from sqlalchemy import Table, MetaData, Column from sqlalchemy import String, JSON, Integer from sqlalchemy.sql import select from sqlalchemy.sql import select and context (class names, function names, or code) available: # Path: osprofiler/drivers/base.py # LOG = logging.getLogger(__name__) # def get_driver(connection_string, *args, **kwargs): # def __init__(self, connection_str, project=None, service=None, host=None, # **kwargs): # def notify(self, info, **kwargs): # def get_report(self, base_id): # def get_name(cls): # def list_traces(self, fields=None): # def list_error_traces(self): # def _build_tree(nodes): # def _append_results(self, trace_id, parent_id, name, project, service, # host, timestamp, raw_payload=None): # def _parse_results(self): # def msec(dt): # class Driver(object): # # Path: osprofiler/exc.py # class CommandError(Exception): # class LogInsightAPIError(Exception): # class LogInsightLoginTimeout(Exception): # def __init__(self, message=None): # def __str__(self): . Output only the next line.
raise exc.CommandError(
Here is a snippet: <|code_start|>def add_tracing(sqlalchemy, engine, name, hide_result=True): """Add tracing to all sqlalchemy calls.""" if not _DISABLED: sqlalchemy.event.listen(engine, "before_cursor_execute", _before_cursor_execute(name)) sqlalchemy.event.listen( engine, "after_cursor_execute", _after_cursor_execute(hide_result=hide_result) ) sqlalchemy.event.listen(engine, "handle_error", handle_error) @contextlib.contextmanager def wrap_session(sqlalchemy, sess): with sess as s: if not getattr(s.bind, "traced", False): add_tracing(sqlalchemy, s.bind, "db") s.bind.traced = True yield s def _before_cursor_execute(name): """Add listener that will send trace info before query is executed.""" def handler(conn, cursor, statement, params, context, executemany): info = {"db": { "statement": statement, "params": params} } <|code_end|> . Write the next line using the current file imports: import contextlib import logging as log from oslo_utils import reflection from osprofiler import profiler and context from other files: # Path: osprofiler/profiler.py # def clean(): # def _ensure_no_multiple_traced(traceable_attrs): # def init(hmac_key, base_id=None, parent_id=None): # def get(): # def start(name, info=None): # def stop(info=None): # def trace(name, info=None, hide_args=False, hide_result=True, # allow_multiple_trace=True): # def decorator(f): # def wrapper(*args, **kwargs): # def trace_cls(name, info=None, hide_args=False, hide_result=True, # trace_private=False, allow_multiple_trace=True, # trace_class_methods=False, trace_static_methods=False): # def trace_checker(attr_name, to_be_wrapped): # def decorator(cls): # def __init__(cls, cls_name, bases, attrs): # def __init__(self, name, info=None): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def __init__(self, hmac_key, base_id=None, parent_id=None): # def get_shorten_id(self, uuid_id): # def get_base_id(self): # def get_parent_id(self): # def get_id(self): # def start(self, name, info=None): # def stop(self, info=None): # def _notify(self, name, info): # class TracedMeta(type): # class Trace(object): # class _Profiler(object): , which may include functions, classes, or code. Output only the next line.
profiler.start(name, info=info)
Here is a snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. LOG = logging.getLogger(__name__) def get_driver(connection_string, *args, **kwargs): """Create driver's instance according to specified connection string""" # NOTE(ayelistratov) Backward compatibility with old Messaging notation # Remove after patching all OS services # NOTE(ishakhat) Raise exception when ParsedResult.scheme is empty if "://" not in connection_string: connection_string += "://" parsed_connection = urlparse.urlparse(connection_string) LOG.debug("String %s looks like a connection string, trying it.", connection_string) backend = parsed_connection.scheme # NOTE(toabctl): To be able to use the connection_string for as sqlalchemy # connection string, transform the backend to the correct driver # See https://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls if backend in ["mysql", "mysql+pymysql", "mysql+mysqldb", "postgresql", "postgresql+psycopg2"]: backend = "sqlalchemy" <|code_end|> . Write the next line using the current file imports: import datetime import logging from urllib import parse as urlparse from osprofiler import _utils and context from other files: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): , which may include functions, classes, or code. Output only the next line.
for driver in _utils.itersubclasses(Driver):
Predict the next line for this snippet: <|code_start|> class JaegerTestCase(test.TestCase): def setUp(self): super(JaegerTestCase, self).setUp() self.payload_start = { "name": "api-start", "base_id": "4e3e0ec6-2938-40b1-8504-09eb1d4b0dee", "trace_id": "1c089ea8-28fe-4f3d-8c00-f6daa2bc32f1", "parent_id": "e2715537-3d1c-4f0c-b3af-87355dc5fc5b", "timestamp": "2018-05-03T04:31:51.781381", "info": { "host": "test" } } self.payload_stop = { "name": "api-stop", "base_id": "4e3e0ec6-2938-40b1-8504-09eb1d4b0dee", "trace_id": "1c089ea8-28fe-4f3d-8c00-f6daa2bc32f1", "parent_id": "e2715537-3d1c-4f0c-b3af-87355dc5fc5b", "timestamp": "2018-05-03T04:31:51.781381", "info": { "host": "test", "function": { "result": 1 } } } <|code_end|> with the help of current file imports: from unittest import mock from osprofiler.drivers import jaeger from osprofiler.tests import test and context from other files: # Path: osprofiler/drivers/jaeger.py # class Jaeger(base.Driver): # def __init__(self, connection_str, project=None, service=None, host=None, # conf=cfg.CONF, **kwargs): # def get_name(cls): # def notify(self, payload): # def get_report(self, base_id): # def list_traces(self, fields=None): # def list_error_traces(self): # def create_span_tags(self, payload): # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): , which may contain function names, class names, or code. Output only the next line.
self.driver = jaeger.Jaeger("jaeger://127.0.0.1:6831",
Next line prediction: <|code_start|># Copyright 2016 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class MongoDBParserTestCase(test.TestCase): def setUp(self): super(MongoDBParserTestCase, self).setUp() <|code_end|> . Use current file imports: (from unittest import mock from osprofiler.drivers.mongodb import MongoDB from osprofiler.tests import test) and context including class names, function names, or small code snippets from other files: # Path: osprofiler/drivers/mongodb.py # class MongoDB(base.Driver): # def __init__(self, connection_str, db_name="osprofiler", project=None, # service=None, host=None, **kwargs): # """MongoDB driver for OSProfiler.""" # # super(MongoDB, self).__init__(connection_str, project=project, # service=service, host=host, **kwargs) # try: # from pymongo import MongoClient # except ImportError: # raise exc.CommandError( # "To use OSProfiler with MongoDB driver, " # "please install `pymongo` library. " # "To install with pip:\n `pip install pymongo`.") # # client = MongoClient(self.connection_str, connect=False) # self.db = client[db_name] # # @classmethod # def get_name(cls): # return "mongodb" # # def notify(self, info): # """Send notifications to MongoDB. # # :param info: Contains information about trace element. # In payload dict there are always 3 ids: # "base_id" - uuid that is common for all notifications # related to one trace. Used to simplify # retrieving of all trace elements from # MongoDB. # "parent_id" - uuid of parent element in trace # "trace_id" - uuid of current element in trace # # With parent_id and trace_id it's quite simple to build # tree of trace elements, which simplify analyze of trace. # # """ # data = info.copy() # data["project"] = self.project # data["service"] = self.service # self.db.profiler.insert_one(data) # # if (self.filter_error_trace # and data.get("info", {}).get("etype") is not None): # self.notify_error_trace(data) # # def notify_error_trace(self, data): # """Store base_id and timestamp of error trace to a separate db.""" # self.db.profiler_error.update( # {"base_id": data["base_id"]}, # {"base_id": data["base_id"], "timestamp": data["timestamp"]}, # upsert=True # ) # # def list_traces(self, fields=None): # """Query all traces from the storage. # # :param fields: Set of trace fields to return. Defaults to 'base_id' # and 'timestamp' # :return List of traces, where each trace is a dictionary containing # at least `base_id` and `timestamp`. # """ # fields = set(fields or self.default_trace_fields) # ids = self.db.profiler.find({}).distinct("base_id") # out_format = {"base_id": 1, "timestamp": 1, "_id": 0} # out_format.update({i: 1 for i in fields}) # return [self.db.profiler.find( # {"base_id": i}, out_format).sort("timestamp")[0] for i in ids] # # def list_error_traces(self): # """Returns all traces that have error/exception.""" # out_format = {"base_id": 1, "timestamp": 1, "_id": 0} # return self.db.profiler_error.find({}, out_format) # # def get_report(self, base_id): # """Retrieves and parses notification from MongoDB. # # :param base_id: Base id of trace elements. # """ # for n in self.db.profiler.find({"base_id": base_id}, {"_id": 0}): # trace_id = n["trace_id"] # parent_id = n["parent_id"] # name = n["name"] # project = n["project"] # service = n["service"] # host = n["info"]["host"] # timestamp = n["timestamp"] # # self._append_results(trace_id, parent_id, name, project, service, # host, timestamp, n) # # return self._parse_results() # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): . Output only the next line.
self.mongodb = MongoDB("mongodb://localhost")
Next line prediction: <|code_start|># License for the specific language governing permissions and limitations # under the License. def dummy_app(environ, response): res = webob_response.Response() return res(environ, response) class WebTestCase(test.TestCase): def setUp(self): super(WebTestCase, self).setUp() profiler.clean() self.addCleanup(profiler.clean) def test_get_trace_id_headers_no_hmac(self): profiler.init(None, base_id="y", parent_id="z") headers = web.get_trace_id_headers() self.assertEqual(headers, {}) def test_get_trace_id_headers(self): profiler.init("key", base_id="y", parent_id="z") headers = web.get_trace_id_headers() self.assertEqual(sorted(headers.keys()), sorted(["X-Trace-Info", "X-Trace-HMAC"])) <|code_end|> . Use current file imports: (from unittest import mock from webob import response as webob_response from osprofiler import _utils as utils from osprofiler import profiler from osprofiler.tests import test from osprofiler import web) and context including class names, function names, or small code snippets from other files: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): # # Path: osprofiler/profiler.py # def clean(): # def _ensure_no_multiple_traced(traceable_attrs): # def init(hmac_key, base_id=None, parent_id=None): # def get(): # def start(name, info=None): # def stop(info=None): # def trace(name, info=None, hide_args=False, hide_result=True, # allow_multiple_trace=True): # def decorator(f): # def wrapper(*args, **kwargs): # def trace_cls(name, info=None, hide_args=False, hide_result=True, # trace_private=False, allow_multiple_trace=True, # trace_class_methods=False, trace_static_methods=False): # def trace_checker(attr_name, to_be_wrapped): # def decorator(cls): # def __init__(cls, cls_name, bases, attrs): # def __init__(self, name, info=None): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def __init__(self, hmac_key, base_id=None, parent_id=None): # def get_shorten_id(self, uuid_id): # def get_base_id(self): # def get_parent_id(self): # def get_id(self): # def start(self, name, info=None): # def stop(self, info=None): # def _notify(self, name, info): # class TracedMeta(type): # class Trace(object): # class _Profiler(object): # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): # # Path: osprofiler/web.py # _REQUIRED_KEYS = ("base_id", "hmac_key") # _OPTIONAL_KEYS = ("parent_id",) # X_TRACE_INFO = "X-Trace-Info" # X_TRACE_HMAC = "X-Trace-HMAC" # _ENABLED = None # _HMAC_KEYS = None # _ENABLED = False # _ENABLED = True # _HMAC_KEYS = utils.split(hmac_keys or "") # def get_trace_id_headers(): # def disable(): # def enable(hmac_keys=None): # def __init__(self, application, hmac_keys=None, enabled=False, **kwargs): # def factory(cls, global_conf, **local_conf): # def filter_(app): # def _trace_is_valid(self, trace_info): # def __call__(self, request): # class WsgiMiddleware(object): . Output only the next line.
trace_info = utils.signed_unpack(headers["X-Trace-Info"],
Continue the code snippet: <|code_start|># Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. def dummy_app(environ, response): res = webob_response.Response() return res(environ, response) class WebTestCase(test.TestCase): def setUp(self): super(WebTestCase, self).setUp() <|code_end|> . Use current file imports: from unittest import mock from webob import response as webob_response from osprofiler import _utils as utils from osprofiler import profiler from osprofiler.tests import test from osprofiler import web and context (classes, functions, or code) from other files: # Path: osprofiler/_utils.py # def split(text, strip=True): # def binary_encode(text, encoding="utf-8"): # def binary_decode(data, encoding="utf-8"): # def generate_hmac(data, hmac_key): # def signed_pack(data, hmac_key): # def signed_unpack(data, hmac_data, hmac_keys): # def itersubclasses(cls, _seen=None): # def import_modules_from_package(package): # def shorten_id(span_id): # # Path: osprofiler/profiler.py # def clean(): # def _ensure_no_multiple_traced(traceable_attrs): # def init(hmac_key, base_id=None, parent_id=None): # def get(): # def start(name, info=None): # def stop(info=None): # def trace(name, info=None, hide_args=False, hide_result=True, # allow_multiple_trace=True): # def decorator(f): # def wrapper(*args, **kwargs): # def trace_cls(name, info=None, hide_args=False, hide_result=True, # trace_private=False, allow_multiple_trace=True, # trace_class_methods=False, trace_static_methods=False): # def trace_checker(attr_name, to_be_wrapped): # def decorator(cls): # def __init__(cls, cls_name, bases, attrs): # def __init__(self, name, info=None): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def __init__(self, hmac_key, base_id=None, parent_id=None): # def get_shorten_id(self, uuid_id): # def get_base_id(self): # def get_parent_id(self): # def get_id(self): # def start(self, name, info=None): # def stop(self, info=None): # def _notify(self, name, info): # class TracedMeta(type): # class Trace(object): # class _Profiler(object): # # Path: osprofiler/tests/test.py # class TestCase(testcase.TestCase): # class FunctionalTestCase(TestCase): # def setUp(self): # # Path: osprofiler/web.py # _REQUIRED_KEYS = ("base_id", "hmac_key") # _OPTIONAL_KEYS = ("parent_id",) # X_TRACE_INFO = "X-Trace-Info" # X_TRACE_HMAC = "X-Trace-HMAC" # _ENABLED = None # _HMAC_KEYS = None # _ENABLED = False # _ENABLED = True # _HMAC_KEYS = utils.split(hmac_keys or "") # def get_trace_id_headers(): # def disable(): # def enable(hmac_keys=None): # def __init__(self, application, hmac_keys=None, enabled=False, **kwargs): # def factory(cls, global_conf, **local_conf): # def filter_(app): # def _trace_is_valid(self, trace_info): # def __call__(self, request): # class WsgiMiddleware(object): . Output only the next line.
profiler.clean()