Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> social_auth = Blueprint('social', __name__) @social_auth.route('/login/<string:backend>/', methods=['GET', 'POST']) @strategy('social.complete') def auth(backend): return do_auth(g.strategy) @social_auth.route('/complete/<string:backend>/', methods=['GET', 'POST']) @strategy('social.complete') def complete(backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(g.strategy, login=lambda strat, user: login_user(user), user=g.user, *args, **kwargs) @social_auth.route('/disconnect/<string:backend>/', methods=['POST']) <|code_end|> with the help of current file imports: from flask import g, Blueprint from flask.ext.login import login_user from social.actions import do_auth, do_complete, do_disconnect from social.apps.flask_app.utils import strategy and context from other files: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/flask_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = url_for(uri, backend=backend) # g.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(backend, *args, **kwargs) # return wrapper # return decorator , which may contain function names, class names, or code. Output only the next line.
@social_auth.route('/disconnect/<string:backend>/<string:association_id>/',
Given the following code snippet before the placeholder: <|code_start|> social_auth = Blueprint('social', __name__) @social_auth.route('/login/<string:backend>/', methods=['GET', 'POST']) @strategy('social.complete') def auth(backend): return do_auth(g.strategy) @social_auth.route('/complete/<string:backend>/', methods=['GET', 'POST']) @strategy('social.complete') def complete(backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(g.strategy, login=lambda strat, user: login_user(user), user=g.user, *args, **kwargs) @social_auth.route('/disconnect/<string:backend>/', methods=['POST']) <|code_end|> , predict the next line using imports from the current file: from flask import g, Blueprint from flask.ext.login import login_user from social.actions import do_auth, do_complete, do_disconnect from social.apps.flask_app.utils import strategy and context including class names, function names, and sometimes code from other files: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/flask_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = url_for(uri, backend=backend) # g.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(backend, *args, **kwargs) # return wrapper # return decorator . Output only the next line.
@social_auth.route('/disconnect/<string:backend>/<string:association_id>/',
Next line prediction: <|code_start|> social_auth = Blueprint('social', __name__) @social_auth.route('/login/<string:backend>/', methods=['GET', 'POST']) @strategy('social.complete') def auth(backend): return do_auth(g.strategy) @social_auth.route('/complete/<string:backend>/', methods=['GET', 'POST']) @strategy('social.complete') def complete(backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(g.strategy, login=lambda strat, user: login_user(user), user=g.user, *args, **kwargs) @social_auth.route('/disconnect/<string:backend>/', methods=['POST']) <|code_end|> . Use current file imports: (from flask import g, Blueprint from flask.ext.login import login_user from social.actions import do_auth, do_complete, do_disconnect from social.apps.flask_app.utils import strategy) and context including class names, function names, or small code snippets from other files: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/flask_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = url_for(uri, backend=backend) # g.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(backend, *args, **kwargs) # return wrapper # return decorator . Output only the next line.
@social_auth.route('/disconnect/<string:backend>/<string:association_id>/',
Predict the next line for this snippet: <|code_start|> return True @classmethod def changed(cls, user): """The given user instance is ready to be saved""" raise NotImplementedError('Implement in subclass') @classmethod def get_username(cls, user): """Return the username for given user""" raise NotImplementedError('Implement in subclass') @classmethod def user_model(cls): """Return the user model""" raise NotImplementedError('Implement in subclass') @classmethod def username_max_length(cls): """Return the max length for username""" raise NotImplementedError('Implement in subclass') @classmethod def clean_username(cls, value): return CLEAN_USERNAME_REGEX.sub('', value) @classmethod def allowed_to_disconnect(cls, user, backend_name, association_id=None): """Return if it's safe to disconnect the social account for the given user""" <|code_end|> with the help of current file imports: import re import time import base64 from datetime import datetime, timedelta from openid.association import Association as OpenIdAssociation from social.backends.utils import get_backend and context from other files: # Path: social/backends/utils.py # def get_backend(backends, name, *args, **kwargs): # """Returns a backend by name. Backends are stored in the BACKENDSCACHE # cache dict. If not found, each of the modules referenced in # AUTHENTICATION_BACKENDS is imported and checked for a BACKENDS # definition. If the named backend is found in the module's BACKENDS # definition, it's then stored in the cache for future access. # """ # try: # # Cached backend which has previously been discovered # return BACKENDSCACHE[name] # except KeyError: # # Reload BACKENDS to ensure a missing backend hasn't been missed # load_backends(backends, force_load=True) # try: # return BACKENDSCACHE[name] # except KeyError: # return None , which may contain function names, class names, or code. Output only the next line.
raise NotImplementedError('Implement in subclass')
Given snippet: <|code_start|># coding=utf-8 sys.path.append('..') manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db': db, 'models': models, 'user': User, 'auth': UserSocialAuth <|code_end|> , continue by predicting the next line. Consider current file imports: import sys from flask_script import Server, Manager, Shell from social.apps.flask_app.models import User, UserSocialAuth from flask_reveal import app, db, models and context: # Path: social/apps/flask_app/models.py # class User(Document, UserMixin): # username = StringField(max_length=200) # email = StringField(max_length=200) # active = BooleanField(default=True) # # def is_active(self): # return self.active # # class UserSocialAuth(Document, MongoengineUserMixin): # #id = StringField(primary_key=True) # user = ReferenceField(User, dbref=True) # provider = StringField(max_length=32) # uid = StringField(max_length=255) # extra_data = DictField() # meta = { # 'indexes': ['uid'] # } # # @classmethod # def username_max_length(cls): # return User.username.max_length # # @classmethod # def user_model(cls): # return User # # @classmethod # def _del_session(cls, qs): # session.clear() # #session.pop(username, None) which might include code, classes, or functions. Output only the next line.
}))
Here is a snippet: <|code_start|># coding=utf-8 sys.path.append('..') manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db': db, <|code_end|> . Write the next line using the current file imports: import sys from flask_script import Server, Manager, Shell from social.apps.flask_app.models import User, UserSocialAuth from flask_reveal import app, db, models and context from other files: # Path: social/apps/flask_app/models.py # class User(Document, UserMixin): # username = StringField(max_length=200) # email = StringField(max_length=200) # active = BooleanField(default=True) # # def is_active(self): # return self.active # # class UserSocialAuth(Document, MongoengineUserMixin): # #id = StringField(primary_key=True) # user = ReferenceField(User, dbref=True) # provider = StringField(max_length=32) # uid = StringField(max_length=255) # extra_data = DictField() # meta = { # 'indexes': ['uid'] # } # # @classmethod # def username_max_length(cls): # return User.username.max_length # # @classmethod # def user_model(cls): # return User # # @classmethod # def _del_session(cls, qs): # session.clear() # #session.pop(username, None) , which may include functions, classes, or code. Output only the next line.
'models': models,
Predict the next line for this snippet: <|code_start|> def backends(): """Load Social Auth current user data to context under the key 'backends'. Will return the output of social.backends.utils.user_backends_data.""" id = session.get('user_id', None) provider = session.get('social_auth_last_login_backend', None) storage = get_helper('STORAGE', do_import=True) try: username = storage.user.get_name(id) except: username = None return { 'backends': user_backends_data(g.user, get_helper('AUTHENTICATION_BACKENDS'), storage), 'session': {'username':username, 'provider':provider} <|code_end|> with the help of current file imports: from flask import g, request, session from social.backends.utils import user_backends_data from social.apps.flask_app.utils import get_helper from social.utils import module_member and context from other files: # Path: social/backends/utils.py # def user_backends_data(user, backends, storage): # """ # Will return backends data for given user, the return value will have the # following keys: # associated: UserSocialAuth model instances for currently associated # accounts # not_associated: Not associated (yet) backend names # backends: All backend names. # # If user is not authenticated, then 'associated' list is empty, and there's # no difference between 'not_associated' and 'backends'. # """ # available = list(load_backends(backends).keys()) # values = {'associated': [], # 'not_associated': available, # 'backends': available} # if user_is_authenticated(user): # associated = storage.user.get_social_auth_for_user(user) # not_associated = list(set(available) - set(associated.provider)) # # set(associated.provider for assoc in associated)) # values['associated'] = associated # values['not_associated'] = not_associated # return values # # Path: social/apps/flask_app/utils.py # def get_helper(name, do_import=False): # config = current_app.config.get(setting_name(name), # DEFAULTS.get(name, None)) # return do_import and module_member(config) or config # # Path: social/utils.py # def module_member(name): # mod, member = name.rsplit('.', 1) # module = import_module(mod) # return getattr(module, member) , which may contain function names, class names, or code. Output only the next line.
}
Continue the code snippet: <|code_start|> DEFAULTS = { 'STORAGE': 'social.apps.flask_app.models.FlaskStorage', 'STRATEGY': 'social.strategies.flask_strategy.FlaskStrategy' } def get_helper(name, do_import=False): config = current_app.config.get(setting_name(name), DEFAULTS.get(name, None)) return do_import and module_member(config) or config def load_strategy(*args, **kwargs): backends = get_helper('AUTHENTICATION_BACKENDS') strategy = get_helper('STRATEGY') <|code_end|> . Use current file imports: from functools import wraps from flask import current_app, url_for, g, request, redirect from social.utils import module_member, setting_name from social.strategies.utils import get_strategy and context (classes, functions, or code) from other files: # Path: social/utils.py # def module_member(name): # mod, member = name.rsplit('.', 1) # module = import_module(mod) # return getattr(module, member) # # def setting_name(*names): # names = [val.upper().replace('-', '_') for val in names if val] # return '_'.join((SETTING_PREFIX,) + tuple(names)) . Output only the next line.
storage = get_helper('STORAGE')
Based on the snippet: <|code_start|> 'STRATEGY': 'social.strategies.flask_strategy.FlaskStrategy' } def get_helper(name, do_import=False): config = current_app.config.get(setting_name(name), DEFAULTS.get(name, None)) return do_import and module_member(config) or config def load_strategy(*args, **kwargs): backends = get_helper('AUTHENTICATION_BACKENDS') strategy = get_helper('STRATEGY') storage = get_helper('STORAGE') return get_strategy(backends, strategy, storage, *args, **kwargs) def strategy(redirect_uri=None): def decorator(func): @wraps(func) def wrapper(backend, *args, **kwargs): uri = redirect_uri if uri and not uri.startswith('/'): uri = url_for(uri, backend=backend) g.strategy = load_strategy(request=request, backend=backend, redirect_uri=uri, *args, **kwargs) return func(backend, *args, **kwargs) return wrapper return decorator <|code_end|> , predict the immediate next line with the help of imports: from functools import wraps from flask import current_app, url_for, g, request, redirect from social.utils import module_member, setting_name from social.strategies.utils import get_strategy and context (classes, functions, sometimes code) from other files: # Path: social/utils.py # def module_member(name): # mod, member = name.rsplit('.', 1) # module = import_module(mod) # return getattr(module, member) # # def setting_name(*names): # names = [val.upper().replace('-', '_') for val in names if val] # return '_'.join((SETTING_PREFIX,) + tuple(names)) . Output only the next line.
def login_required(fn):
Using the snippet: <|code_start|> chart_header = start_date.strftime('%b %d %Y') + " - " + end_date.strftime('%b %d %Y') budget_data = {} # budget data for primary chart cat_data = {} # category data for drill down for budget in budgets: subcat = {} #This will hold the drill down data for each budget if Transaction.objects.filter(budget__budget=budget.id, debit=True, date__range=[start_date, end_date]).count(): #If transactions for budget exist amount = Transaction.objects.filter(budget__budget=budget.id, debit=True, date__range=[start_date, end_date]).aggregate(Sum('amount')) #Get the sum of amount for the budget budget_data[budget.name] = amount['amount__sum'] #Add to budget data # FOR THE DRILL DOWN # for category in categories: if Transaction.objects.filter(budget__budget=budget.id, #If the category exists in the given budget category=category.id, debit=True, date__range=[start_date, end_date]).count(): category_amount = Transaction.objects.filter(budget__budget=budget.id, category=category.id, debit=True, date__range=[start_date, end_date]).aggregate(Sum('amount')) #Get the sum of the amount for the category subcat[category.name] = category_amount['amount__sum'] if Transaction.objects.filter(budget__budget=budget.id, #If there are uncategorized transactions in the budget category__isnull=True, debit=True, date__range=[start_date, end_date]).count(): category_amount = Transaction.objects.filter(budget__budget=budget.id, category__isnull=True).aggregate(Sum('amount')) subcat['Uncatorgorized'] = category_amount['amount__sum'] cat_data[budget.name] = subcat # END DRILL DOWN # ## END CHART CODE ## context = {'accounts': accounts, 'transfer_form': transfer_form, 'chart_header': chart_header, 'budget_data': budget_data, 'cat_data': cat_data, 'filter_form': filter_form} <|code_end|> , determine the next line of code. You have imports: from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView from django.db.models import Sum from .models import Account from .forms import TransferForm from transactions.forms import FilterForm from transactions.models import Transaction, Category from budget.models import Budget import datetime and context (class names, function names, or code) available: # Path: banking/accounts/models.py # class Account(models.Model): # name = models.CharField(max_length=50) # balance = models.DecimalField(max_digits=65, decimal_places=2) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # Path: banking/accounts/forms.py # class TransferForm(forms.Form): # date = forms.DateField( widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0", 'size': '10'})) # from_acct = TransferChoiceField(queryset=Account.objects.all()) # to_acct = TransferChoiceField(queryset=Account.objects.all()) # amount = forms.DecimalField(max_digits=65, decimal_places=2, localize=True, widget=forms.TextInput(attrs={'size': '6'})) . Output only the next line.
return context
Next line prediction: <|code_start|> class AccountsOverview(View): def get_context(self, *args, **kwargs): transfer_form = TransferForm(prefix='transfer_form') filter_form = FilterForm(prefix='filter_form') accounts = Account.objects.all().order_by('name') ## CODE FOR CHART DATA ## categories = Category.objects.all() #Categories for drill down budgets = Budget.objects.all() #Budgets for primary chart if 'startdate' and 'enddate' in kwargs: <|code_end|> . Use current file imports: (from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView from django.db.models import Sum from .models import Account from .forms import TransferForm from transactions.forms import FilterForm from transactions.models import Transaction, Category from budget.models import Budget import datetime) and context including class names, function names, or small code snippets from other files: # Path: banking/accounts/models.py # class Account(models.Model): # name = models.CharField(max_length=50) # balance = models.DecimalField(max_digits=65, decimal_places=2) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # Path: banking/accounts/forms.py # class TransferForm(forms.Form): # date = forms.DateField( widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0", 'size': '10'})) # from_acct = TransferChoiceField(queryset=Account.objects.all()) # to_acct = TransferChoiceField(queryset=Account.objects.all()) # amount = forms.DecimalField(max_digits=65, decimal_places=2, localize=True, widget=forms.TextInput(attrs={'size': '6'})) . Output only the next line.
start_date = kwargs['startdate']
Given the following code snippet before the placeholder: <|code_start|> ###Handle special fields### if key == "budget":# If the transaction is applied towards a budget: #The transaction will hit the monthly budget for the month the transaction is posted in #If you are paying something for next months budget (i.e. paying the mortgage due the 1st) #then you need to post-date the transaction to the next month if value != None: #If the budget value is not NONE date = transaction_form.cleaned_data['date'] year = date.year month = date.month #Get the budget for the month and year of the transaction budget = MonthlyBudget.objects.filter(budget__slug=value, month__year=year, month__month=month).first() if budget: transaction_data[key] = budget #pass the instance of the monthly budget #Apply the transaction to the monthly budget new_budget_actual = budget.actual + transaction_form.cleaned_data['amount'] budget.actual = new_budget_actual budget.save() else: #Otherwise show an error notifying the user that no instance of the budget for the given month and year month = date.strftime('%B') error = "Error: There is no {} budget for {}. {}. Please add the budget then resubmit the transaction.".format(value, month, year) #if there is no matching budget set the value to Error context = {'transaction_form': transaction_form, 'error': error, 'account': accountobj, 'filter_form': filter_form} return render(request, 'transactions\overview.html', context) elif key == "direction": #Convert the direction to either True or False for the debit field if value == "O": #If money is going OUT it is a debit transaction_data["debit"] = True else: #If money is coming in it is not a debit transaction_data["debit"] = False ###If there is nothing special with the field just add the key and value to the dictionary### else: transaction_data[key] = value <|code_end|> , predict the next line using imports from the current file: from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView, FormView from django.db.models import Sum from .models import Transaction from accounts.models import Account from .forms import AddTransactionForm, FilterForm from budget.models import MonthlyBudget import datetime and context including class names, function names, and sometimes code from other files: # Path: banking/transactions/models.py # class Transaction(models.Model): # date = models.DateField() # account = models.ForeignKey(Account) # amount = models.DecimalField(max_digits=65, decimal_places=2) # balance = models.DecimalField(max_digits=65, decimal_places=2) # beneficiary = models.CharField(max_length=50) # budget = models.ForeignKey(MonthlyBudget, blank=True, null=True) # category = models.ForeignKey('Category', blank=True, null=True) # debit = models.BooleanField(default=True) # transfer = models.BooleanField(default=False) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # time = datetime.datetime.now().time().strftime("%H%M%S") #Add the hour, min, and second to the slug to avoid Unique constraint conflicts # forslug = "{0.date}-{1}-{0.account}-{0.amount}".format(self, time) # self.slug = slugify(forslug) # super(Transaction, self).save() # # Path: banking/transactions/forms.py # class AddTransactionForm(forms.Form): # date = forms.DateField( widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'size': '10', 'data-start-week-day': "0"})) # budget = forms.CharField() # beneficiary = forms.CharField() # category = forms.CharField() # amount = forms.DecimalField(max_digits=65, decimal_places=2, localize=True, widget=forms.TextInput(attrs={'size': '6'})) # direction = forms.ChoiceField(widget=forms.RadioSelect, choices=DIRECTION_CHOICES, initial="O") # # def __init__(self, *args, **kwargs): #Need to overide the init so that the modelchoice queryset will update each time the form loads # super(AddTransactionForm, self).__init__(*args, **kwargs) # self.fields['budget'] = forms.ModelChoiceField(queryset=Budget.objects.all(), required=False) # self.fields['category'] = forms.ModelChoiceField(queryset=Category.objects.all(), required=False) # # class FilterForm(forms.Form): # thirty_days_ago = datetime.datetime.today() + datetime.timedelta(-30) # thirty_days_ago = thirty_days_ago.strftime('%Y-%m-%d') # start_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-date': thirty_days_ago, 'data-start-week-day': "0"})) # end_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0"})) . Output only the next line.
if transaction_form.cleaned_data['direction'] == 'O': #Check the direction of money flow and update the balance of the account
Based on the snippet: <|code_start|> end_date = 0 if (action == 'add_transaction'): transaction_form = AddTransactionForm(request.POST, prefix='transaction_form') if transaction_form.is_valid(): transaction_data = {'account': accountobj} for key, value in transaction_form.cleaned_data.items(): ###Handle special fields### if key == "budget":# If the transaction is applied towards a budget: #The transaction will hit the monthly budget for the month the transaction is posted in #If you are paying something for next months budget (i.e. paying the mortgage due the 1st) #then you need to post-date the transaction to the next month if value != None: #If the budget value is not NONE date = transaction_form.cleaned_data['date'] year = date.year month = date.month #Get the budget for the month and year of the transaction budget = MonthlyBudget.objects.filter(budget__slug=value, month__year=year, month__month=month).first() if budget: transaction_data[key] = budget #pass the instance of the monthly budget #Apply the transaction to the monthly budget new_budget_actual = budget.actual + transaction_form.cleaned_data['amount'] budget.actual = new_budget_actual budget.save() else: #Otherwise show an error notifying the user that no instance of the budget for the given month and year month = date.strftime('%B') error = "Error: There is no {} budget for {}. {}. Please add the budget then resubmit the transaction.".format(value, month, year) #if there is no matching budget set the value to Error context = {'transaction_form': transaction_form, 'error': error, 'account': accountobj, 'filter_form': filter_form} return render(request, 'transactions\overview.html', context) elif key == "direction": #Convert the direction to either True or False for the debit field <|code_end|> , predict the immediate next line with the help of imports: from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView, FormView from django.db.models import Sum from .models import Transaction from accounts.models import Account from .forms import AddTransactionForm, FilterForm from budget.models import MonthlyBudget import datetime and context (classes, functions, sometimes code) from other files: # Path: banking/transactions/models.py # class Transaction(models.Model): # date = models.DateField() # account = models.ForeignKey(Account) # amount = models.DecimalField(max_digits=65, decimal_places=2) # balance = models.DecimalField(max_digits=65, decimal_places=2) # beneficiary = models.CharField(max_length=50) # budget = models.ForeignKey(MonthlyBudget, blank=True, null=True) # category = models.ForeignKey('Category', blank=True, null=True) # debit = models.BooleanField(default=True) # transfer = models.BooleanField(default=False) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # time = datetime.datetime.now().time().strftime("%H%M%S") #Add the hour, min, and second to the slug to avoid Unique constraint conflicts # forslug = "{0.date}-{1}-{0.account}-{0.amount}".format(self, time) # self.slug = slugify(forslug) # super(Transaction, self).save() # # Path: banking/transactions/forms.py # class AddTransactionForm(forms.Form): # date = forms.DateField( widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'size': '10', 'data-start-week-day': "0"})) # budget = forms.CharField() # beneficiary = forms.CharField() # category = forms.CharField() # amount = forms.DecimalField(max_digits=65, decimal_places=2, localize=True, widget=forms.TextInput(attrs={'size': '6'})) # direction = forms.ChoiceField(widget=forms.RadioSelect, choices=DIRECTION_CHOICES, initial="O") # # def __init__(self, *args, **kwargs): #Need to overide the init so that the modelchoice queryset will update each time the form loads # super(AddTransactionForm, self).__init__(*args, **kwargs) # self.fields['budget'] = forms.ModelChoiceField(queryset=Budget.objects.all(), required=False) # self.fields['category'] = forms.ModelChoiceField(queryset=Category.objects.all(), required=False) # # class FilterForm(forms.Form): # thirty_days_ago = datetime.datetime.today() + datetime.timedelta(-30) # thirty_days_ago = thirty_days_ago.strftime('%Y-%m-%d') # start_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-date': thirty_days_ago, 'data-start-week-day': "0"})) # end_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0"})) . Output only the next line.
if value == "O": #If money is going OUT it is a debit
Using the snippet: <|code_start|> context = {'transactions': transactions, 'account': accountobj, 'transaction_form': transaction_form, 'filter_form': filter_form, 'balances': balances} return context def get(self, request, account): start_date = 0 end_date = 0 return render(request, 'transactions/overview.html', self.get_context_data(request, account=account, start_date=start_date, end_date=end_date)) def post(self, request, account): action = self.request.POST['action'] accountobj = Account.objects.get(slug = account) start_date =0 end_date = 0 if (action == 'add_transaction'): transaction_form = AddTransactionForm(request.POST, prefix='transaction_form') if transaction_form.is_valid(): transaction_data = {'account': accountobj} for key, value in transaction_form.cleaned_data.items(): ###Handle special fields### if key == "budget":# If the transaction is applied towards a budget: #The transaction will hit the monthly budget for the month the transaction is posted in #If you are paying something for next months budget (i.e. paying the mortgage due the 1st) #then you need to post-date the transaction to the next month if value != None: #If the budget value is not NONE date = transaction_form.cleaned_data['date'] <|code_end|> , determine the next line of code. You have imports: from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView, FormView from django.db.models import Sum from .models import Transaction from accounts.models import Account from .forms import AddTransactionForm, FilterForm from budget.models import MonthlyBudget import datetime and context (class names, function names, or code) available: # Path: banking/transactions/models.py # class Transaction(models.Model): # date = models.DateField() # account = models.ForeignKey(Account) # amount = models.DecimalField(max_digits=65, decimal_places=2) # balance = models.DecimalField(max_digits=65, decimal_places=2) # beneficiary = models.CharField(max_length=50) # budget = models.ForeignKey(MonthlyBudget, blank=True, null=True) # category = models.ForeignKey('Category', blank=True, null=True) # debit = models.BooleanField(default=True) # transfer = models.BooleanField(default=False) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # time = datetime.datetime.now().time().strftime("%H%M%S") #Add the hour, min, and second to the slug to avoid Unique constraint conflicts # forslug = "{0.date}-{1}-{0.account}-{0.amount}".format(self, time) # self.slug = slugify(forslug) # super(Transaction, self).save() # # Path: banking/transactions/forms.py # class AddTransactionForm(forms.Form): # date = forms.DateField( widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'size': '10', 'data-start-week-day': "0"})) # budget = forms.CharField() # beneficiary = forms.CharField() # category = forms.CharField() # amount = forms.DecimalField(max_digits=65, decimal_places=2, localize=True, widget=forms.TextInput(attrs={'size': '6'})) # direction = forms.ChoiceField(widget=forms.RadioSelect, choices=DIRECTION_CHOICES, initial="O") # # def __init__(self, *args, **kwargs): #Need to overide the init so that the modelchoice queryset will update each time the form loads # super(AddTransactionForm, self).__init__(*args, **kwargs) # self.fields['budget'] = forms.ModelChoiceField(queryset=Budget.objects.all(), required=False) # self.fields['category'] = forms.ModelChoiceField(queryset=Category.objects.all(), required=False) # # class FilterForm(forms.Form): # thirty_days_ago = datetime.datetime.today() + datetime.timedelta(-30) # thirty_days_ago = thirty_days_ago.strftime('%Y-%m-%d') # start_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-date': thirty_days_ago, 'data-start-week-day': "0"})) # end_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0"})) . Output only the next line.
year = date.year
Given snippet: <|code_start|> if budget_data['duration'] == 'M': newmonthlybudget = MonthlyBudget.objects.create(budget=newbudget, month=budget_data['starting_month'], planned=budget_data['amount'], actual=0.00) else: start = budget_data['starting_month'] start_month = int(start.month) start_year = int(start.year) months = [] while start_month < 13: months.append(start_month) start_month += 1 print(months) for month in months: budget_month = str(datetime.date(start_year, month, 1)) newmonthlybudget = MonthlyBudget.objects.create(budget=newbudget, month=budget_month, planned=budget_data['amount'], actual=0.00) planned_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month).aggregate( Sum('planned')) elif (action == 'date_filter'): filter_form = FilterForm(request.POST, prefix='filter_form') if filter_form.is_valid(): month = filter_form.cleaned_data['month'] header = month.strftime('%B') + " " + str(month.year) monthlybudgets = MonthlyBudget.objects.filter(month__year=month.year, month__month=month.month) planned_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=month.month).aggregate( Sum('planned')) actual_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=month.month).aggregate( Sum('actual')) else: monthlybudgets = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month) context = {'cash_out': cash_out, 'cash_in': cash_in, 'monthlybudgets': monthlybudgets,'budget_form': budget_form, 'header': header, 'filter_form': filter_form, 'planned_total': planned_total, 'actual_total': actual_total} <|code_end|> , continue by predicting the next line. Consider current file imports: from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView from django.db.models import Sum from .models import Budget, MonthlyBudget from transactions.models import Transaction from .forms import AddMonthlyBudget, FilterForm import datetime and context: # Path: banking/budget/models.py # class Budget(models.Model): # name = models.CharField(max_length=50) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # self.slug = slugify(self.name) # super(Budget, self).save() # # class MonthlyBudget(models.Model): # budget = models.ForeignKey('Budget') # month = models.DateField() # planned = models.DecimalField(max_digits=65, decimal_places=2) # actual = models.DecimalField(max_digits=65, decimal_places=2, blank=True, null=True) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # forslug = "{0.budget}-{0.month}".format(self) # self.slug = slugify(forslug) # super(MonthlyBudget, self).save() # # Path: banking/budget/forms.py # class AddMonthlyBudget(forms.Form): # budget = forms.CharField(widget=forms.TextInput(attrs={'size': '15'})) # amount = forms.DecimalField(max_digits=65, decimal_places=2, widget=forms.TextInput(attrs={'size': '6'})) # starting_month = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'size': '10', 'data-start-week-day': "0"})) # duration = forms.ChoiceField(widget=forms.RadioSelect, choices=DURATION_CHOICES) # # class FilterForm(forms.Form): # month = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0"})) which might include code, classes, or functions. Output only the next line.
return render(request, 'budget/monthlybudget.html', context)
Given snippet: <|code_start|> class MonthlyBudgetOverview(View): def get(self, request): budget_form = AddMonthlyBudget(prefix='budget_form') filter_form = FilterForm(prefix='filter_form') now = datetime.datetime.now() monthlybudgets = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month) header = now.strftime('%B') + " " + str(now.year) planned_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month).aggregate(Sum('planned')) actual_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month).aggregate(Sum('actual')) cash_in = Transaction.objects.filter(date__year=now.year, date__month=now.month, debit=False, transfer=False).aggregate(Sum('amount')) cash_out = Transaction.objects.filter(date__year=now.year, date__month=now.month, debit=True, transfer=False).aggregate( <|code_end|> , continue by predicting the next line. Consider current file imports: from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView from django.db.models import Sum from .models import Budget, MonthlyBudget from transactions.models import Transaction from .forms import AddMonthlyBudget, FilterForm import datetime and context: # Path: banking/budget/models.py # class Budget(models.Model): # name = models.CharField(max_length=50) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # self.slug = slugify(self.name) # super(Budget, self).save() # # class MonthlyBudget(models.Model): # budget = models.ForeignKey('Budget') # month = models.DateField() # planned = models.DecimalField(max_digits=65, decimal_places=2) # actual = models.DecimalField(max_digits=65, decimal_places=2, blank=True, null=True) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # forslug = "{0.budget}-{0.month}".format(self) # self.slug = slugify(forslug) # super(MonthlyBudget, self).save() # # Path: banking/budget/forms.py # class AddMonthlyBudget(forms.Form): # budget = forms.CharField(widget=forms.TextInput(attrs={'size': '15'})) # amount = forms.DecimalField(max_digits=65, decimal_places=2, widget=forms.TextInput(attrs={'size': '6'})) # starting_month = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'size': '10', 'data-start-week-day': "0"})) # duration = forms.ChoiceField(widget=forms.RadioSelect, choices=DURATION_CHOICES) # # class FilterForm(forms.Form): # month = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0"})) which might include code, classes, or functions. Output only the next line.
Sum('amount'))
Given the following code snippet before the placeholder: <|code_start|> class MonthlyBudgetOverview(View): def get(self, request): budget_form = AddMonthlyBudget(prefix='budget_form') filter_form = FilterForm(prefix='filter_form') now = datetime.datetime.now() monthlybudgets = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month) header = now.strftime('%B') + " " + str(now.year) planned_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month).aggregate(Sum('planned')) actual_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month).aggregate(Sum('actual')) cash_in = Transaction.objects.filter(date__year=now.year, date__month=now.month, debit=False, transfer=False).aggregate(Sum('amount')) cash_out = Transaction.objects.filter(date__year=now.year, date__month=now.month, debit=True, transfer=False).aggregate( Sum('amount')) context = {'cash_out': cash_out, 'cash_in': cash_in, 'monthlybudgets': monthlybudgets,'budget_form': budget_form, 'header': header, 'filter_form': filter_form, 'planned_total': planned_total, 'actual_total': actual_total} return render(request, 'budget/monthlybudget.html', context) <|code_end|> , predict the next line using imports from the current file: from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView from django.db.models import Sum from .models import Budget, MonthlyBudget from transactions.models import Transaction from .forms import AddMonthlyBudget, FilterForm import datetime and context including class names, function names, and sometimes code from other files: # Path: banking/budget/models.py # class Budget(models.Model): # name = models.CharField(max_length=50) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # self.slug = slugify(self.name) # super(Budget, self).save() # # class MonthlyBudget(models.Model): # budget = models.ForeignKey('Budget') # month = models.DateField() # planned = models.DecimalField(max_digits=65, decimal_places=2) # actual = models.DecimalField(max_digits=65, decimal_places=2, blank=True, null=True) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # forslug = "{0.budget}-{0.month}".format(self) # self.slug = slugify(forslug) # super(MonthlyBudget, self).save() # # Path: banking/budget/forms.py # class AddMonthlyBudget(forms.Form): # budget = forms.CharField(widget=forms.TextInput(attrs={'size': '15'})) # amount = forms.DecimalField(max_digits=65, decimal_places=2, widget=forms.TextInput(attrs={'size': '6'})) # starting_month = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'size': '10', 'data-start-week-day': "0"})) # duration = forms.ChoiceField(widget=forms.RadioSelect, choices=DURATION_CHOICES) # # class FilterForm(forms.Form): # month = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0"})) . Output only the next line.
def post(self, request):
Given snippet: <|code_start|> now = datetime.datetime.now() action = self.request.POST['action'] monthlybudgets = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month) header = now.strftime('%B') + " " + str(now.year) planned_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month).aggregate(Sum('planned')) actual_total = MonthlyBudget.objects.filter(month__year=now.year, month__month=now.month).aggregate( Sum('actual')) cash_in = Transaction.objects.filter(date__year=now.year, date__month=now.month, debit=False, transfer=False).aggregate( Sum('amount')) cash_out = Transaction.objects.filter(date__year=now.year, date__month=now.month, debit=True, transfer=False).aggregate( Sum('amount')) if (action == 'add_budget'): budget_form = AddMonthlyBudget(request.POST, prefix = 'budget_form') if budget_form.is_valid(): budget_data = {} for key, value in budget_form.cleaned_data.items(): budget_data[key] = value newbudget = Budget.objects.filter(name=budget_data['budget']).first() #Look to see if the budget already exists if newbudget: pass #if the budget exists then do nothing else: newbudget = Budget.objects.create(name=budget_data['budget']) if budget_data['duration'] == 'M': newmonthlybudget = MonthlyBudget.objects.create(budget=newbudget, month=budget_data['starting_month'], planned=budget_data['amount'], actual=0.00) else: start = budget_data['starting_month'] start_month = int(start.month) start_year = int(start.year) months = [] <|code_end|> , continue by predicting the next line. Consider current file imports: from django.shortcuts import render from django.views.generic import View, CreateView, UpdateView from django.db.models import Sum from .models import Budget, MonthlyBudget from transactions.models import Transaction from .forms import AddMonthlyBudget, FilterForm import datetime and context: # Path: banking/budget/models.py # class Budget(models.Model): # name = models.CharField(max_length=50) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # self.slug = slugify(self.name) # super(Budget, self).save() # # class MonthlyBudget(models.Model): # budget = models.ForeignKey('Budget') # month = models.DateField() # planned = models.DecimalField(max_digits=65, decimal_places=2) # actual = models.DecimalField(max_digits=65, decimal_places=2, blank=True, null=True) # slug = models.SlugField(unique=True) # # def __str__(self): # return self.slug # # def save(self, *args, **kwargs): # forslug = "{0.budget}-{0.month}".format(self) # self.slug = slugify(forslug) # super(MonthlyBudget, self).save() # # Path: banking/budget/forms.py # class AddMonthlyBudget(forms.Form): # budget = forms.CharField(widget=forms.TextInput(attrs={'size': '15'})) # amount = forms.DecimalField(max_digits=65, decimal_places=2, widget=forms.TextInput(attrs={'size': '6'})) # starting_month = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'size': '10', 'data-start-week-day': "0"})) # duration = forms.ChoiceField(widget=forms.RadioSelect, choices=DURATION_CHOICES) # # class FilterForm(forms.Form): # month = forms.DateField(widget=forms.TextInput(attrs={'class': 'ink-datepicker', 'data-start-week-day': "0"})) which might include code, classes, or functions. Output only the next line.
while start_month < 13:
Using the snippet: <|code_start|> register = template.Library() DOUBLE_RENDER = getattr(settings, 'DOUBLE_RENDER', False) #class RateUrlsNode(template.Node): # def __init__(self, object, up_name, down_name, form_name=None): # self.object, self.up_name, self.down_name = object, up_name, down_name # self.form_name = form_name # # def render(self, context): # obj = template.Variable(self.object).resolve(context) # if obj and hasattr(obj, 'get_absolute_url'): # context[self.up_name] = '%s%s/%s/' % (obj.get_absolute_url(), _('rate'), _('up')) # context[self.down_name] = '%s%s/%s/' % (obj.get_absolute_url(), _('rate'), _('down')) # elif obj: # ct = ContentType.objects.get_for_model(obj) # context[self.form_name] = RateForm(initial={'content_type' : ct.id, 'target' : obj._get_pk_val()}) # context[self.up_name] = reverse('rate_up') # context[self.down_name] = reverse('rate_down') # return '' class RateUrlNode(template.Node): def __init__(self, object, url_var_name, form_name=None): self.object = object self.url_var_name =url_var_name self.form_name = form_name def render(self, context): <|code_end|> , determine the next line of code. You have imports: from decimal import Decimal from django import template from django.db import models from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from django_ratings.models import TotalRate from django_ratings.forms import RateForm from django_ratings.views import get_was_rated from django.utils.translation import ugettext as _ from recepty import settings and context (class names, function names, or code) available: # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # Path: django_ratings/forms.py # class RateForm(forms.Form): # content_type = forms.IntegerField(widget=forms.HiddenInput) # target = forms.IntegerField(widget=forms.HiddenInput) # # def clean_content_type(self): # try: # value = ContentType.objects.get(pk=self.cleaned_data['content_type']) # except models.ObjectDoesNotExist: # raise forms.ValidationError, _('The given ContentType object does not exist.') # return value # # def clean_target(self): # try: # value = self.cleaned_data['content_type'].get_object_for_this_type(pk=self.cleaned_data['content_type']) # except models.ObjectDoesNotExist: # raise forms.ValidationError, _('The given target object does not exist.') # return value # # Path: django_ratings/views.py # def get_was_rated(request, ct, target): # """ # Returns whether object was rated by current user # # Rating can fail later on db query, this checks user cookies # """ # if isinstance(ct, ContentType): # ct = ct.id # if isinstance(target, models.Model): # target = target.pk # return '%s:%s' % (ct, target) in _get_cookie(request) . Output only the next line.
obj = template.Variable(self.object).resolve(context)
Here is a snippet: <|code_start|> register = template.Library() DOUBLE_RENDER = getattr(settings, 'DOUBLE_RENDER', False) #class RateUrlsNode(template.Node): # def __init__(self, object, up_name, down_name, form_name=None): # self.object, self.up_name, self.down_name = object, up_name, down_name # self.form_name = form_name # # def render(self, context): # obj = template.Variable(self.object).resolve(context) # if obj and hasattr(obj, 'get_absolute_url'): # context[self.up_name] = '%s%s/%s/' % (obj.get_absolute_url(), _('rate'), _('up')) # context[self.down_name] = '%s%s/%s/' % (obj.get_absolute_url(), _('rate'), _('down')) # elif obj: # ct = ContentType.objects.get_for_model(obj) # context[self.form_name] = RateForm(initial={'content_type' : ct.id, 'target' : obj._get_pk_val()}) # context[self.up_name] = reverse('rate_up') # context[self.down_name] = reverse('rate_down') # return '' class RateUrlNode(template.Node): def __init__(self, object, url_var_name, form_name=None): self.object = object self.url_var_name =url_var_name <|code_end|> . Write the next line using the current file imports: from decimal import Decimal from django import template from django.db import models from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from django_ratings.models import TotalRate from django_ratings.forms import RateForm from django_ratings.views import get_was_rated from django.utils.translation import ugettext as _ from recepty import settings and context from other files: # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # Path: django_ratings/forms.py # class RateForm(forms.Form): # content_type = forms.IntegerField(widget=forms.HiddenInput) # target = forms.IntegerField(widget=forms.HiddenInput) # # def clean_content_type(self): # try: # value = ContentType.objects.get(pk=self.cleaned_data['content_type']) # except models.ObjectDoesNotExist: # raise forms.ValidationError, _('The given ContentType object does not exist.') # return value # # def clean_target(self): # try: # value = self.cleaned_data['content_type'].get_object_for_this_type(pk=self.cleaned_data['content_type']) # except models.ObjectDoesNotExist: # raise forms.ValidationError, _('The given target object does not exist.') # return value # # Path: django_ratings/views.py # def get_was_rated(request, ct, target): # """ # Returns whether object was rated by current user # # Rating can fail later on db query, this checks user cookies # """ # if isinstance(ct, ContentType): # ct = ct.id # if isinstance(target, models.Model): # target = target.pk # return '%s:%s' % (ct, target) in _get_cookie(request) , which may include functions, classes, or code. Output only the next line.
self.form_name = form_name
Based on the snippet: <|code_start|> # ratings - specific settings ANONYMOUS_KARMA = getattr(settings, 'ANONYMOUS_KARMA', 1) INITIAL_USER_KARMA = getattr(settings, 'ANONYMOUS_KARMA', 4) MINIMAL_ANONYMOUS_IP_DELAY = getattr(settings, 'MINIMAL_ANONYMOUS_IP_DELAY', 1800) RATINGS_COOKIE_NAME = getattr(settings, 'RATINGS_COOKIE_NAME', 'ratings_voted') RATINGS_MAX_COOKIE_LENGTH = getattr(settings, 'RATINGS_MAX_COOKIE_LENGTH', 20) RATINGS_MAX_COOKIE_AGE = getattr(settings, 'RATINGS_MAX_COOKIE_AGE', 3600) PERIOD_CHOICES = ( ('d', 'day'), ('m', 'month'), ('y', 'year'), ) class UserKarmaManager(models.Manager): def total_rate_to_karma(self): self.all().update(karma=0) for r in TotalRate.objects.filter(target_ct__in=karma.sources.registered_content_types()): owner, weight = karma.sources.get_owner(r.target) amount = r.amount * weight updated = self.filter(user=owner).update(karma=models.F('karma') + amount) if updated == 0: self.create(user=owner, karma=amount) <|code_end|> , predict the immediate next line with the help of imports: from datetime import datetime, timedelta from decimal import Decimal from django.db import models, connection from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django_ratings import karma and context (classes, functions, sometimes code) from other files: # Path: django_ratings/karma.py # class KarmaSources(object): # def __init__(self): # def register(self, model, owner_getter, weight=1): # def get_owner(self, instance): # def registered_content_types(self): . Output only the next line.
class UserKarma(models.Model):
Using the snippet: <|code_start|> def test_karma_gets_created_for_appropriate_total_rate(self): TotalRate.objects.create(amount=100, **self.kw) UserKarma.objects.total_rate_to_karma() self.assert_equals(1, UserKarma.objects.count()) k = UserKarma.objects.all()[0] self.assert_equals(self.user, k.user) self.assert_equals(100, k.karma) def test_calculate_can_cope_with_existing_karmas(self): UserKarma.objects.create(user=self.user, karma=10000) TotalRate.objects.create(amount=100, **self.kw) UserKarma.objects.total_rate_to_karma() self.assert_equals(1, UserKarma.objects.count()) k = UserKarma.objects.all()[0] self.assert_equals(self.user, k.user) self.assert_equals(100, k.karma) class TestKarmaSources(KarmaTestCase): def test_return_none_for_non_registered_model(self): self.assert_equals(None, karma.sources.get_owner(self.user)) def test_returns_owner_for_registered_model(self): karma.sources.register(User, lambda u:u) self.assert_equals((self.user, 1), karma.sources.get_owner(self.user)) def test_raises_error_on_double_registration_with_different_weights(self): <|code_end|> , determine the next line of code. You have imports: from django.contrib.auth.models import User, UNUSABLE_PASSWORD from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured from django_ratings import karma from django_ratings.models import TotalRate, UserKarma from helpers import SimpleRateTestCase and context (class names, function names, or code) available: # Path: django_ratings/karma.py # class KarmaSources(object): # def __init__(self): # def register(self, model, owner_getter, weight=1): # def get_owner(self, instance): # def registered_content_types(self): # # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class UserKarma(models.Model): # user = models.ForeignKey(User, primary_key=True) # karma = models.DecimalField(_('Karma'), max_digits=10, decimal_places=2) # # objects = UserKarmaManager() # # class Meta: # verbose_name = _("User's karma") # verbose_name_plural = _("Users' karmas") . Output only the next line.
f = lambda u:u
Continue the code snippet: <|code_start|> def test_raises_error_on_double_registration_with_different_weights(self): f = lambda u:u karma.sources.register(User, f, 100) self.assert_raises(ImproperlyConfigured, karma.sources.register, User, f, 10) def test_raises_error_on_double_registration_with_different_getters(self): karma.sources.register(User, lambda u:u) self.assert_raises(ImproperlyConfigured, karma.sources.register, User, lambda u: u.pk) def test_weight_gets_matched_correctly(self): karma.sources.register(User, lambda u:u, 100) self.assert_equals((self.user, 100), karma.sources.get_owner(self.user)) def test_double_registration_works_for_same_values(self): f = lambda u:u karma.sources.register(User, f, 100) karma.sources.register(User, f, 100) self.assert_equals((self.user, 100), karma.sources.get_owner(self.user)) def test_get_contenttypes_is_empty_on_empty_sources(self): self.assert_equals([], karma.sources.registered_content_types()) def test_get_contenttypes_returns_registered_models(self): karma.sources.register(User, lambda u:u) karma.sources.register(ContentType, lambda u:u) self.assert_equals( sorted([ ContentType.objects.get_for_model(User), ContentType.objects.get_for_model(ContentType) <|code_end|> . Use current file imports: from django.contrib.auth.models import User, UNUSABLE_PASSWORD from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured from django_ratings import karma from django_ratings.models import TotalRate, UserKarma from helpers import SimpleRateTestCase and context (classes, functions, or code) from other files: # Path: django_ratings/karma.py # class KarmaSources(object): # def __init__(self): # def register(self, model, owner_getter, weight=1): # def get_owner(self, instance): # def registered_content_types(self): # # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class UserKarma(models.Model): # user = models.ForeignKey(User, primary_key=True) # karma = models.DecimalField(_('Karma'), max_digits=10, decimal_places=2) # # objects = UserKarmaManager() # # class Meta: # verbose_name = _("User's karma") # verbose_name_plural = _("Users' karmas") . Output only the next line.
]),
Next line prediction: <|code_start|> def test_karma_doesnt_get_created_when_no_applicable_ratings(self): UserKarma.objects.total_rate_to_karma() self.assert_equals(0, UserKarma.objects.count()) def test_karma_gets_created_with_weight_for_appropriate_total_rate(self): karma.sources.register(User, lambda u: self.user, 2) TotalRate.objects.create(amount=100, target_ct=ContentType.objects.get_for_model(User), target_id=self.user.pk) UserKarma.objects.total_rate_to_karma() self.assert_equals(1, UserKarma.objects.count()) k = UserKarma.objects.all()[0] self.assert_equals(self.user, k.user) self.assert_equals(200, k.karma) def test_karma_gets_created_for_appropriate_total_rate(self): TotalRate.objects.create(amount=100, **self.kw) UserKarma.objects.total_rate_to_karma() self.assert_equals(1, UserKarma.objects.count()) k = UserKarma.objects.all()[0] self.assert_equals(self.user, k.user) self.assert_equals(100, k.karma) def test_calculate_can_cope_with_existing_karmas(self): UserKarma.objects.create(user=self.user, karma=10000) TotalRate.objects.create(amount=100, **self.kw) UserKarma.objects.total_rate_to_karma() self.assert_equals(1, UserKarma.objects.count()) k = UserKarma.objects.all()[0] <|code_end|> . Use current file imports: (from django.contrib.auth.models import User, UNUSABLE_PASSWORD from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured from django_ratings import karma from django_ratings.models import TotalRate, UserKarma from helpers import SimpleRateTestCase) and context including class names, function names, or small code snippets from other files: # Path: django_ratings/karma.py # class KarmaSources(object): # def __init__(self): # def register(self, model, owner_getter, weight=1): # def get_owner(self, instance): # def registered_content_types(self): # # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class UserKarma(models.Model): # user = models.ForeignKey(User, primary_key=True) # karma = models.DecimalField(_('Karma'), max_digits=10, decimal_places=2) # # objects = UserKarmaManager() # # class Meta: # verbose_name = _("User's karma") # verbose_name_plural = _("Users' karmas") . Output only the next line.
self.assert_equals(self.user, k.user)
Given snippet: <|code_start|> for ct in self.objs: objs.append((TotalRate.objects.get_for_object(ct), TotalRate.objects.get_normalized_rating(ct, top))) self.assert_equals([(ct.pk*10, (ct.pk-1)) for ct in self.objs], objs) def test_distribution_in_same_sized_universum(self): objs = [] top = len(self.objs) * 10 for ct in self.objs: objs.append((TotalRate.objects.get_for_object(ct), TotalRate.objects.get_normalized_rating(ct, top))) self.assert_equals([(ct.pk*10, (ct.pk-1)*10) for ct in self.objs], objs) class TestTopObjects(MultipleRatedObjectsTestCase): def test_only_return_count_objects(self): self.assert_equals(1, len(TotalRate.objects.get_top_objects(1))) def test_return_top_rated_objects(self): self.assert_equals(list(ContentType.objects.order_by('-pk')[:3]), TotalRate.objects.get_top_objects(3)) def test_return_only_given_model_type(self): Rating.objects.create( target_ct=ContentType.objects.get_for_model(Rating), target_id=self.ratings[0].pk, amount=1 ) self.assert_equals(self.ratings[:1], TotalRate.objects.get_top_objects(10, mods=[Rating])) def test_return_only_given_model_type_even_if_no_ratings(self): self.assert_equals(0, len(TotalRate.objects.get_top_objects(10, mods=[TotalRate]))) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib.contenttypes.models import ContentType from django_ratings.models import TotalRate, Rating from helpers import SimpleRateTestCase, MultipleRatedObjectsTestCase and context: # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class Rating(models.Model): # """ # Rating of an object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateTimeField(_('Time'), default=datetime.now, editable=False) # user = models.ForeignKey(User, blank=True, null=True) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # ip_address = models.CharField(_('IP Address'), max_length="15", blank=True) # # objects = RatingManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Rating') # verbose_name_plural = _('Ratings') # # def save(self, **kwargs): # """ # Modified save() method that checks for duplicit entries. # """ # if not self.pk: # # fail silently on inserting duplicate ratings # if self.user: # try: # Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user) # return # except Rating.DoesNotExist: # pass # elif (self.ip_address and Rating.objects.filter( # target_ct=self.target_ct, # target_id=self.target_id, # user__isnull=True, # ip_address=self.ip_address , # time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY) # ).count() > 0): # return # # denormalize the total rate # cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount) # if cnt == 0: # tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount) # # # super(Rating, self).save(**kwargs) which might include code, classes, or functions. Output only the next line.
class TestRating(SimpleRateTestCase):
Continue the code snippet: <|code_start|> def test_distribution_in_same_sized_universum(self): objs = [] top = len(self.objs) * 10 for ct in self.objs: objs.append((TotalRate.objects.get_for_object(ct), TotalRate.objects.get_normalized_rating(ct, top))) self.assert_equals([(ct.pk*10, (ct.pk-1)*10) for ct in self.objs], objs) class TestTopObjects(MultipleRatedObjectsTestCase): def test_only_return_count_objects(self): self.assert_equals(1, len(TotalRate.objects.get_top_objects(1))) def test_return_top_rated_objects(self): self.assert_equals(list(ContentType.objects.order_by('-pk')[:3]), TotalRate.objects.get_top_objects(3)) def test_return_only_given_model_type(self): Rating.objects.create( target_ct=ContentType.objects.get_for_model(Rating), target_id=self.ratings[0].pk, amount=1 ) self.assert_equals(self.ratings[:1], TotalRate.objects.get_top_objects(10, mods=[Rating])) def test_return_only_given_model_type_even_if_no_ratings(self): self.assert_equals(0, len(TotalRate.objects.get_top_objects(10, mods=[TotalRate]))) class TestRating(SimpleRateTestCase): def test_default_rating_of_an_object(self): self.assert_equals(0, Rating.objects.get_for_object(self.obj)) <|code_end|> . Use current file imports: from django.contrib.contenttypes.models import ContentType from django_ratings.models import TotalRate, Rating from helpers import SimpleRateTestCase, MultipleRatedObjectsTestCase and context (classes, functions, or code) from other files: # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class Rating(models.Model): # """ # Rating of an object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateTimeField(_('Time'), default=datetime.now, editable=False) # user = models.ForeignKey(User, blank=True, null=True) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # ip_address = models.CharField(_('IP Address'), max_length="15", blank=True) # # objects = RatingManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Rating') # verbose_name_plural = _('Ratings') # # def save(self, **kwargs): # """ # Modified save() method that checks for duplicit entries. # """ # if not self.pk: # # fail silently on inserting duplicate ratings # if self.user: # try: # Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user) # return # except Rating.DoesNotExist: # pass # elif (self.ip_address and Rating.objects.filter( # target_ct=self.target_ct, # target_id=self.target_id, # user__isnull=True, # ip_address=self.ip_address , # time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY) # ).count() > 0): # return # # denormalize the total rate # cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount) # if cnt == 0: # tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount) # # # super(Rating, self).save(**kwargs) . Output only the next line.
def test_rating_shows_in_get_for_model(self):
Next line prediction: <|code_start|> class RatingOptions(admin.ModelAdmin): list_filter = ('time', 'target_ct',) list_display = ('__unicode__', 'time', 'amount', 'user',) <|code_end|> . Use current file imports: (from django.contrib import admin from django_ratings.models import Rating, TotalRate, ModelWeight) and context including class names, function names, or small code snippets from other files: # Path: django_ratings/models.py # ANONYMOUS_KARMA = getattr(settings, 'ANONYMOUS_KARMA', 1) # INITIAL_USER_KARMA = getattr(settings, 'ANONYMOUS_KARMA', 4) # MINIMAL_ANONYMOUS_IP_DELAY = getattr(settings, 'MINIMAL_ANONYMOUS_IP_DELAY', 1800) # RATINGS_COOKIE_NAME = getattr(settings, 'RATINGS_COOKIE_NAME', 'ratings_voted') # RATINGS_MAX_COOKIE_LENGTH = getattr(settings, 'RATINGS_MAX_COOKIE_LENGTH', 20) # RATINGS_MAX_COOKIE_AGE = getattr(settings, 'RATINGS_MAX_COOKIE_AGE', 3600) # PERIOD_CHOICES = ( # ('d', 'day'), # ('m', 'month'), # ('y', 'year'), # ) # class UserKarmaManager(models.Manager): # class UserKarma(models.Model): # class Meta: # class TotalRateManager(models.Manager): # class TotalRate(models.Model): # class Meta: # class AggManager(models.Manager): # class Agg(models.Model): # class Meta: # class RatingManager(models.Manager): # class Rating(models.Model): # class Meta: # def total_rate_to_karma(self): # def get_normalized_rating(self, obj, top, step=None): # def get_for_object(self, obj): # def get_top_objects(self, count, mods=[]): # def __unicode__(self): # def move_agg_to_agg(self, time_limit, time_format): # def agg_assume(self): # def agg_to_totalrate(self): # def __unicode__(self): # def get_for_object(self, obj): # def move_rate_to_agg(self, time_limit, time_format): # def __unicode__(self): # def save(self, **kwargs): . Output only the next line.
class TotalRateOptions(admin.ModelAdmin):
Given the code snippet: <|code_start|> class TestAggregation(SimpleRateTestCase): def test_totalrate_from_aggregation(self): now = date.today() for i in range(1,4): Agg.objects.create(people=i, amount=4-i, time=now, period='d', detract=0, **self.kw) Agg.objects.agg_to_totalrate() self.assert_equals(6, TotalRate.objects.get_for_object(self.obj)) <|code_end|> , generate the next line using the imports in this file: from datetime import date, timedelta, datetime from django_ratings.models import TotalRate, Rating, Agg from django_ratings.aggregation import transfer_data from helpers import SimpleRateTestCase and context (functions, classes, or occasionally code) from other files: # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class Rating(models.Model): # """ # Rating of an object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateTimeField(_('Time'), default=datetime.now, editable=False) # user = models.ForeignKey(User, blank=True, null=True) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # ip_address = models.CharField(_('IP Address'), max_length="15", blank=True) # # objects = RatingManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Rating') # verbose_name_plural = _('Ratings') # # def save(self, **kwargs): # """ # Modified save() method that checks for duplicit entries. # """ # if not self.pk: # # fail silently on inserting duplicate ratings # if self.user: # try: # Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user) # return # except Rating.DoesNotExist: # pass # elif (self.ip_address and Rating.objects.filter( # target_ct=self.target_ct, # target_id=self.target_id, # user__isnull=True, # ip_address=self.ip_address , # time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY) # ).count() > 0): # return # # denormalize the total rate # cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount) # if cnt == 0: # tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount) # # # super(Rating, self).save(**kwargs) # # class Agg(models.Model): # """ # Aggregation of rating objects. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateField(_('Time')) # people = models.IntegerField(_('People')) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # period = models.CharField(_('Period'), max_length="1", choices=PERIOD_CHOICES) # detract = models.IntegerField(_('Detract'), default=0, max_length=1) # # objects = AggManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Aggregation') # verbose_name_plural = _('Aggregations') # ordering = ('-time',) # # Path: django_ratings/aggregation.py # def transfer_data(): # """ # transfer data from table Rating to table Agg # """ # logger.info("transfer_data BEGIN") # timenow = datetime.now() # for t in sorted(TIMES_ALL.keys(), reverse=True): # TIME_DELTA = t # time_agg = timenow - timedelta(seconds=TIME_DELTA) # Rating.objects.move_rate_to_agg(time_agg, TIMES_ALL[t]) # transfer_agg_to_agg() # transfer_agg_to_totalrate() # logger.info("transfer_data END") . Output only the next line.
def test_aggregation_from_aggegates(self):
Predict the next line after this snippet: <|code_start|> before = now - timedelta(days=40) Agg.objects.create(people=2, amount=4, time=before, **self.kw) Agg.objects.create(people=1, amount=8, time=before, **self.kw) Agg.objects.move_agg_to_agg(now, 'month') expected = [ (before.replace(day=1), 3, 12 ), (now.replace(day=1), 12, 3 ), ] self.assert_equals(2, Agg.objects.count()) self.assert_equals(expected, [(a.time, a.people, a.amount) for a in Agg.objects.order_by('time')]) def test_aggregation_from_ratings_works_for_days(self): now = datetime.now() Rating.objects.create(amount=1, time=now, **self.kw) Rating.objects.create(amount=2, time=now, **self.kw) yesterday = now - timedelta(days=1) Rating.objects.create(amount=4, time=yesterday, **self.kw) Rating.objects.create(amount=8, time=yesterday, **self.kw) Rating.objects.move_rate_to_agg(now, 'day') self.assert_equals(0, Rating.objects.count()) self.assert_equals(2, Agg.objects.count()) expected = [ (yesterday.date(), 2, 12 ), (now.date(), 2, 3 ), <|code_end|> using the current file's imports: from datetime import date, timedelta, datetime from django_ratings.models import TotalRate, Rating, Agg from django_ratings.aggregation import transfer_data from helpers import SimpleRateTestCase and any relevant context from other files: # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class Rating(models.Model): # """ # Rating of an object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateTimeField(_('Time'), default=datetime.now, editable=False) # user = models.ForeignKey(User, blank=True, null=True) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # ip_address = models.CharField(_('IP Address'), max_length="15", blank=True) # # objects = RatingManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Rating') # verbose_name_plural = _('Ratings') # # def save(self, **kwargs): # """ # Modified save() method that checks for duplicit entries. # """ # if not self.pk: # # fail silently on inserting duplicate ratings # if self.user: # try: # Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user) # return # except Rating.DoesNotExist: # pass # elif (self.ip_address and Rating.objects.filter( # target_ct=self.target_ct, # target_id=self.target_id, # user__isnull=True, # ip_address=self.ip_address , # time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY) # ).count() > 0): # return # # denormalize the total rate # cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount) # if cnt == 0: # tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount) # # # super(Rating, self).save(**kwargs) # # class Agg(models.Model): # """ # Aggregation of rating objects. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateField(_('Time')) # people = models.IntegerField(_('People')) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # period = models.CharField(_('Period'), max_length="1", choices=PERIOD_CHOICES) # detract = models.IntegerField(_('Detract'), default=0, max_length=1) # # objects = AggManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Aggregation') # verbose_name_plural = _('Aggregations') # ordering = ('-time',) # # Path: django_ratings/aggregation.py # def transfer_data(): # """ # transfer data from table Rating to table Agg # """ # logger.info("transfer_data BEGIN") # timenow = datetime.now() # for t in sorted(TIMES_ALL.keys(), reverse=True): # TIME_DELTA = t # time_agg = timenow - timedelta(seconds=TIME_DELTA) # Rating.objects.move_rate_to_agg(time_agg, TIMES_ALL[t]) # transfer_agg_to_agg() # transfer_agg_to_totalrate() # logger.info("transfer_data END") . Output only the next line.
]
Based on the snippet: <|code_start|> (now.replace(day=1), 12, 3 ), ] self.assert_equals(2, Agg.objects.count()) self.assert_equals(expected, [(a.time, a.people, a.amount) for a in Agg.objects.order_by('time')]) def test_aggregation_from_ratings_works_for_days(self): now = datetime.now() Rating.objects.create(amount=1, time=now, **self.kw) Rating.objects.create(amount=2, time=now, **self.kw) yesterday = now - timedelta(days=1) Rating.objects.create(amount=4, time=yesterday, **self.kw) Rating.objects.create(amount=8, time=yesterday, **self.kw) Rating.objects.move_rate_to_agg(now, 'day') self.assert_equals(0, Rating.objects.count()) self.assert_equals(2, Agg.objects.count()) expected = [ (yesterday.date(), 2, 12 ), (now.date(), 2, 3 ), ] self.assert_equals(expected, [(a.time, a.people, a.amount) for a in Agg.objects.order_by('time')]) def test_transfer_data_aggregates_newer_ratings_daily(self): now = datetime.now() Rating.objects.create(amount=1, time=now, **self.kw) Rating.objects.create(amount=2, time=now, **self.kw) <|code_end|> , predict the immediate next line with the help of imports: from datetime import date, timedelta, datetime from django_ratings.models import TotalRate, Rating, Agg from django_ratings.aggregation import transfer_data from helpers import SimpleRateTestCase and context (classes, functions, sometimes code) from other files: # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class Rating(models.Model): # """ # Rating of an object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateTimeField(_('Time'), default=datetime.now, editable=False) # user = models.ForeignKey(User, blank=True, null=True) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # ip_address = models.CharField(_('IP Address'), max_length="15", blank=True) # # objects = RatingManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Rating') # verbose_name_plural = _('Ratings') # # def save(self, **kwargs): # """ # Modified save() method that checks for duplicit entries. # """ # if not self.pk: # # fail silently on inserting duplicate ratings # if self.user: # try: # Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user) # return # except Rating.DoesNotExist: # pass # elif (self.ip_address and Rating.objects.filter( # target_ct=self.target_ct, # target_id=self.target_id, # user__isnull=True, # ip_address=self.ip_address , # time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY) # ).count() > 0): # return # # denormalize the total rate # cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount) # if cnt == 0: # tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount) # # # super(Rating, self).save(**kwargs) # # class Agg(models.Model): # """ # Aggregation of rating objects. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateField(_('Time')) # people = models.IntegerField(_('People')) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # period = models.CharField(_('Period'), max_length="1", choices=PERIOD_CHOICES) # detract = models.IntegerField(_('Detract'), default=0, max_length=1) # # objects = AggManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Aggregation') # verbose_name_plural = _('Aggregations') # ordering = ('-time',) # # Path: django_ratings/aggregation.py # def transfer_data(): # """ # transfer data from table Rating to table Agg # """ # logger.info("transfer_data BEGIN") # timenow = datetime.now() # for t in sorted(TIMES_ALL.keys(), reverse=True): # TIME_DELTA = t # time_agg = timenow - timedelta(seconds=TIME_DELTA) # Rating.objects.move_rate_to_agg(time_agg, TIMES_ALL[t]) # transfer_agg_to_agg() # transfer_agg_to_totalrate() # logger.info("transfer_data END") . Output only the next line.
yesterday = now - timedelta(days=1)
Given the code snippet: <|code_start|> now = datetime.now() Rating.objects.create(amount=1, time=now, **self.kw) Rating.objects.create(amount=2, time=now, **self.kw) yesterday = now - timedelta(days=1) Rating.objects.create(amount=4, time=yesterday, **self.kw) Rating.objects.create(amount=8, time=yesterday, **self.kw) Rating.objects.move_rate_to_agg(now, 'day') self.assert_equals(0, Rating.objects.count()) self.assert_equals(2, Agg.objects.count()) expected = [ (yesterday.date(), 2, 12 ), (now.date(), 2, 3 ), ] self.assert_equals(expected, [(a.time, a.people, a.amount) for a in Agg.objects.order_by('time')]) def test_transfer_data_aggregates_newer_ratings_daily(self): now = datetime.now() Rating.objects.create(amount=1, time=now, **self.kw) Rating.objects.create(amount=2, time=now, **self.kw) yesterday = now - timedelta(days=1) Rating.objects.create(amount=4, time=yesterday, **self.kw) Rating.objects.create(amount=8, time=yesterday, **self.kw) transfer_data() expected = [ (yesterday.date(), 2, 12 ), <|code_end|> , generate the next line using the imports in this file: from datetime import date, timedelta, datetime from django_ratings.models import TotalRate, Rating, Agg from django_ratings.aggregation import transfer_data from helpers import SimpleRateTestCase and context (functions, classes, or occasionally code) from other files: # Path: django_ratings/models.py # class TotalRate(models.Model): # """ # save all rating for individual object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID')) # target = generic.GenericForeignKey('target_ct', 'target_id') # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # # objects = TotalRateManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Total rate') # verbose_name_plural = _('Total rates') # unique_together = (('target_ct', 'target_id',),) # # class Rating(models.Model): # """ # Rating of an object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateTimeField(_('Time'), default=datetime.now, editable=False) # user = models.ForeignKey(User, blank=True, null=True) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # ip_address = models.CharField(_('IP Address'), max_length="15", blank=True) # # objects = RatingManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Rating') # verbose_name_plural = _('Ratings') # # def save(self, **kwargs): # """ # Modified save() method that checks for duplicit entries. # """ # if not self.pk: # # fail silently on inserting duplicate ratings # if self.user: # try: # Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user) # return # except Rating.DoesNotExist: # pass # elif (self.ip_address and Rating.objects.filter( # target_ct=self.target_ct, # target_id=self.target_id, # user__isnull=True, # ip_address=self.ip_address , # time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY) # ).count() > 0): # return # # denormalize the total rate # cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount) # if cnt == 0: # tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount) # # # super(Rating, self).save(**kwargs) # # class Agg(models.Model): # """ # Aggregation of rating objects. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateField(_('Time')) # people = models.IntegerField(_('People')) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # period = models.CharField(_('Period'), max_length="1", choices=PERIOD_CHOICES) # detract = models.IntegerField(_('Detract'), default=0, max_length=1) # # objects = AggManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Aggregation') # verbose_name_plural = _('Aggregations') # ordering = ('-time',) # # Path: django_ratings/aggregation.py # def transfer_data(): # """ # transfer data from table Rating to table Agg # """ # logger.info("transfer_data BEGIN") # timenow = datetime.now() # for t in sorted(TIMES_ALL.keys(), reverse=True): # TIME_DELTA = t # time_agg = timenow - timedelta(seconds=TIME_DELTA) # Rating.objects.move_rate_to_agg(time_agg, TIMES_ALL[t]) # transfer_agg_to_agg() # transfer_agg_to_totalrate() # logger.info("transfer_data END") . Output only the next line.
(now.date(), 2, 3 ),
Next line prediction: <|code_start|> class SimpleRateTestCase(DatabaseTestCase): def setUp(self): super(SimpleRateTestCase, self).setUp() self.obj = ContentType.objects.get_for_model(ContentType) self.kw = { 'target_ct': ContentType.objects.get_for_model(self.obj), 'target_id': self.obj.pk } class MultipleRatedObjectsTestCase(DatabaseTestCase): def setUp(self): super(MultipleRatedObjectsTestCase, self).setUp() self.ratings = [] meta_ct = ContentType.objects.get_for_model(ContentType) self.objs = list(ContentType.objects.order_by('pk')) <|code_end|> . Use current file imports: (from djangosanetesting.cases import DatabaseTestCase from django.contrib.contenttypes.models import ContentType from django_ratings.models import Rating) and context including class names, function names, or small code snippets from other files: # Path: django_ratings/models.py # class Rating(models.Model): # """ # Rating of an object. # """ # target_ct = models.ForeignKey(ContentType, db_index=True) # target_id = models.PositiveIntegerField(_('Object ID'), db_index=True) # target = generic.GenericForeignKey('target_ct', 'target_id') # # time = models.DateTimeField(_('Time'), default=datetime.now, editable=False) # user = models.ForeignKey(User, blank=True, null=True) # amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2) # ip_address = models.CharField(_('IP Address'), max_length="15", blank=True) # # objects = RatingManager() # # def __unicode__(self): # return u'%s points for %s' % (self.amount, self.target) # # class Meta: # verbose_name = _('Rating') # verbose_name_plural = _('Ratings') # # def save(self, **kwargs): # """ # Modified save() method that checks for duplicit entries. # """ # if not self.pk: # # fail silently on inserting duplicate ratings # if self.user: # try: # Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user) # return # except Rating.DoesNotExist: # pass # elif (self.ip_address and Rating.objects.filter( # target_ct=self.target_ct, # target_id=self.target_id, # user__isnull=True, # ip_address=self.ip_address , # time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY) # ).count() > 0): # return # # denormalize the total rate # cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount) # if cnt == 0: # tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount) # # # super(Rating, self).save(**kwargs) . Output only the next line.
for ct in self.objs:
Given the code snippet: <|code_start|> class TestAssets(unittest.TestCase): def setUp(self): self.assets = VersionedAssets() self.assets['jquery.js'][Version('1.7.1')] = 'jquery-1.7.1.js' self.assets['jquery.js'][Version('1.8.3')] = 'jquery-1.8.3.js' self.assets['jquery.some.js'][Version('1.8.3')] = { 'provides': 'jquery.js', 'requires': 'jquery.js', 'bundle': None, } self.assets['jquery.form.js'][Version('2.96.0')] = ( 'jquery.js', 'jquery.form-2.96.js', ) self.assets['jquery.form.1.js'][Version('2.96.0')] = { <|code_end|> , generate the next line using the imports in this file: from io import StringIO from coaster.assets import AssetNotFound, UglipyJS, Version, VersionedAssets import unittest import pytest and context (functions, classes, or occasionally code) from other files: # Path: coaster/assets.py # _VERSION_SPECIFIER_RE = re.compile('[<=>!*]') # def split_namespec(namespec): # def __init__(self): # def _require_recursive(self, *namespecs): # def require(self, *namespecs): # def setup(self): # def output(self, _in, out, **kw): # class AssetNotFound(Exception): # noqa: N818 # class VersionedAssets(defaultdict): # class UglipyJS(Filter): . Output only the next line.
'requires': 'jquery.js>=1.8.3',
Predict the next line for this snippet: <|code_start|> ) def test_asset_unversioned(self): bundle = self.assets.require('jquery.js') assert bundle.contents == ('jquery-1.8.3.js',) def test_asset_versioned(self): bundle = self.assets.require('jquery.js==1.7.1') assert bundle.contents == ('jquery-1.7.1.js',) bundle = self.assets.require('jquery.js<1.8.0') assert bundle.contents == ('jquery-1.7.1.js',) bundle = self.assets.require('jquery.js>=1.8.0') assert bundle.contents == ('jquery-1.8.3.js',) def test_missing_asset(self): with pytest.raises(AssetNotFound): self.assets.require('missing.js') def test_single_requires(self): bundle = self.assets.require('jquery.form.js') assert bundle.contents == ('jquery-1.8.3.js', 'jquery.form-2.96.js') def test_single_requires_which_is_dict(self): bundle = self.assets.require('jquery.form.1.js') assert bundle.contents == ('jquery-1.8.3.js',) def test_provides_requires(self): bundle = self.assets.require('jquery.some.js', 'jquery.form.js') assert bundle.contents == ('jquery-1.8.3.js', 'jquery.form-2.96.js') <|code_end|> with the help of current file imports: from io import StringIO from coaster.assets import AssetNotFound, UglipyJS, Version, VersionedAssets import unittest import pytest and context from other files: # Path: coaster/assets.py # _VERSION_SPECIFIER_RE = re.compile('[<=>!*]') # def split_namespec(namespec): # def __init__(self): # def _require_recursive(self, *namespecs): # def require(self, *namespecs): # def setup(self): # def output(self, _in, out, **kw): # class AssetNotFound(Exception): # noqa: N818 # class VersionedAssets(defaultdict): # class UglipyJS(Filter): , which may contain function names, class names, or code. Output only the next line.
def test_version_copies(self):
Given snippet: <|code_start|> class TestAssets(unittest.TestCase): def setUp(self): self.assets = VersionedAssets() self.assets['jquery.js'][Version('1.7.1')] = 'jquery-1.7.1.js' self.assets['jquery.js'][Version('1.8.3')] = 'jquery-1.8.3.js' self.assets['jquery.some.js'][Version('1.8.3')] = { <|code_end|> , continue by predicting the next line. Consider current file imports: from io import StringIO from coaster.assets import AssetNotFound, UglipyJS, Version, VersionedAssets import unittest import pytest and context: # Path: coaster/assets.py # _VERSION_SPECIFIER_RE = re.compile('[<=>!*]') # def split_namespec(namespec): # def __init__(self): # def _require_recursive(self, *namespecs): # def require(self, *namespecs): # def setup(self): # def output(self, _in, out, **kw): # class AssetNotFound(Exception): # noqa: N818 # class VersionedAssets(defaultdict): # class UglipyJS(Filter): which might include code, classes, or functions. Output only the next line.
'provides': 'jquery.js',
Given the code snippet: <|code_start|> self.assets = VersionedAssets() self.assets['jquery.js'][Version('1.7.1')] = 'jquery-1.7.1.js' self.assets['jquery.js'][Version('1.8.3')] = 'jquery-1.8.3.js' self.assets['jquery.some.js'][Version('1.8.3')] = { 'provides': 'jquery.js', 'requires': 'jquery.js', 'bundle': None, } self.assets['jquery.form.js'][Version('2.96.0')] = ( 'jquery.js', 'jquery.form-2.96.js', ) self.assets['jquery.form.1.js'][Version('2.96.0')] = { 'requires': 'jquery.js>=1.8.3', 'provides': 'jquery.form.js', } self.assets['old-lib.js'][Version('1.0.0')] = ( 'jquery.js<1.8.0', 'old-lib-1.0.0.js', ) def test_asset_unversioned(self): bundle = self.assets.require('jquery.js') assert bundle.contents == ('jquery-1.8.3.js',) def test_asset_versioned(self): bundle = self.assets.require('jquery.js==1.7.1') assert bundle.contents == ('jquery-1.7.1.js',) bundle = self.assets.require('jquery.js<1.8.0') assert bundle.contents == ('jquery-1.7.1.js',) <|code_end|> , generate the next line using the imports in this file: from io import StringIO from coaster.assets import AssetNotFound, UglipyJS, Version, VersionedAssets import unittest import pytest and context (functions, classes, or occasionally code) from other files: # Path: coaster/assets.py # _VERSION_SPECIFIER_RE = re.compile('[<=>!*]') # def split_namespec(namespec): # def __init__(self): # def _require_recursive(self, *namespecs): # def require(self, *namespecs): # def setup(self): # def output(self, _in, out, **kw): # class AssetNotFound(Exception): # noqa: N818 # class VersionedAssets(defaultdict): # class UglipyJS(Filter): . Output only the next line.
bundle = self.assets.require('jquery.js>=1.8.0')
Next line prediction: <|code_start|> # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. <|code_end|> . Use current file imports: (from typing import Dict from coaster import _version # isort:skip import os import sys) and context including class names, function names, or small code snippets from other files: # Path: coaster/_version.py . Output only the next line.
html_theme = 'alabaster'
Given the code snippet: <|code_start|>| Computer | $1600 | | Phone | $12 | | Pipe | $1 | | Function name | Description | | ------------- | ------------------------------ | | `help()` | Display the help window. | | `destroy()` | **Destroy your computer!** | ''' sample_output = ''' <p>This is a sample piece of text and represents a paragraph.</p> <p>This is the second paragraph.<br> It has a newline break here.</p> <p>Here is some <strong>bold text</strong> and some <em>emphasized text</em>. It also works with <strong>bold text</strong> and <em>emphasized text</em>.</p> <p>In addition, we support <ins>insertions</ins>, <del>deletions</del> and <mark>markers</mark>.</p> <p>Innocuous HTML tags are allowed when <code>html=True</code> is used: &lt;b&gt;Hello!&lt;/b&gt;</p> <p>Dangerous tags are always removed: &lt;script&gt;window.alert(‘Hello!’)&lt;/script&gt;</p> <p>#This is not a header</p> <h1>This is a header in text-only mode</h1> <h3>This is a header in HTML and text mode</h3> <p>A list:</p> <ol start="2"> <li>Starts at two, because why not?</li> <li>2<sup>10</sup> = 1024</li> <li>Water is H<sub>2</sub>O</li> <li>😄</li> <li>Symbols (ignored): (tm) (c) (r) c/o</li> <li>Symbols (converted): ± → ← ↔ ≠ ½ ¼ 1<sup>st</sup> 2<sup>nd</sup> 3<sup>rd</sup> 4<sup>th</sup> 42<sup>nd</sup></li> </ol> <|code_end|> , generate the next line using the imports in this file: from coaster.gfm import markdown and context (functions, classes, or occasionally code) from other files: # Path: coaster/gfm.py . Output only the next line.
<p>An <a href="https://www.example.com/" rel="nofollow">inline link</a></p>
Continue the code snippet: <|code_start|>app1.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app1) app2 = Flask(__name__) app2.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app2.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app2) @app1.route('/<doc>') @NamedDocument.is_url_for('view', doc='name') def doc_view(doc): return f'view {doc}' @app1.route('/<doc>/edit') @NamedDocument.is_url_for('edit', doc='name') def doc_edit(doc): return f'edit {doc}' @app1.route('/<doc>/upper') @NamedDocument.is_url_for('upper', doc=lambda d: d.name.upper()) def doc_upper(doc): return f'upper {doc}' # The unusual parameter `other='**other.name'` requires an explanation. # The first `other` refers to `<other>` in the URL. The second refers # to the parameter given to `NamedDocument.url_for` in the test below. <|code_end|> . Use current file imports: import unittest import pytest from flask import Flask from werkzeug.routing import BuildError from coaster.db import db from .test_sqlalchemy_models import Container, NamedDocument, ScopedNamedDocument and context (classes, functions, or code) from other files: # Path: coaster/db.py # def _set_sqlite_pragma(dbapi_connection, connection_record): # def _set_postgresql_timezone(dbapi_connection, connection_record): # # Path: tests/test_sqlalchemy_models.py # class Container(BaseMixin, db.Model): # __tablename__ = 'container' # name = Column(Unicode(80), nullable=True) # title = Column(Unicode(80), nullable=True) # # content = Column(Unicode(250)) # # class NamedDocument(BaseNameMixin, db.Model): # __tablename__ = 'named_document' # reserved_names = ['new'] # container_id = Column(Integer, ForeignKey('container.id')) # container = relationship(Container) # # content = Column(Unicode(250)) # # class ScopedNamedDocument(BaseScopedNameMixin, db.Model): # __tablename__ = 'scoped_named_document' # reserved_names = ['new'] # container_id = Column(Integer, ForeignKey('container.id')) # container = relationship(Container) # parent = synonym('container') # # content = Column(Unicode(250)) # __table_args__ = (UniqueConstraint('container_id', 'name'),) . Output only the next line.
@app1.route('/<doc>/with/<other>')
Using the snippet: <|code_start|> @app1.route('/<container>/<doc>/edit') @ScopedNamedDocument.is_url_for( 'edit', _external=True, container=('parent', 'id'), doc='name' ) def sdoc_edit(container, doc): return f'edit {container} {doc}' @app1.route('/<doc>/app_only') @NamedDocument.is_url_for('app_only', _app=app1, doc='name') def doc_app_only(doc): return f'app_only {doc}' @app1.route('/<doc>/app1') @NamedDocument.is_url_for('per_app', _app=app1, doc='name') def doc_per_app1(doc): return f'per_app {doc}' @app2.route('/<doc>/app2') @NamedDocument.is_url_for('per_app', _app=app2, doc='name') def doc_per_app2(doc): return f'per_app {doc}' # --- Tests ------------------------------------------------------------------- <|code_end|> , determine the next line of code. You have imports: import unittest import pytest from flask import Flask from werkzeug.routing import BuildError from coaster.db import db from .test_sqlalchemy_models import Container, NamedDocument, ScopedNamedDocument and context (class names, function names, or code) available: # Path: coaster/db.py # def _set_sqlite_pragma(dbapi_connection, connection_record): # def _set_postgresql_timezone(dbapi_connection, connection_record): # # Path: tests/test_sqlalchemy_models.py # class Container(BaseMixin, db.Model): # __tablename__ = 'container' # name = Column(Unicode(80), nullable=True) # title = Column(Unicode(80), nullable=True) # # content = Column(Unicode(250)) # # class NamedDocument(BaseNameMixin, db.Model): # __tablename__ = 'named_document' # reserved_names = ['new'] # container_id = Column(Integer, ForeignKey('container.id')) # container = relationship(Container) # # content = Column(Unicode(250)) # # class ScopedNamedDocument(BaseScopedNameMixin, db.Model): # __tablename__ = 'scoped_named_document' # reserved_names = ['new'] # container_id = Column(Integer, ForeignKey('container.id')) # container = relationship(Container) # parent = synonym('container') # # content = Column(Unicode(250)) # __table_args__ = (UniqueConstraint('container_id', 'name'),) . Output only the next line.
class TestUrlForBase(unittest.TestCase):
Predict the next line after this snippet: <|code_start|> @app1.route('/<doc>/edit') @NamedDocument.is_url_for('edit', doc='name') def doc_edit(doc): return f'edit {doc}' @app1.route('/<doc>/upper') @NamedDocument.is_url_for('upper', doc=lambda d: d.name.upper()) def doc_upper(doc): return f'upper {doc}' # The unusual parameter `other='**other.name'` requires an explanation. # The first `other` refers to `<other>` in the URL. The second refers # to the parameter given to `NamedDocument.url_for` in the test below. @app1.route('/<doc>/with/<other>') @NamedDocument.is_url_for('with', doc='name', other='**other.name') def doc_with(doc, other): return f'{doc} with {other}' @app1.route('/<container>/<doc>') @ScopedNamedDocument.is_url_for('view', container='parent.id', doc='name') def sdoc_view(container, doc): return f'view {container} {doc}' @app1.route('/<container>/<doc>/edit') @ScopedNamedDocument.is_url_for( <|code_end|> using the current file's imports: import unittest import pytest from flask import Flask from werkzeug.routing import BuildError from coaster.db import db from .test_sqlalchemy_models import Container, NamedDocument, ScopedNamedDocument and any relevant context from other files: # Path: coaster/db.py # def _set_sqlite_pragma(dbapi_connection, connection_record): # def _set_postgresql_timezone(dbapi_connection, connection_record): # # Path: tests/test_sqlalchemy_models.py # class Container(BaseMixin, db.Model): # __tablename__ = 'container' # name = Column(Unicode(80), nullable=True) # title = Column(Unicode(80), nullable=True) # # content = Column(Unicode(250)) # # class NamedDocument(BaseNameMixin, db.Model): # __tablename__ = 'named_document' # reserved_names = ['new'] # container_id = Column(Integer, ForeignKey('container.id')) # container = relationship(Container) # # content = Column(Unicode(250)) # # class ScopedNamedDocument(BaseScopedNameMixin, db.Model): # __tablename__ = 'scoped_named_document' # reserved_names = ['new'] # container_id = Column(Integer, ForeignKey('container.id')) # container = relationship(Container) # parent = synonym('container') # # content = Column(Unicode(250)) # __table_args__ = (UniqueConstraint('container_id', 'name'),) . Output only the next line.
'edit', _external=True, container=('parent', 'id'), doc='name'
Given the following code snippet before the placeholder: <|code_start|>) def sdoc_edit(container, doc): return f'edit {container} {doc}' @app1.route('/<doc>/app_only') @NamedDocument.is_url_for('app_only', _app=app1, doc='name') def doc_app_only(doc): return f'app_only {doc}' @app1.route('/<doc>/app1') @NamedDocument.is_url_for('per_app', _app=app1, doc='name') def doc_per_app1(doc): return f'per_app {doc}' @app2.route('/<doc>/app2') @NamedDocument.is_url_for('per_app', _app=app2, doc='name') def doc_per_app2(doc): return f'per_app {doc}' # --- Tests ------------------------------------------------------------------- class TestUrlForBase(unittest.TestCase): app = app1 def setUp(self): <|code_end|> , predict the next line using imports from the current file: import unittest import pytest from flask import Flask from werkzeug.routing import BuildError from coaster.db import db from .test_sqlalchemy_models import Container, NamedDocument, ScopedNamedDocument and context including class names, function names, and sometimes code from other files: # Path: coaster/db.py # def _set_sqlite_pragma(dbapi_connection, connection_record): # def _set_postgresql_timezone(dbapi_connection, connection_record): # # Path: tests/test_sqlalchemy_models.py # class Container(BaseMixin, db.Model): # __tablename__ = 'container' # name = Column(Unicode(80), nullable=True) # title = Column(Unicode(80), nullable=True) # # content = Column(Unicode(250)) # # class NamedDocument(BaseNameMixin, db.Model): # __tablename__ = 'named_document' # reserved_names = ['new'] # container_id = Column(Integer, ForeignKey('container.id')) # container = relationship(Container) # # content = Column(Unicode(250)) # # class ScopedNamedDocument(BaseScopedNameMixin, db.Model): # __tablename__ = 'scoped_named_document' # reserved_names = ['new'] # container_id = Column(Integer, ForeignKey('container.id')) # container = relationship(Container) # parent = synonym('container') # # content = Column(Unicode(250)) # __table_args__ = (UniqueConstraint('container_id', 'name'),) . Output only the next line.
self.ctx = self.app.test_request_context()
Predict the next line after this snippet: <|code_start|> .. cmdoption:: -C, --numc Number of controllers to start, to handle simultaneous requests. Each controller requires one AMQP connection. Default is 2. .. cmdoption:: --sup-interval Supervisor schedule Interval in seconds. Default is 5. """ from __future__ import absolute_import from __future__ import with_statement BANNER = """ -------------- cyme@%(id)s v%(version)s ---- **** ----- --- * *** * -- [Configuration] -- * - **** --- . url: http://%(addr)s:%(port)s - ** ---------- . broker: %(broker)s - ** ---------- . logfile: %(logfile)s@%(loglevel)s - ** ---------- . sup: interval=%(sup.interval)s - ** ---------- . presence: interval=%(presence.interval)s - *** --- * --- . controllers: #%(controllers)s <|code_end|> using the current file's imports: import atexit import os from importlib import import_module from celery import current_app as celery from celery.bin.base import daemon_options from celery.platforms import (create_pidlock, detached, signals, set_process_title) from celery.utils import instantiate from cell.utils import cached_property, shortuuid from .base import CymeCommand, Option from cyme.utils import LazyProgressBar from cyme.utils import LazyProgressBar and any relevant context from other files: # Path: cyme/management/commands/base.py # def die(msg, exitcode=1): # def __init__(self, env=None, *args, **kwargs): # def setup_default_env(self, env): # def get_version(self): # def enter_instance_dir(self): # def install_cry_handler(self): # def install_rdb_handler(self): # def redirect_stdouts_to_logger(self, loglevel='INFO', logfile=None, # redirect_level='WARNING'): # def setup_logging(self, loglevel='WARNING', logfile=None, **kwargs): # def prepare_options(self, broker=None, loglevel=None, logfile=None, # pidfile=None, detach=None, instance_dir=None, **kwargs): # def print_help(self, prog_name=None, subcommand=None): # def instance_dir(self): # class CymeCommand(CeleryCommand): # LOG_LEVELS = LOG_LEVELS . Output only the next line.
-- ******* ---- . instancedir: %(instance_dir)s
Next line prediction: <|code_start|> Custom instance directory (default is :file:`instances/``) Must be writeable by the user cyme-branch runs as. .. cmdoption:: -C, --numc Number of controllers to start, to handle simultaneous requests. Each controller requires one AMQP connection. Default is 2. .. cmdoption:: --sup-interval Supervisor schedule Interval in seconds. Default is 5. """ from __future__ import absolute_import from __future__ import with_statement BANNER = """ -------------- cyme@%(id)s v%(version)s ---- **** ----- --- * *** * -- [Configuration] -- * - **** --- . url: http://%(addr)s:%(port)s - ** ---------- . broker: %(broker)s - ** ---------- . logfile: %(logfile)s@%(loglevel)s - ** ---------- . sup: interval=%(sup.interval)s <|code_end|> . Use current file imports: (import atexit import os from importlib import import_module from celery import current_app as celery from celery.bin.base import daemon_options from celery.platforms import (create_pidlock, detached, signals, set_process_title) from celery.utils import instantiate from cell.utils import cached_property, shortuuid from .base import CymeCommand, Option from cyme.utils import LazyProgressBar from cyme.utils import LazyProgressBar) and context including class names, function names, or small code snippets from other files: # Path: cyme/management/commands/base.py # def die(msg, exitcode=1): # def __init__(self, env=None, *args, **kwargs): # def setup_default_env(self, env): # def get_version(self): # def enter_instance_dir(self): # def install_cry_handler(self): # def install_rdb_handler(self): # def redirect_stdouts_to_logger(self, loglevel='INFO', logfile=None, # redirect_level='WARNING'): # def setup_logging(self, loglevel='WARNING', logfile=None, **kwargs): # def prepare_options(self, broker=None, loglevel=None, logfile=None, # pidfile=None, detach=None, instance_dir=None, **kwargs): # def print_help(self, prog_name=None, subcommand=None): # def instance_dir(self): # class CymeCommand(CeleryCommand): # LOG_LEVELS = LOG_LEVELS . Output only the next line.
- ** ---------- . presence: interval=%(presence.interval)s
Predict the next line after this snippet: <|code_start|> model = knn.KNNRegressor(k=5, distance_func=distance.euclidean) model.fit(X_train, y_train) predictions = model.predict(X_test) print("regression mse", mean_squared_error(y_test, predictions)) def classification(): X, y = make_classification( n_samples=500, n_features=5, n_informative=5, n_redundant=0, n_repeated=0, n_classes=3, random_state=1111, class_sep=1.5, ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1111) clf = knn.KNNClassifier(k=5, distance_func=distance.euclidean) clf.fit(X_train, y_train) predictions = clf.predict(X_test) print("classification accuracy", accuracy(y_test, predictions)) if __name__ == "__main__": regression() <|code_end|> using the current file's imports: from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from sklearn.datasets import make_classification from sklearn.datasets import make_regression from scipy.spatial import distance from mla import knn from mla.metrics.metrics import mean_squared_error, accuracy and any relevant context from other files: # Path: mla/knn.py # class KNNBase(BaseEstimator): # class KNNClassifier(KNNBase): # class KNNRegressor(KNNBase): # def __init__(self, k=5, distance_func=euclidean): # def aggregate(self, neighbors_targets): # def _predict(self, X=None): # def _predict_x(self, x): # def aggregate(self, neighbors_targets): # def aggregate(self, neighbors_targets): # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) # # @unhot # def accuracy(actual, predicted): # return 1.0 - classification_error(actual, predicted) . Output only the next line.
classification()
Using the snippet: <|code_start|>try: except ImportError: def regression(): # Generate a random regression problem X, y = make_regression( <|code_end|> , determine the next line of code. You have imports: from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from sklearn.datasets import make_classification from sklearn.datasets import make_regression from scipy.spatial import distance from mla import knn from mla.metrics.metrics import mean_squared_error, accuracy and context (class names, function names, or code) available: # Path: mla/knn.py # class KNNBase(BaseEstimator): # class KNNClassifier(KNNBase): # class KNNRegressor(KNNBase): # def __init__(self, k=5, distance_func=euclidean): # def aggregate(self, neighbors_targets): # def _predict(self, X=None): # def _predict_x(self, x): # def aggregate(self, neighbors_targets): # def aggregate(self, neighbors_targets): # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) # # @unhot # def accuracy(actual, predicted): # return 1.0 - classification_error(actual, predicted) . Output only the next line.
n_samples=500, n_features=5, n_informative=5, n_targets=1, noise=0.05, random_state=1111, bias=0.5
Based on the snippet: <|code_start|> try: except ImportError: logging.basicConfig(level=logging.DEBUG) def classification(): # Generate a random binary classification problem. <|code_end|> , predict the immediate next line with the help of imports: import logging from sklearn.datasets import make_classification from sklearn.datasets import make_regression from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from mla.ensemble.gbm import GradientBoostingClassifier, GradientBoostingRegressor from mla.metrics.metrics import mean_squared_error and context (classes, functions, sometimes code) from other files: # Path: mla/ensemble/gbm.py # class GradientBoostingClassifier(GradientBoosting): # def fit(self, X, y=None): # # Convert labels from {0, 1} to {-1, 1} # y = (y * 2) - 1 # self.loss = LogisticLoss() # super(GradientBoostingClassifier, self).fit(X, y) # # class GradientBoostingRegressor(GradientBoosting): # def fit(self, X, y=None): # self.loss = LeastSquaresLoss() # super(GradientBoostingRegressor, self).fit(X, y) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) . Output only the next line.
X, y = make_classification(
Predict the next line after this snippet: <|code_start|> try: except ImportError: logging.basicConfig(level=logging.DEBUG) def classification(): # Generate a random binary classification problem. X, y = make_classification( <|code_end|> using the current file's imports: import logging from sklearn.datasets import make_classification from sklearn.datasets import make_regression from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from mla.ensemble.gbm import GradientBoostingClassifier, GradientBoostingRegressor from mla.metrics.metrics import mean_squared_error and any relevant context from other files: # Path: mla/ensemble/gbm.py # class GradientBoostingClassifier(GradientBoosting): # def fit(self, X, y=None): # # Convert labels from {0, 1} to {-1, 1} # y = (y * 2) - 1 # self.loss = LogisticLoss() # super(GradientBoostingClassifier, self).fit(X, y) # # class GradientBoostingRegressor(GradientBoosting): # def fit(self, X, y=None): # self.loss = LeastSquaresLoss() # super(GradientBoostingRegressor, self).fit(X, y) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) . Output only the next line.
n_samples=350, n_features=15, n_informative=10, random_state=1111, n_classes=2, class_sep=1.0, n_redundant=0
Here is a snippet: <|code_start|> try: except ImportError: logging.basicConfig(level=logging.DEBUG) def classification(): # Generate a random binary classification problem. X, y = make_classification( n_samples=350, n_features=15, n_informative=10, random_state=1111, n_classes=2, class_sep=1.0, n_redundant=0 ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=1111) model = GradientBoostingClassifier(n_estimators=50, max_depth=4, max_features=8, learning_rate=0.1) model.fit(X_train, y_train) predictions = model.predict(X_test) print(predictions) print(predictions.min()) print(predictions.max()) print("classification, roc auc score: %s" % roc_auc_score(y_test, predictions)) def regression(): # Generate a random regression problem X, y = make_regression( n_samples=500, n_features=5, n_informative=5, n_targets=1, noise=0.05, random_state=1111, bias=0.5 ) <|code_end|> . Write the next line using the current file imports: import logging from sklearn.datasets import make_classification from sklearn.datasets import make_regression from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from mla.ensemble.gbm import GradientBoostingClassifier, GradientBoostingRegressor from mla.metrics.metrics import mean_squared_error and context from other files: # Path: mla/ensemble/gbm.py # class GradientBoostingClassifier(GradientBoosting): # def fit(self, X, y=None): # # Convert labels from {0, 1} to {-1, 1} # y = (y * 2) - 1 # self.loss = LogisticLoss() # super(GradientBoostingClassifier, self).fit(X, y) # # class GradientBoostingRegressor(GradientBoosting): # def fit(self, X, y=None): # self.loss = LeastSquaresLoss() # super(GradientBoostingRegressor, self).fit(X, y) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) , which may include functions, classes, or code. Output only the next line.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1111)
Here is a snippet: <|code_start|> def classification(): # Generate a random binary classification problem. X, y = make_classification( n_samples=1000, n_features=10, n_informative=10, random_state=1111, n_classes=2, class_sep=2.5, n_redundant=0 ) <|code_end|> . Write the next line using the current file imports: from sklearn.datasets import make_classification from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from mla.naive_bayes import NaiveBayesClassifier and context from other files: # Path: mla/naive_bayes.py # class NaiveBayesClassifier(BaseEstimator): # """Gaussian Naive Bayes.""" # # # Binary problem. # n_classes = 2 # # def fit(self, X, y=None): # self._setup_input(X, y) # # Check target labels # assert list(np.unique(y)) == [0, 1] # # # Mean and variance for each class and feature combination # self._mean = np.zeros((self.n_classes, self.n_features), dtype=np.float64) # self._var = np.zeros((self.n_classes, self.n_features), dtype=np.float64) # # self._priors = np.zeros(self.n_classes, dtype=np.float64) # # for c in range(self.n_classes): # # Filter features by class # X_c = X[y == c] # # # Calculate mean, variance, prior for each class # self._mean[c, :] = X_c.mean(axis=0) # self._var[c, :] = X_c.var(axis=0) # self._priors[c] = X_c.shape[0] / float(X.shape[0]) # # def _predict(self, X=None): # # Apply _predict_proba for each row # predictions = np.apply_along_axis(self._predict_row, 1, X) # # # Normalize probabilities so that each row will sum up to 1.0 # return softmax(predictions) # # def _predict_row(self, x): # """Predict log likelihood for given row.""" # output = [] # for y in range(self.n_classes): # prior = np.log(self._priors[y]) # posterior = np.log(self._pdf(y, x)).sum() # prediction = prior + posterior # # output.append(prediction) # return output # # def _pdf(self, n_class, x): # """Calculate Gaussian PDF for each feature.""" # # mean = self._mean[n_class] # var = self._var[n_class] # # numerator = np.exp(-(x - mean) ** 2 / (2 * var)) # denominator = np.sqrt(2 * np.pi * var) # return numerator / denominator , which may include functions, classes, or code. Output only the next line.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1111)
Given snippet: <|code_start|># coding=utf-8 try: except ImportError: @pytest.fixture def dataset(): # Generate a random binary classification problem. return make_classification( n_samples=1000, n_features=100, n_informative=75, random_state=1111, n_classes=2, class_sep=2.5 ) # TODO: fix @pytest.mark.skip() def test_PCA(dataset): X, y = dataset X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1111) p = PCA(50, solver="eigen") # fit PCA with training set, not the entire dataset p.fit(X_train) X_train_reduced = p.transform(X_train) X_test_reduced = p.transform(X_test) model = RandomForestClassifier(n_estimators=25, max_depth=5) model.fit(X_train_reduced, y_train) <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from sklearn.datasets import make_classification from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from mla.ensemble import RandomForestClassifier from mla.pca import PCA and context: # Path: mla/ensemble/random_forest.py # class RandomForestClassifier(RandomForest): # def __init__(self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="entropy"): # super(RandomForestClassifier, self).__init__( # n_estimators=n_estimators, # max_features=max_features, # min_samples_split=min_samples_split, # max_depth=max_depth, # criterion=criterion, # ) # # if criterion == "entropy": # self.criterion = information_gain # else: # raise ValueError() # # # Initialize empty trees # for _ in range(self.n_estimators): # self.trees.append(Tree(criterion=self.criterion)) # # def _predict(self, X=None): # y_shape = np.unique(self.y).shape[0] # predictions = np.zeros((X.shape[0], y_shape)) # # for i in range(X.shape[0]): # row_pred = np.zeros(y_shape) # for tree in self.trees: # row_pred += tree.predict_row(X[i, :]) # # row_pred /= self.n_estimators # predictions[i, :] = row_pred # return predictions # # Path: mla/pca.py # class PCA(BaseEstimator): # y_required = False # # def __init__(self, n_components, solver="svd"): # """Principal component analysis (PCA) implementation. # # Transforms a dataset of possibly correlated values into n linearly # uncorrelated components. The components are ordered such that the first # has the largest possible variance and each following component as the # largest possible variance given the previous components. This causes # the early components to contain most of the variability in the dataset. # # Parameters # ---------- # n_components : int # solver : str, default 'svd' # {'svd', 'eigen'} # """ # self.solver = solver # self.n_components = n_components # self.components = None # self.mean = None # # def fit(self, X, y=None): # self.mean = np.mean(X, axis=0) # self._decompose(X) # # def _decompose(self, X): # # Mean centering # X = X.copy() # X -= self.mean # # if self.solver == "svd": # _, s, Vh = svd(X, full_matrices=True) # elif self.solver == "eigen": # s, Vh = np.linalg.eig(np.cov(X.T)) # Vh = Vh.T # # s_squared = s ** 2 # variance_ratio = s_squared / s_squared.sum() # logging.info("Explained variance ratio: %s" % (variance_ratio[0: self.n_components])) # self.components = Vh[0: self.n_components] # # def transform(self, X): # X = X.copy() # X -= self.mean # return np.dot(X, self.components.T) # # def _predict(self, X=None): # return self.transform(X) which might include code, classes, or functions. Output only the next line.
predictions = model.predict(X_test_reduced)[:, 1]
Predict the next line after this snippet: <|code_start|># coding=utf-8 try: except ImportError: @pytest.fixture def dataset(): # Generate a random binary classification problem. <|code_end|> using the current file's imports: import pytest from sklearn.datasets import make_classification from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from mla.ensemble import RandomForestClassifier from mla.pca import PCA and any relevant context from other files: # Path: mla/ensemble/random_forest.py # class RandomForestClassifier(RandomForest): # def __init__(self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="entropy"): # super(RandomForestClassifier, self).__init__( # n_estimators=n_estimators, # max_features=max_features, # min_samples_split=min_samples_split, # max_depth=max_depth, # criterion=criterion, # ) # # if criterion == "entropy": # self.criterion = information_gain # else: # raise ValueError() # # # Initialize empty trees # for _ in range(self.n_estimators): # self.trees.append(Tree(criterion=self.criterion)) # # def _predict(self, X=None): # y_shape = np.unique(self.y).shape[0] # predictions = np.zeros((X.shape[0], y_shape)) # # for i in range(X.shape[0]): # row_pred = np.zeros(y_shape) # for tree in self.trees: # row_pred += tree.predict_row(X[i, :]) # # row_pred /= self.n_estimators # predictions[i, :] = row_pred # return predictions # # Path: mla/pca.py # class PCA(BaseEstimator): # y_required = False # # def __init__(self, n_components, solver="svd"): # """Principal component analysis (PCA) implementation. # # Transforms a dataset of possibly correlated values into n linearly # uncorrelated components. The components are ordered such that the first # has the largest possible variance and each following component as the # largest possible variance given the previous components. This causes # the early components to contain most of the variability in the dataset. # # Parameters # ---------- # n_components : int # solver : str, default 'svd' # {'svd', 'eigen'} # """ # self.solver = solver # self.n_components = n_components # self.components = None # self.mean = None # # def fit(self, X, y=None): # self.mean = np.mean(X, axis=0) # self._decompose(X) # # def _decompose(self, X): # # Mean centering # X = X.copy() # X -= self.mean # # if self.solver == "svd": # _, s, Vh = svd(X, full_matrices=True) # elif self.solver == "eigen": # s, Vh = np.linalg.eig(np.cov(X.T)) # Vh = Vh.T # # s_squared = s ** 2 # variance_ratio = s_squared / s_squared.sum() # logging.info("Explained variance ratio: %s" % (variance_ratio[0: self.n_components])) # self.components = Vh[0: self.n_components] # # def transform(self, X): # X = X.copy() # X -= self.mean # return np.dot(X, self.components.T) # # def _predict(self, X=None): # return self.transform(X) . Output only the next line.
return make_classification(
Next line prediction: <|code_start|> logging.basicConfig(level=logging.DEBUG) def print_curve(rbm): def moving_average(a, n=25): ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n plt.plot(moving_average(rbm.errors)) plt.show() X = np.random.uniform(0, 1, (1500, 10)) rbm = RBM(n_hidden=10, max_epochs=200, batch_size=10, learning_rate=0.1) rbm.fit(X) <|code_end|> . Use current file imports: (import logging import numpy as np from mla.rbm import RBM from matplotlib import pyplot as plt) and context including class names, function names, or small code snippets from other files: # Path: mla/rbm.py # class RBM(BaseEstimator): # y_required = False # # def __init__(self, n_hidden=128, learning_rate=0.1, batch_size=10, max_epochs=100): # """Bernoulli Restricted Boltzmann Machine (RBM) # # Parameters # ---------- # # n_hidden : int, default 128 # The number of hidden units. # learning_rate : float, default 0.1 # batch_size : int, default 10 # max_epochs : int, default 100 # """ # self.max_epochs = max_epochs # self.batch_size = batch_size # self.lr = learning_rate # self.n_hidden = n_hidden # # def fit(self, X, y=None): # self.n_visible = X.shape[1] # self._init_weights() # self._setup_input(X, y) # self._train() # # def _init_weights(self): # # self.W = np.random.randn(self.n_visible, self.n_hidden) * 0.1 # # # Bias for visible and hidden units # self.bias_v = np.zeros(self.n_visible, dtype=np.float32) # self.bias_h = np.zeros(self.n_hidden, dtype=np.float32) # # self.errors = [] # # def _train(self): # """Use CD-1 training procedure, basically an exact inference for `positive_associations`, # followed by a "non burn-in" block Gibbs Sampling for the `negative_associations`.""" # # for i in range(self.max_epochs): # error = 0 # for batch in batch_iterator(self.X, batch_size=self.batch_size): # positive_hidden = sigmoid(np.dot(batch, self.W) + self.bias_h) # hidden_states = self._sample(positive_hidden) # sample hidden state h1 # positive_associations = np.dot(batch.T, positive_hidden) # # negative_visible = sigmoid(np.dot(hidden_states, self.W.T) + self.bias_v) # negative_visible = self._sample(negative_visible) # use the sampled hidden state h1 to sample v1 # negative_hidden = sigmoid(np.dot(negative_visible, self.W) + self.bias_h) # negative_associations = np.dot(negative_visible.T, negative_hidden) # # lr = self.lr / float(batch.shape[0]) # self.W += lr * ((positive_associations - negative_associations) / float(self.batch_size)) # self.bias_h += lr * (negative_hidden.sum(axis=0) - negative_associations.sum(axis=0)) # self.bias_v += lr * (np.asarray(batch.sum(axis=0)).squeeze() - negative_visible.sum(axis=0)) # # error += np.sum((batch - negative_visible) ** 2) # # self.errors.append(error) # logging.info("Iteration %s, error %s" % (i, error)) # logging.debug("Weights: %s" % self.W) # logging.debug("Hidden bias: %s" % self.bias_h) # logging.debug("Visible bias: %s" % self.bias_v) # # def _sample(self, X): # return X > np.random.random_sample(size=X.shape) # # def _predict(self, X=None): # return sigmoid(np.dot(X, self.W) + self.bias_h) . Output only the next line.
print_curve(rbm)
Here is a snippet: <|code_start|>from __future__ import division def test_data_validation(): with pytest.raises(ValueError): check_data([], 1) with pytest.raises(ValueError): check_data([1, 2, 3], [3, 2]) a, b = check_data([1, 2, 3], [3, 2, 1]) assert np.all(a == np.array([1, 2, 3])) assert np.all(b == np.array([3, 2, 1])) <|code_end|> . Write the next line using the current file imports: import numpy as np import pytest from numpy.testing import assert_almost_equal from mla.metrics.base import check_data, validate_input from mla.metrics.metrics import get_metric and context from other files: # Path: mla/metrics/base.py # def check_data(a, b): # if not isinstance(a, np.ndarray): # a = np.array(a) # # if not isinstance(b, np.ndarray): # b = np.array(b) # # if type(a) != type(b): # raise ValueError("Type mismatch: %s and %s" % (type(a), type(b))) # # if a.size != b.size: # raise ValueError("Arrays must be equal in length.") # return a, b # # def validate_input(function): # def wrapper(a, b): # a, b = check_data(a, b) # return function(a, b) # # return wrapper # # Path: mla/metrics/metrics.py # def get_metric(name): # """Return metric function by name""" # try: # return globals()[name] # except Exception: # raise ValueError("Invalid metric function.") , which may include functions, classes, or code. Output only the next line.
def metric(name):
Here is a snippet: <|code_start|> with pytest.raises(ValueError): check_data([1, 2, 3], [3, 2]) a, b = check_data([1, 2, 3], [3, 2, 1]) assert np.all(a == np.array([1, 2, 3])) assert np.all(b == np.array([3, 2, 1])) def metric(name): return validate_input(get_metric(name)) def test_classification_error(): f = metric("classification_error") assert f([1, 2, 3, 4], [1, 2, 3, 4]) == 0 assert f([1, 2, 3, 4], [1, 2, 3, 5]) == 0.25 assert f([1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0]) == (1.0 / 6) def test_absolute_error(): f = metric("absolute_error") assert f([3], [5]) == [2] assert f([-1], [-4]) == [3] def test_mean_absolute_error(): f = metric("mean_absolute_error") assert f([1, 2, 3], [1, 2, 3]) == 0 <|code_end|> . Write the next line using the current file imports: import numpy as np import pytest from numpy.testing import assert_almost_equal from mla.metrics.base import check_data, validate_input from mla.metrics.metrics import get_metric and context from other files: # Path: mla/metrics/base.py # def check_data(a, b): # if not isinstance(a, np.ndarray): # a = np.array(a) # # if not isinstance(b, np.ndarray): # b = np.array(b) # # if type(a) != type(b): # raise ValueError("Type mismatch: %s and %s" % (type(a), type(b))) # # if a.size != b.size: # raise ValueError("Arrays must be equal in length.") # return a, b # # def validate_input(function): # def wrapper(a, b): # a, b = check_data(a, b) # return function(a, b) # # return wrapper # # Path: mla/metrics/metrics.py # def get_metric(name): # """Return metric function by name""" # try: # return globals()[name] # except Exception: # raise ValueError("Invalid metric function.") , which may include functions, classes, or code. Output only the next line.
assert f([1, 2, 3], [3, 2, 1]) == 4 / 3
Given snippet: <|code_start|> assert np.all(a == np.array([1, 2, 3])) assert np.all(b == np.array([3, 2, 1])) def metric(name): return validate_input(get_metric(name)) def test_classification_error(): f = metric("classification_error") assert f([1, 2, 3, 4], [1, 2, 3, 4]) == 0 assert f([1, 2, 3, 4], [1, 2, 3, 5]) == 0.25 assert f([1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0]) == (1.0 / 6) def test_absolute_error(): f = metric("absolute_error") assert f([3], [5]) == [2] assert f([-1], [-4]) == [3] def test_mean_absolute_error(): f = metric("mean_absolute_error") assert f([1, 2, 3], [1, 2, 3]) == 0 assert f([1, 2, 3], [3, 2, 1]) == 4 / 3 def test_squared_error(): f = metric("squared_error") assert f([1], [1]) == [0] <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np import pytest from numpy.testing import assert_almost_equal from mla.metrics.base import check_data, validate_input from mla.metrics.metrics import get_metric and context: # Path: mla/metrics/base.py # def check_data(a, b): # if not isinstance(a, np.ndarray): # a = np.array(a) # # if not isinstance(b, np.ndarray): # b = np.array(b) # # if type(a) != type(b): # raise ValueError("Type mismatch: %s and %s" % (type(a), type(b))) # # if a.size != b.size: # raise ValueError("Arrays must be equal in length.") # return a, b # # def validate_input(function): # def wrapper(a, b): # a, b = check_data(a, b) # return function(a, b) # # return wrapper # # Path: mla/metrics/metrics.py # def get_metric(name): # """Return metric function by name""" # try: # return globals()[name] # except Exception: # raise ValueError("Invalid metric function.") which might include code, classes, or functions. Output only the next line.
assert f([3], [1]) == [4]
Predict the next line for this snippet: <|code_start|> def kmeans_example(plot=False): X, y = make_blobs(centers=4, n_samples=500, n_features=2, shuffle=True, random_state=42) clusters = len(np.unique(y)) k = KMeans(K=clusters, max_iters=150, init="++") <|code_end|> with the help of current file imports: import numpy as np from sklearn.datasets import make_blobs from mla.kmeans import KMeans and context from other files: # Path: mla/kmeans.py # class KMeans(BaseEstimator): # """Partition a dataset into K clusters. # # Finds clusters by repeatedly assigning each data point to the cluster with # the nearest centroid and iterating until the assignments converge (meaning # they don't change during an iteration) or the maximum number of iterations # is reached. # # Parameters # ---------- # # K : int # The number of clusters into which the dataset is partitioned. # max_iters: int # The maximum iterations of assigning points to the nearest cluster. # Short-circuited by the assignments converging on their own. # init: str, default 'random' # The name of the method used to initialize the first clustering. # # 'random' - Randomly select values from the dataset as the K centroids. # '++' - Select a random first centroid from the dataset, then select # K - 1 more centroids by choosing values from the dataset with a # probability distribution proportional to the squared distance # from each point's closest existing cluster. Attempts to create # larger distances between initial clusters to improve convergence # rates and avoid degenerate cases. # """ # # y_required = False # # def __init__(self, K=5, max_iters=100, init="random"): # self.K = K # self.max_iters = max_iters # self.clusters = [[] for _ in range(self.K)] # self.centroids = [] # self.init = init # # def _initialize_centroids(self, init): # """Set the initial centroids.""" # # if init == "random": # self.centroids = [self.X[x] for x in random.sample(range(self.n_samples), self.K)] # elif init == "++": # self.centroids = [random.choice(self.X)] # while len(self.centroids) < self.K: # self.centroids.append(self._choose_next_center()) # else: # raise ValueError("Unknown type of init parameter") # # def _predict(self, X=None): # """Perform clustering on the dataset.""" # self._initialize_centroids(self.init) # centroids = self.centroids # # # Optimize clusters # for _ in range(self.max_iters): # self._assign(centroids) # centroids_old = centroids # centroids = [self._get_centroid(cluster) for cluster in self.clusters] # # if self._is_converged(centroids_old, centroids): # break # # self.centroids = centroids # # return self._get_predictions() # # def _get_predictions(self): # predictions = np.empty(self.n_samples) # # for i, cluster in enumerate(self.clusters): # for index in cluster: # predictions[index] = i # return predictions # # def _assign(self, centroids): # # for row in range(self.n_samples): # for i, cluster in enumerate(self.clusters): # if row in cluster: # self.clusters[i].remove(row) # break # # closest = self._closest(row, centroids) # self.clusters[closest].append(row) # # def _closest(self, fpoint, centroids): # """Find the closest centroid for a point.""" # closest_index = None # closest_distance = None # for i, point in enumerate(centroids): # dist = euclidean_distance(self.X[fpoint], point) # if closest_index is None or dist < closest_distance: # closest_index = i # closest_distance = dist # return closest_index # # def _get_centroid(self, cluster): # """Get values by indices and take the mean.""" # return [np.mean(np.take(self.X[:, i], cluster)) for i in range(self.n_features)] # # def _dist_from_centers(self): # """Calculate distance from centers.""" # return np.array([min([euclidean_distance(x, c) for c in self.centroids]) for x in self.X]) # # def _choose_next_center(self): # distances = self._dist_from_centers() # squared_distances = distances ** 2 # probs = squared_distances / squared_distances.sum() # ind = np.random.choice(self.X.shape[0], 1, p=probs)[0] # return self.X[ind] # # def _is_converged(self, centroids_old, centroids): # """Check if the distance between old and new centroids is zero.""" # distance = 0 # for i in range(self.K): # distance += euclidean_distance(centroids_old[i], centroids[i]) # return distance == 0 # # def plot(self, ax=None, holdon=False): # sns.set(style="white") # palette = sns.color_palette("hls", self.K + 1) # data = self.X # # if ax is None: # _, ax = plt.subplots() # # for i, index in enumerate(self.clusters): # point = np.array(data[index]).T # ax.scatter(*point, c=[palette[i], ]) # # for point in self.centroids: # ax.scatter(*point, marker="x", linewidths=10) # # if not holdon: # plt.show() , which may contain function names, class names, or code. Output only the next line.
k.fit(X)
Predict the next line after this snippet: <|code_start|>try: except ImportError: # Change to DEBUG to see convergence logging.basicConfig(level=logging.ERROR) def regression(): # Generate a random regression problem X, y = make_regression( n_samples=10000, n_features=100, n_informative=75, n_targets=1, noise=0.05, random_state=1111, bias=0.5 ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1111) model = LinearRegression(lr=0.01, max_iters=2000, penalty="l2", C=0.03) model.fit(X_train, y_train) predictions = model.predict(X_test) print("regression mse", mean_squared_error(y_test, predictions)) def classification(): # Generate a random binary classification problem. X, y = make_classification( n_samples=1000, n_features=100, n_informative=75, random_state=1111, n_classes=2, class_sep=2.5 ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1111) model = LogisticRegression(lr=0.01, max_iters=500, penalty="l1", C=0.01) model.fit(X_train, y_train) <|code_end|> using the current file's imports: import logging from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from sklearn.datasets import make_classification from sklearn.datasets import make_regression from mla.linear_models import LinearRegression, LogisticRegression from mla.metrics.metrics import mean_squared_error, accuracy and any relevant context from other files: # Path: mla/linear_models.py # class LinearRegression(BasicRegression): # """Linear regression with gradient descent optimizer.""" # # def _loss(self, w): # loss = self.cost_func(self.y, np.dot(self.X, w)) # return self._add_penalty(loss, w) # # def init_cost(self): # self.cost_func = mean_squared_error # # class LogisticRegression(BasicRegression): # """Binary logistic regression with gradient descent optimizer.""" # # def init_cost(self): # self.cost_func = binary_crossentropy # # def _loss(self, w): # loss = self.cost_func(self.y, self.sigmoid(np.dot(self.X, w))) # return self._add_penalty(loss, w) # # @staticmethod # def sigmoid(x): # return 0.5 * (np.tanh(0.5 * x) + 1) # # def _predict(self, X=None): # X = self._add_intercept(X) # return self.sigmoid(X.dot(self.theta)) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) # # @unhot # def accuracy(actual, predicted): # return 1.0 - classification_error(actual, predicted) . Output only the next line.
predictions = model.predict(X_test)
Based on the snippet: <|code_start|> def regression(): # Generate a random regression problem X, y = make_regression( n_samples=10000, n_features=100, n_informative=75, n_targets=1, noise=0.05, random_state=1111, bias=0.5 ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1111) model = LinearRegression(lr=0.01, max_iters=2000, penalty="l2", C=0.03) model.fit(X_train, y_train) predictions = model.predict(X_test) print("regression mse", mean_squared_error(y_test, predictions)) def classification(): # Generate a random binary classification problem. X, y = make_classification( n_samples=1000, n_features=100, n_informative=75, random_state=1111, n_classes=2, class_sep=2.5 ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1111) model = LogisticRegression(lr=0.01, max_iters=500, penalty="l1", C=0.01) model.fit(X_train, y_train) predictions = model.predict(X_test) print("classification accuracy", accuracy(y_test, predictions)) if __name__ == "__main__": regression() <|code_end|> , predict the immediate next line with the help of imports: import logging from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from sklearn.datasets import make_classification from sklearn.datasets import make_regression from mla.linear_models import LinearRegression, LogisticRegression from mla.metrics.metrics import mean_squared_error, accuracy and context (classes, functions, sometimes code) from other files: # Path: mla/linear_models.py # class LinearRegression(BasicRegression): # """Linear regression with gradient descent optimizer.""" # # def _loss(self, w): # loss = self.cost_func(self.y, np.dot(self.X, w)) # return self._add_penalty(loss, w) # # def init_cost(self): # self.cost_func = mean_squared_error # # class LogisticRegression(BasicRegression): # """Binary logistic regression with gradient descent optimizer.""" # # def init_cost(self): # self.cost_func = binary_crossentropy # # def _loss(self, w): # loss = self.cost_func(self.y, self.sigmoid(np.dot(self.X, w))) # return self._add_penalty(loss, w) # # @staticmethod # def sigmoid(x): # return 0.5 * (np.tanh(0.5 * x) + 1) # # def _predict(self, X=None): # X = self._add_intercept(X) # return self.sigmoid(X.dot(self.theta)) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) # # @unhot # def accuracy(actual, predicted): # return 1.0 - classification_error(actual, predicted) . Output only the next line.
classification()
Predict the next line after this snippet: <|code_start|> try: except ImportError: # Change to DEBUG to see convergence logging.basicConfig(level=logging.ERROR) def regression(): # Generate a random regression problem <|code_end|> using the current file's imports: import logging from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from sklearn.datasets import make_classification from sklearn.datasets import make_regression from mla.linear_models import LinearRegression, LogisticRegression from mla.metrics.metrics import mean_squared_error, accuracy and any relevant context from other files: # Path: mla/linear_models.py # class LinearRegression(BasicRegression): # """Linear regression with gradient descent optimizer.""" # # def _loss(self, w): # loss = self.cost_func(self.y, np.dot(self.X, w)) # return self._add_penalty(loss, w) # # def init_cost(self): # self.cost_func = mean_squared_error # # class LogisticRegression(BasicRegression): # """Binary logistic regression with gradient descent optimizer.""" # # def init_cost(self): # self.cost_func = binary_crossentropy # # def _loss(self, w): # loss = self.cost_func(self.y, self.sigmoid(np.dot(self.X, w))) # return self._add_penalty(loss, w) # # @staticmethod # def sigmoid(x): # return 0.5 * (np.tanh(0.5 * x) + 1) # # def _predict(self, X=None): # X = self._add_intercept(X) # return self.sigmoid(X.dot(self.theta)) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) # # @unhot # def accuracy(actual, predicted): # return 1.0 - classification_error(actual, predicted) . Output only the next line.
X, y = make_regression(
Using the snippet: <|code_start|> try: except ImportError: logging.basicConfig(level=logging.DEBUG) def classification(): # Generate a random binary classification problem. X, y = make_classification( n_samples=500, n_features=10, n_informative=10, random_state=1111, n_classes=2, class_sep=2.5, n_redundant=0 ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=1111) model = RandomForestClassifier(n_estimators=10, max_depth=4) model.fit(X_train, y_train) predictions_prob = model.predict(X_test)[:, 1] predictions = np.argmax(model.predict(X_test), axis=1) #print(predictions.shape) print("classification, roc auc score: %s" % roc_auc_score(y_test, predictions_prob)) <|code_end|> , determine the next line of code. You have imports: import logging import numpy as np from sklearn.datasets import make_classification from sklearn.datasets import make_regression from sklearn.metrics import roc_auc_score, accuracy_score from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from mla.ensemble.random_forest import RandomForestClassifier, RandomForestRegressor from mla.metrics.metrics import mean_squared_error and context (class names, function names, or code) available: # Path: mla/ensemble/random_forest.py # class RandomForestClassifier(RandomForest): # def __init__(self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="entropy"): # super(RandomForestClassifier, self).__init__( # n_estimators=n_estimators, # max_features=max_features, # min_samples_split=min_samples_split, # max_depth=max_depth, # criterion=criterion, # ) # # if criterion == "entropy": # self.criterion = information_gain # else: # raise ValueError() # # # Initialize empty trees # for _ in range(self.n_estimators): # self.trees.append(Tree(criterion=self.criterion)) # # def _predict(self, X=None): # y_shape = np.unique(self.y).shape[0] # predictions = np.zeros((X.shape[0], y_shape)) # # for i in range(X.shape[0]): # row_pred = np.zeros(y_shape) # for tree in self.trees: # row_pred += tree.predict_row(X[i, :]) # # row_pred /= self.n_estimators # predictions[i, :] = row_pred # return predictions # # class RandomForestRegressor(RandomForest): # def __init__(self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="mse"): # super(RandomForestRegressor, self).__init__( # n_estimators=n_estimators, # max_features=max_features, # min_samples_split=min_samples_split, # max_depth=max_depth, # ) # # if criterion == "mse": # self.criterion = mse_criterion # else: # raise ValueError() # # # Initialize empty regression trees # for _ in range(self.n_estimators): # self.trees.append(Tree(regression=True, criterion=self.criterion)) # # def _predict(self, X=None): # predictions = np.zeros((X.shape[0], self.n_estimators)) # for i, tree in enumerate(self.trees): # predictions[:, i] = tree.predict(X) # return predictions.mean(axis=1) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) . Output only the next line.
print("classification, accuracy score: %s" % accuracy_score(y_test, predictions))
Here is a snippet: <|code_start|>try: except ImportError: logging.basicConfig(level=logging.DEBUG) def classification(): # Generate a random binary classification problem. X, y = make_classification( n_samples=500, n_features=10, n_informative=10, random_state=1111, n_classes=2, class_sep=2.5, n_redundant=0 ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=1111) model = RandomForestClassifier(n_estimators=10, max_depth=4) model.fit(X_train, y_train) predictions_prob = model.predict(X_test)[:, 1] predictions = np.argmax(model.predict(X_test), axis=1) #print(predictions.shape) print("classification, roc auc score: %s" % roc_auc_score(y_test, predictions_prob)) print("classification, accuracy score: %s" % accuracy_score(y_test, predictions)) def regression(): # Generate a random regression problem X, y = make_regression( n_samples=500, n_features=5, n_informative=5, n_targets=1, noise=0.05, random_state=1111, bias=0.5 ) <|code_end|> . Write the next line using the current file imports: import logging import numpy as np from sklearn.datasets import make_classification from sklearn.datasets import make_regression from sklearn.metrics import roc_auc_score, accuracy_score from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from mla.ensemble.random_forest import RandomForestClassifier, RandomForestRegressor from mla.metrics.metrics import mean_squared_error and context from other files: # Path: mla/ensemble/random_forest.py # class RandomForestClassifier(RandomForest): # def __init__(self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="entropy"): # super(RandomForestClassifier, self).__init__( # n_estimators=n_estimators, # max_features=max_features, # min_samples_split=min_samples_split, # max_depth=max_depth, # criterion=criterion, # ) # # if criterion == "entropy": # self.criterion = information_gain # else: # raise ValueError() # # # Initialize empty trees # for _ in range(self.n_estimators): # self.trees.append(Tree(criterion=self.criterion)) # # def _predict(self, X=None): # y_shape = np.unique(self.y).shape[0] # predictions = np.zeros((X.shape[0], y_shape)) # # for i in range(X.shape[0]): # row_pred = np.zeros(y_shape) # for tree in self.trees: # row_pred += tree.predict_row(X[i, :]) # # row_pred /= self.n_estimators # predictions[i, :] = row_pred # return predictions # # class RandomForestRegressor(RandomForest): # def __init__(self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="mse"): # super(RandomForestRegressor, self).__init__( # n_estimators=n_estimators, # max_features=max_features, # min_samples_split=min_samples_split, # max_depth=max_depth, # ) # # if criterion == "mse": # self.criterion = mse_criterion # else: # raise ValueError() # # # Initialize empty regression trees # for _ in range(self.n_estimators): # self.trees.append(Tree(regression=True, criterion=self.criterion)) # # def _predict(self, X=None): # predictions = np.zeros((X.shape[0], self.n_estimators)) # for i, tree in enumerate(self.trees): # predictions[:, i] = tree.predict(X) # return predictions.mean(axis=1) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) , which may include functions, classes, or code. Output only the next line.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1111)
Predict the next line for this snippet: <|code_start|> try: except ImportError: logging.basicConfig(level=logging.DEBUG) <|code_end|> with the help of current file imports: import logging import numpy as np from sklearn.datasets import make_classification from sklearn.datasets import make_regression from sklearn.metrics import roc_auc_score, accuracy_score from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split from mla.ensemble.random_forest import RandomForestClassifier, RandomForestRegressor from mla.metrics.metrics import mean_squared_error and context from other files: # Path: mla/ensemble/random_forest.py # class RandomForestClassifier(RandomForest): # def __init__(self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="entropy"): # super(RandomForestClassifier, self).__init__( # n_estimators=n_estimators, # max_features=max_features, # min_samples_split=min_samples_split, # max_depth=max_depth, # criterion=criterion, # ) # # if criterion == "entropy": # self.criterion = information_gain # else: # raise ValueError() # # # Initialize empty trees # for _ in range(self.n_estimators): # self.trees.append(Tree(criterion=self.criterion)) # # def _predict(self, X=None): # y_shape = np.unique(self.y).shape[0] # predictions = np.zeros((X.shape[0], y_shape)) # # for i in range(X.shape[0]): # row_pred = np.zeros(y_shape) # for tree in self.trees: # row_pred += tree.predict_row(X[i, :]) # # row_pred /= self.n_estimators # predictions[i, :] = row_pred # return predictions # # class RandomForestRegressor(RandomForest): # def __init__(self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="mse"): # super(RandomForestRegressor, self).__init__( # n_estimators=n_estimators, # max_features=max_features, # min_samples_split=min_samples_split, # max_depth=max_depth, # ) # # if criterion == "mse": # self.criterion = mse_criterion # else: # raise ValueError() # # # Initialize empty regression trees # for _ in range(self.n_estimators): # self.trees.append(Tree(regression=True, criterion=self.criterion)) # # def _predict(self, X=None): # predictions = np.zeros((X.shape[0], self.n_estimators)) # for i, tree in enumerate(self.trees): # predictions[:, i] = tree.predict(X) # return predictions.mean(axis=1) # # Path: mla/metrics/metrics.py # def mean_squared_error(actual, predicted): # return np.mean(squared_error(actual, predicted)) , which may contain function names, class names, or code. Output only the next line.
def classification():
Using the snippet: <|code_start|># -*- coding: utf-8 -*- def test_bp_add(debugger): src_file = "src/test_breakpoint_basic.cpp" line = 5 debugger.load_binary(os.path.join(TEST_SRC_DIR, "test_breakpoint_basic")) assert debugger.breakpoint_manager.add_breakpoint(src_file, line) assert not debugger.breakpoint_manager.add_breakpoint(src_file, 100) assert not debugger.breakpoint_manager.add_breakpoint("", line) debugger.breakpoint_manager.add_breakpoint(src_file, 1) assert len(debugger.breakpoint_manager.get_breakpoints()) == 2 <|code_end|> , determine the next line of code. You have imports: import os from tests.conftest import TEST_SRC_DIR and context (class names, function names, or code) available: # Path: tests/conftest.py # TEST_SRC_DIR = os.path.join(TEST_DIR, "src") . Output only the next line.
def test_bp_remove(debugger):
Continue the code snippet: <|code_start|> def is_data_available(fd, timeout=0.05): return len(select.select([fd], [], [], timeout)[0]) != 0 def __init__(self, width=-1, height=-1): Gtk.ScrolledWindow.__init__(self) self.set_hexpand(True) self.set_vexpand(True) self.set_size_request(width, height) self.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS) self.textview = Gtk.TextView() font_desc = Pango.FontDescription.from_string("monospace") if font_desc: self.textview.modify_font(font_desc) self.add(self.textview) self.show_all() @require_gui_thread def get_buffer(self): return self.textview.get_buffer() @require_gui_thread def get_cursor_iter(self): cursor_rectangle = self.textview.get_cursor_locations(None)[0] return self.textview.get_iter_at_location(cursor_rectangle.x, <|code_end|> . Use current file imports: from gi.repository import Gtk from gi.repository import Gdk from gi.repository import Pango from debugger.enums import ProcessState from debugger.util import Logger from gui_util import require_gui_thread, run_on_gui import select import threading import time import traceback and context (classes, functions, or code) from other files: # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # Path: debugger/util.py # class Logger(object): # """ # Helper class for logging. # """ # logger = None # # @staticmethod # def init_logger(level): # logging.basicConfig() # Logger.logger = logging.getLogger("debugger") # Logger.logger.setLevel(level) # # @staticmethod # def debug(message, *args, **kwargs): # Logger.logger.debug(message, *args, **kwargs) # # @staticmethod # def info(message, *args, **kwargs): # Logger.logger.info(message, *args, **kwargs) . Output only the next line.
cursor_rectangle.y)
Continue the code snippet: <|code_start|> self.write(text) def _read_data(self, debugger, stream_attr, data_tag): stream_file = getattr(debugger.io_manager, stream_attr) if Console.is_data_available(stream_file): data = stream_file.readline() if len(data) > 0: run_on_gui(self._write_on_ui, data, data_tag) def _watch_file_thread(self, debugger): while not self.stop_thread.is_set(): try: self._read_data(debugger, "stdout", "stdout") self._read_data(debugger, "stderr", "stderr") except: time.sleep(0.01) def _stop_watch_thread(self): if self.watch_thread is not None: self.stop_thread.set() self.watch_thread.join() self.watch_thread = None self.stop_thread.clear() def _watch_output(self, debugger): self._stop_watch_thread() self.watch_thread = threading.Thread(target=self._watch_file_thread, <|code_end|> . Use current file imports: from gi.repository import Gtk from gi.repository import Gdk from gi.repository import Pango from debugger.enums import ProcessState from debugger.util import Logger from gui_util import require_gui_thread, run_on_gui import select import threading import time import traceback and context (classes, functions, or code) from other files: # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # Path: debugger/util.py # class Logger(object): # """ # Helper class for logging. # """ # logger = None # # @staticmethod # def init_logger(level): # logging.basicConfig() # Logger.logger = logging.getLogger("debugger") # Logger.logger.setLevel(level) # # @staticmethod # def debug(message, *args, **kwargs): # Logger.logger.debug(message, *args, **kwargs) # # @staticmethod # def info(message, *args, **kwargs): # Logger.logger.info(message, *args, **kwargs) . Output only the next line.
args=[debugger])
Predict the next line for this snippet: <|code_start|># # This file is part of Devi. # # Devi is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License, or # (at your option) any later version. # # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class EnvVarWidget(Gtk.Box): def __init__(self, *args, **kwargs): Gtk.Box.__init__(self, *args, **kwargs) self.set_orientation(Gtk.Orientation.HORIZONTAL) self.entry_name = Gtk.Entry() self.entry_value = Gtk.Entry() self.pack_start(self.entry_name, False, False, 0) <|code_end|> with the help of current file imports: from gi.repository import Gtk from debugger.debugger_api import StartupInfo from gui.dialog import FileOpenDialog from gui.gui_util import require_gui_thread and context from other files: # Path: debugger/debugger_api.py # class StartupInfo(object): # def __init__(self, cmd_arguments="", working_directory="", env_vars=None): # """ # @type cmd_arguments: str # @type working_directory: str # @type env_vars: list of tuple of (str, str) # """ # self.cmd_arguments = cmd_arguments # self.working_directory = working_directory # self.env_vars = env_vars if env_vars is not None else [] # # def copy(self): # return StartupInfo(self.cmd_arguments, # self.working_directory, # list(self.env_vars)) # # def __repr__(self): # return "StartupInfo: [{}, {}, {}]".format( # self.cmd_arguments, self.working_directory, self.env_vars # ) # # Path: gui/dialog.py # class FileOpenDialog(object): # @staticmethod # @require_gui_thread # def select_file(title, parent, initial_path=None): # """ # @type title: str # @type parent: Gtk.Widget # @type initial_path: str # @rtype: str # """ # dialog = FileOpenDialog(title, parent, False, initial_path) # # file = dialog.open() # dialog.destroy() # # return file # # @staticmethod # @require_gui_thread # def select_folder(title, parent, initial_path=None): # """ # @type title: str # @type parent: Gtk.Widget # @type initial_path: str # @rtype: str # """ # dialog = FileOpenDialog(title, parent, True, initial_path) # # folder = dialog.open() # dialog.destroy() # # return folder # # def __init__(self, title, parent, directory=False, initial_path=None): # """ # Opens a file or folder chooser dialog. # @type title: str # @type parent: Gtk.Widget # @type directory: bool # @type initial_path: str # """ # type = Gtk.FileChooserAction.OPEN # # if directory: # type = Gtk.FileChooserAction.SELECT_FOLDER # # self.dialog = Gtk.FileChooserDialog(title, parent, # type, # (Gtk.STOCK_CANCEL, # Gtk.ResponseType.CANCEL, # Gtk.STOCK_OPEN, # Gtk.ResponseType.OK)) # # if initial_path: # self.dialog.set_current_folder(initial_path) # # @require_gui_thread # def open(self): # response = self.dialog.run() # if response == Gtk.ResponseType.OK: # return self.dialog.get_filename() # else: # return None # # @require_gui_thread # def destroy(self): # self.dialog.destroy() # # Path: gui/gui_util.py # def require_gui_thread(func): # """ # @type func: callable # @rtype: callable # """ # def check(*args, **kwargs): # assert_is_gui_thread() # return func(*args, **kwargs) # return check , which may contain function names, class names, or code. Output only the next line.
self.pack_start(self.entry_value, False, False, 0)
Predict the next line after this snippet: <|code_start|># Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class EnvVarWidget(Gtk.Box): def __init__(self, *args, **kwargs): Gtk.Box.__init__(self, *args, **kwargs) self.set_orientation(Gtk.Orientation.HORIZONTAL) self.entry_name = Gtk.Entry() self.entry_value = Gtk.Entry() self.pack_start(self.entry_name, False, False, 0) self.pack_start(self.entry_value, False, False, 0) @property def name(self): return self.entry_name.get_text() @property def value(self): <|code_end|> using the current file's imports: from gi.repository import Gtk from debugger.debugger_api import StartupInfo from gui.dialog import FileOpenDialog from gui.gui_util import require_gui_thread and any relevant context from other files: # Path: debugger/debugger_api.py # class StartupInfo(object): # def __init__(self, cmd_arguments="", working_directory="", env_vars=None): # """ # @type cmd_arguments: str # @type working_directory: str # @type env_vars: list of tuple of (str, str) # """ # self.cmd_arguments = cmd_arguments # self.working_directory = working_directory # self.env_vars = env_vars if env_vars is not None else [] # # def copy(self): # return StartupInfo(self.cmd_arguments, # self.working_directory, # list(self.env_vars)) # # def __repr__(self): # return "StartupInfo: [{}, {}, {}]".format( # self.cmd_arguments, self.working_directory, self.env_vars # ) # # Path: gui/dialog.py # class FileOpenDialog(object): # @staticmethod # @require_gui_thread # def select_file(title, parent, initial_path=None): # """ # @type title: str # @type parent: Gtk.Widget # @type initial_path: str # @rtype: str # """ # dialog = FileOpenDialog(title, parent, False, initial_path) # # file = dialog.open() # dialog.destroy() # # return file # # @staticmethod # @require_gui_thread # def select_folder(title, parent, initial_path=None): # """ # @type title: str # @type parent: Gtk.Widget # @type initial_path: str # @rtype: str # """ # dialog = FileOpenDialog(title, parent, True, initial_path) # # folder = dialog.open() # dialog.destroy() # # return folder # # def __init__(self, title, parent, directory=False, initial_path=None): # """ # Opens a file or folder chooser dialog. # @type title: str # @type parent: Gtk.Widget # @type directory: bool # @type initial_path: str # """ # type = Gtk.FileChooserAction.OPEN # # if directory: # type = Gtk.FileChooserAction.SELECT_FOLDER # # self.dialog = Gtk.FileChooserDialog(title, parent, # type, # (Gtk.STOCK_CANCEL, # Gtk.ResponseType.CANCEL, # Gtk.STOCK_OPEN, # Gtk.ResponseType.OK)) # # if initial_path: # self.dialog.set_current_folder(initial_path) # # @require_gui_thread # def open(self): # response = self.dialog.run() # if response == Gtk.ResponseType.OK: # return self.dialog.get_filename() # else: # return None # # @require_gui_thread # def destroy(self): # self.dialog.destroy() # # Path: gui/gui_util.py # def require_gui_thread(func): # """ # @type func: callable # @rtype: callable # """ # def check(*args, **kwargs): # assert_is_gui_thread() # return func(*args, **kwargs) # return check . Output only the next line.
return self.entry_value.get_text()
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Jakub Beranek # # This file is part of Devi. # # Devi is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License, or # (at your option) any later version. # # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class NoDrawableFound(BaseException): pass class FontStyle(object): <|code_end|> . Use current file imports: import cairo from enum import Enum from debugger.debugee import Variable from geometry import Margin, RectangleBBox, Padding from mouse import ClickHandler from size import Size from vector import Vector from widgets import ValueEntry from debugger.util import EventBroadcaster, Logger from gui.gui_util import require_gui_thread and context (classes, functions, or code) from other files: # Path: debugger/debugee.py # class Variable(object): # """ # Represents a variable with type. # """ # @staticmethod # def from_lldb(lldb_var): # """ # @type lldb_var: lldb.SBValue # @rtype: Variable # """ # address = str(lldb_var.addr) # name = lldb_var.name # value = lldb_var.value # # if value is None: # value = lldb_var.summary # # type = Type.from_lldb(lldb_var.type) # path = lldb_var.path # # var = Variable(address, name, value, type, path) # # if type.is_composite(): # for i in xrange(lldb_var.num_children): # var.add_child(Variable.from_lldb(lldb_var.GetChildAtIndex(i))) # # return var # # def __init__(self, address=None, name=None, value=None, type=None, # path=None): # """ # @type address: str # @type name: str # @type value: str # @type type: Type # @type path: str # """ # self.address = address # self.name = name # self._value = value # self.type = type # self.path = path # # self.children = [] # # self.on_value_changed = EventBroadcaster() # # self.constraint = None # # def add_child(self, child): # """ # Adds a child variable to this variable. # @type child: Variable # """ # self.children.append(child) # child.on_value_changed.redirect(self.on_value_changed) # # def set_constraint(self, constraint): # """ # @type constraint: callable # """ # self.constraint = constraint # # def get_index_by_address(self, address): # """ # @type address: str # @rtype: int # """ # if address == self.address: # return 0 # else: # return None # # @property # def value(self): # return self._value # # @value.setter # def value(self, value): # if self.constraint and not self.constraint(self, value): # return # # self._value = value # self.on_value_changed.notify(self) # # def __repr__(self): # return "Variable: {0} ({1}) = {2}".format(self.type, # self.path # if self.path # else self.name, # self.value) # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) # # class Logger(object): # """ # Helper class for logging. # """ # logger = None # # @staticmethod # def init_logger(level): # logging.basicConfig() # Logger.logger = logging.getLogger("debugger") # Logger.logger.setLevel(level) # # @staticmethod # def debug(message, *args, **kwargs): # Logger.logger.debug(message, *args, **kwargs) # # @staticmethod # def info(message, *args, **kwargs): # Logger.logger.info(message, *args, **kwargs) # # Path: gui/gui_util.py # def require_gui_thread(func): # """ # @type func: callable # @rtype: callable # """ # def check(*args, **kwargs): # assert_is_gui_thread() # return func(*args, **kwargs) # return check . Output only the next line.
def __init__(self, color=None, bold=False, italic=False, font_family=None):
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- TEST_FILE = "test_frame" TEST_LINE = 6 def test_frame_list(debugger): def test_frame_list_cb(): assert len(debugger.thread_manager.get_frames()) == 2 setup_debugger(debugger, TEST_FILE, TEST_LINE, test_frame_list_cb) <|code_end|> . Use current file imports: import os from tests.conftest import setup_debugger and context (classes, functions, or code) from other files: # Path: tests/conftest.py # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) . Output only the next line.
def test_frame_properties(debugger):
Next line prediction: <|code_start|># -*- coding: utf-8 -*- def test_stop_no_launch(debugger): debugger.load_binary(os.path.join(TEST_SRC_DIR, "test_breakpoint_basic")) debugger.quit_program() def test_load_file(debugger): assert debugger.load_binary(os.path.join(TEST_SRC_DIR, "test_breakpoint_basic")) assert debugger.state.is_set(DebuggerState.BinaryLoaded) <|code_end|> . Use current file imports: (import os from debugger.enums import DebuggerState from tests.conftest import TEST_SRC_DIR) and context including class names, function names, or small code snippets from other files: # Path: debugger/enums.py # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 # # Path: tests/conftest.py # TEST_SRC_DIR = os.path.join(TEST_DIR, "src") . Output only the next line.
assert debugger.file_manager.get_main_source_file() == os.path.join(
Next line prediction: <|code_start|># -*- coding: utf-8 -*- def test_stop_no_launch(debugger): debugger.load_binary(os.path.join(TEST_SRC_DIR, "test_breakpoint_basic")) debugger.quit_program() <|code_end|> . Use current file imports: (import os from debugger.enums import DebuggerState from tests.conftest import TEST_SRC_DIR) and context including class names, function names, or small code snippets from other files: # Path: debugger/enums.py # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 # # Path: tests/conftest.py # TEST_SRC_DIR = os.path.join(TEST_DIR, "src") . Output only the next line.
def test_load_file(debugger):
Continue the code snippet: <|code_start|> def _open_file(self, attribute, mode, file_path): setattr(self, attribute, open(file_path, mode, buffering=0)) def _close_file(self, attribute): try: if getattr(self, attribute): getattr(self, attribute).close() setattr(self, attribute, None) except: pass def handle_io(self): if len(self.file_threads) > 0: return stdin, stdout, stderr = [util.create_pipe() for _ in xrange(3)] self.file_paths += (stdin, stdout, stderr) self._create_thread(["stdout", "r", stdout]) self._create_thread(["stderr", "r", stderr]) self._create_thread(["stdin", "w", stdin]) map(lambda thread: thread.start(), self.file_threads) return (stdin, stdout, stderr) def stop_io(self): <|code_end|> . Use current file imports: import os import threading from debugger import util, debugger_api and context (classes, functions, or code) from other files: # Path: debugger/util.py # def create_pipe(): # def get_root_path(path): # def init_logger(level): # def debug(message, *args, **kwargs): # def info(message, *args, **kwargs): # def __init__(self, time, callback): # def _callback(self): # def stop_repeating(self): # def dispatch(root_object, properties=None, arguments=None): # def __init__(self, required_state, current_state): # def __init__(self, enum_cls, initial_value=0): # def _check_cls(self, obj): # def set(self, value): # def unset(self, value): # def is_set(self, value): # def get_value(self): # def clear(self): # def __repr__(self): # def __init__(self): # def notify(self, *args, **kwargs): # def subscribe(self, listener): # def unsubscribe(self, listener): # def clear(self): # def redirect(self, broadcaster): # def __call__(self, *args, **kwargs): # def __init__(self, name=""): # def __enter__(self): # def __exit__(self, exc_type, exc_val, exc_tb): # def __init__(self): # def stop(self): # def add_job(self, fn, args, callback): # def _do_work(self): # class Logger(object): # class RepeatTimer(Thread): # class Dispatcher(object): # class BadStateError(Exception): # class Flags(object): # class EventBroadcaster(object): # class Profiler(object): # class Worker(Thread): # WORKER_ID = 0 # # Path: debugger/debugger_api.py # class ProcessExitedEventData(object): # class ProcessStoppedEventData(object): # class StartupInfo(object): # class HeapManager(object): # class IOManager(object): # class BreakpointManager(object): # class FileManager(object): # class ThreadManager(object): # class VariableManager(object): # class Debugger(object): # def __init__(self, return_code): # def __init__(self, stop_reason): # def __init__(self, cmd_arguments="", working_directory="", env_vars=None): # def copy(self): # def __repr__(self): # def __init__(self, debugger): # def watch(self): # def stop(self): # def find_block_by_address(self, addr): # def get_total_allocations(self): # def get_total_deallocations(self): # def __init__(self): # def handle_io(self): # def stop_io(self): # def __init__(self, debugger): # def add_breakpoint(self, location, line): # def toggle_breakpoint(self, location, line): # def get_breakpoints(self): # def find_breakpoint(self, location, line): # def remove_breakpoint(self, location, line): # def __init__(self, debugger): # def get_main_source_file(self): # def get_current_location(self): # def get_line_address(self, filename, line): # def disassemble(self, filename, line): # def disassemble_raw(self, filename, line): # def __init__(self, debugger): # def get_current_thread(self): # def get_thread_info(self): # def set_thread_by_index(self, thread_id): # def get_current_frame(self, with_variables=False): # def get_frames(self): # def get_frames_with_variables(self): # def change_frame(self, frame_index): # def __init__(self, debugger): # def get_type(self, expression, level=0): # def get_variable(self, expression, level=0): # def update_variable(self, variable): # def get_memory(self, address, count): # def get_registers(self): # def get_vector_items(self, vector): # def __init__(self): # def require_state(self, required_state): # def get_state(self): # def get_process_state(self): # def load_binary(self, binary_path): # def launch(self, startup_info=None): # def exec_continue(self): # def exec_pause(self): # def exec_step_over(self): # def exec_step_in(self): # def exec_step_out(self): # def quit_program(self, return_code=1): # def terminate(self): # def wait_for_stop(self): # def wait_for_exit(self): . Output only the next line.
map(lambda thread: thread.join(), self.file_threads)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Jakub Beranek # # This file is part of Devi. # # Devi is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License, or # (at your option) any later version. # # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class IOManager(debugger_api.IOManager): def __init__(self): super(IOManager, self).__init__() self.file_threads = [] <|code_end|> . Write the next line using the current file imports: import os import threading from debugger import util, debugger_api and context from other files: # Path: debugger/util.py # def create_pipe(): # def get_root_path(path): # def init_logger(level): # def debug(message, *args, **kwargs): # def info(message, *args, **kwargs): # def __init__(self, time, callback): # def _callback(self): # def stop_repeating(self): # def dispatch(root_object, properties=None, arguments=None): # def __init__(self, required_state, current_state): # def __init__(self, enum_cls, initial_value=0): # def _check_cls(self, obj): # def set(self, value): # def unset(self, value): # def is_set(self, value): # def get_value(self): # def clear(self): # def __repr__(self): # def __init__(self): # def notify(self, *args, **kwargs): # def subscribe(self, listener): # def unsubscribe(self, listener): # def clear(self): # def redirect(self, broadcaster): # def __call__(self, *args, **kwargs): # def __init__(self, name=""): # def __enter__(self): # def __exit__(self, exc_type, exc_val, exc_tb): # def __init__(self): # def stop(self): # def add_job(self, fn, args, callback): # def _do_work(self): # class Logger(object): # class RepeatTimer(Thread): # class Dispatcher(object): # class BadStateError(Exception): # class Flags(object): # class EventBroadcaster(object): # class Profiler(object): # class Worker(Thread): # WORKER_ID = 0 # # Path: debugger/debugger_api.py # class ProcessExitedEventData(object): # class ProcessStoppedEventData(object): # class StartupInfo(object): # class HeapManager(object): # class IOManager(object): # class BreakpointManager(object): # class FileManager(object): # class ThreadManager(object): # class VariableManager(object): # class Debugger(object): # def __init__(self, return_code): # def __init__(self, stop_reason): # def __init__(self, cmd_arguments="", working_directory="", env_vars=None): # def copy(self): # def __repr__(self): # def __init__(self, debugger): # def watch(self): # def stop(self): # def find_block_by_address(self, addr): # def get_total_allocations(self): # def get_total_deallocations(self): # def __init__(self): # def handle_io(self): # def stop_io(self): # def __init__(self, debugger): # def add_breakpoint(self, location, line): # def toggle_breakpoint(self, location, line): # def get_breakpoints(self): # def find_breakpoint(self, location, line): # def remove_breakpoint(self, location, line): # def __init__(self, debugger): # def get_main_source_file(self): # def get_current_location(self): # def get_line_address(self, filename, line): # def disassemble(self, filename, line): # def disassemble_raw(self, filename, line): # def __init__(self, debugger): # def get_current_thread(self): # def get_thread_info(self): # def set_thread_by_index(self, thread_id): # def get_current_frame(self, with_variables=False): # def get_frames(self): # def get_frames_with_variables(self): # def change_frame(self, frame_index): # def __init__(self, debugger): # def get_type(self, expression, level=0): # def get_variable(self, expression, level=0): # def update_variable(self, variable): # def get_memory(self, address, count): # def get_registers(self): # def get_vector_items(self, vector): # def __init__(self): # def require_state(self, required_state): # def get_state(self): # def get_process_state(self): # def load_binary(self, binary_path): # def launch(self, startup_info=None): # def exec_continue(self): # def exec_pause(self): # def exec_step_over(self): # def exec_step_in(self): # def exec_step_out(self): # def quit_program(self, return_code=1): # def terminate(self): # def wait_for_stop(self): # def wait_for_exit(self): , which may include functions, classes, or code. Output only the next line.
self.file_paths = []
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- TEST_FILE = "test_type" TEST_LINE = 51 def check_type(debugger, variable_name, type_name, type_category, basic_type_category=BasicTypeCategory.Invalid): type = debugger.variable_manager.get_type(variable_name) if isinstance(type_name, str): assert type.name == type_name elif hasattr(type_name, "__call__"): <|code_end|> , predict the next line using imports from the current file: from debugger.enums import TypeCategory, BasicTypeCategory from tests.conftest import setup_debugger and context including class names, function names, and sometimes code from other files: # Path: debugger/enums.py # class TypeCategory(Enum): # """ # Represents type of C/C++ type. # """ # Any = -1 # Array = 1 # BlockPointer = 2 # Builtin = 4 # Class = 8 # ComplexFloat = 16 # ComplexInteger = 32 # Enumeration = 64 # Function = 128 # Invalid = 0 # MemberPointer = 256 # ObjCInterface = 1024 # ObjCObject = 512 # ObjCObjectPointer = 2048 # Other = -2147483648 # Pointer = 4096 # CString = 4097 # Reference = 8192 # Struct = 16384 # Typedef = 32768 # Union = 65536 # Vector = 131072 # String = 42 # # def nice_name(self): # name_mappings = { # TypeCategory.Class: "class", # TypeCategory.Struct: "struct" # } # return name_mappings.get(self, str(self)) # # class BasicTypeCategory(Enum): # """ # Represents type of a primitive C/C++ type. # """ # Bool = 20 # Char = 2 # Char16 = 8 # Char32 = 9 # Double = 23 # DoubleComplex = 26 # Float = 22 # FloatComplex = 25 # Half = 21 # Int = 12 # Int128 = 18 # Invalid = 0 # Long = 14 # LongDouble = 24 # LongDoubleComplex = 27 # LongLong = 16 # NullPtr = 31 # ObjCClass = 29 # ObjCID = 28 # ObjCSel = 30 # Other = 32 # Short = 10 # SignedChar = 3 # SignedWChar = 6 # UnsignedChar = 4 # UnsignedInt = 13 # UnsignedInt128 = 19 # UnsignedLong = 15 # UnsignedLongLong = 17 # UnsignedShort = 11 # UnsignedWChar = 7 # Void = 1 # WChar = 5 # # @staticmethod # def is_char(type): # """ # @type type: BasicTypeCategory # @rtype: bool # """ # return type in (BasicTypeCategory.Char, # BasicTypeCategory.Char16, # BasicTypeCategory.Char32, # BasicTypeCategory.SignedChar, # BasicTypeCategory.UnsignedChar, # BasicTypeCategory.SignedWChar, # BasicTypeCategory.UnsignedWChar, # BasicTypeCategory.WChar) # # Path: tests/conftest.py # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) . Output only the next line.
assert type_name(type.name)
Given the following code snippet before the placeholder: <|code_start|> assert type_name(type.name) assert type.type_category == type_category assert type.basic_type_category == basic_type_category return type def test_types(debugger): def test_types_cb(): check_type(debugger, "varInt", "int", TypeCategory.Builtin, BasicTypeCategory.Int) check_type(debugger, "varUnsignedShort", "unsigned short", TypeCategory.Builtin, BasicTypeCategory.UnsignedShort) check_type(debugger, "varFloat", "float", TypeCategory.Builtin, BasicTypeCategory.Float) check_type(debugger, "varClassA", "classA", TypeCategory.Class) check_type(debugger, "varStructA", "structA", TypeCategory.Struct) check_type(debugger, "varUnionA", "unionA", TypeCategory.Union) check_type(debugger, "varEnumA", "enumA", TypeCategory.Enumeration) check_type(debugger, "varEnumB", "enumB", TypeCategory.Enumeration) type = check_type(debugger, "varVector", lambda name: name.startswith("std::vector<int>"), TypeCategory.Vector) assert type.child_type.name == "int" check_type(debugger, "varString", "std::string", TypeCategory.String) type = check_type(debugger, "varArray", "int [10]", TypeCategory.Array) assert type.count == 10 <|code_end|> , predict the next line using imports from the current file: from debugger.enums import TypeCategory, BasicTypeCategory from tests.conftest import setup_debugger and context including class names, function names, and sometimes code from other files: # Path: debugger/enums.py # class TypeCategory(Enum): # """ # Represents type of C/C++ type. # """ # Any = -1 # Array = 1 # BlockPointer = 2 # Builtin = 4 # Class = 8 # ComplexFloat = 16 # ComplexInteger = 32 # Enumeration = 64 # Function = 128 # Invalid = 0 # MemberPointer = 256 # ObjCInterface = 1024 # ObjCObject = 512 # ObjCObjectPointer = 2048 # Other = -2147483648 # Pointer = 4096 # CString = 4097 # Reference = 8192 # Struct = 16384 # Typedef = 32768 # Union = 65536 # Vector = 131072 # String = 42 # # def nice_name(self): # name_mappings = { # TypeCategory.Class: "class", # TypeCategory.Struct: "struct" # } # return name_mappings.get(self, str(self)) # # class BasicTypeCategory(Enum): # """ # Represents type of a primitive C/C++ type. # """ # Bool = 20 # Char = 2 # Char16 = 8 # Char32 = 9 # Double = 23 # DoubleComplex = 26 # Float = 22 # FloatComplex = 25 # Half = 21 # Int = 12 # Int128 = 18 # Invalid = 0 # Long = 14 # LongDouble = 24 # LongDoubleComplex = 27 # LongLong = 16 # NullPtr = 31 # ObjCClass = 29 # ObjCID = 28 # ObjCSel = 30 # Other = 32 # Short = 10 # SignedChar = 3 # SignedWChar = 6 # UnsignedChar = 4 # UnsignedInt = 13 # UnsignedInt128 = 19 # UnsignedLong = 15 # UnsignedLongLong = 17 # UnsignedShort = 11 # UnsignedWChar = 7 # Void = 1 # WChar = 5 # # @staticmethod # def is_char(type): # """ # @type type: BasicTypeCategory # @rtype: bool # """ # return type in (BasicTypeCategory.Char, # BasicTypeCategory.Char16, # BasicTypeCategory.Char32, # BasicTypeCategory.SignedChar, # BasicTypeCategory.UnsignedChar, # BasicTypeCategory.SignedWChar, # BasicTypeCategory.UnsignedWChar, # BasicTypeCategory.WChar) # # Path: tests/conftest.py # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) . Output only the next line.
assert type.child_type.name == "int"
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- TEST_FILE = "test_type" TEST_LINE = 51 def check_type(debugger, variable_name, type_name, type_category, basic_type_category=BasicTypeCategory.Invalid): type = debugger.variable_manager.get_type(variable_name) if isinstance(type_name, str): assert type.name == type_name <|code_end|> using the current file's imports: from debugger.enums import TypeCategory, BasicTypeCategory from tests.conftest import setup_debugger and any relevant context from other files: # Path: debugger/enums.py # class TypeCategory(Enum): # """ # Represents type of C/C++ type. # """ # Any = -1 # Array = 1 # BlockPointer = 2 # Builtin = 4 # Class = 8 # ComplexFloat = 16 # ComplexInteger = 32 # Enumeration = 64 # Function = 128 # Invalid = 0 # MemberPointer = 256 # ObjCInterface = 1024 # ObjCObject = 512 # ObjCObjectPointer = 2048 # Other = -2147483648 # Pointer = 4096 # CString = 4097 # Reference = 8192 # Struct = 16384 # Typedef = 32768 # Union = 65536 # Vector = 131072 # String = 42 # # def nice_name(self): # name_mappings = { # TypeCategory.Class: "class", # TypeCategory.Struct: "struct" # } # return name_mappings.get(self, str(self)) # # class BasicTypeCategory(Enum): # """ # Represents type of a primitive C/C++ type. # """ # Bool = 20 # Char = 2 # Char16 = 8 # Char32 = 9 # Double = 23 # DoubleComplex = 26 # Float = 22 # FloatComplex = 25 # Half = 21 # Int = 12 # Int128 = 18 # Invalid = 0 # Long = 14 # LongDouble = 24 # LongDoubleComplex = 27 # LongLong = 16 # NullPtr = 31 # ObjCClass = 29 # ObjCID = 28 # ObjCSel = 30 # Other = 32 # Short = 10 # SignedChar = 3 # SignedWChar = 6 # UnsignedChar = 4 # UnsignedInt = 13 # UnsignedInt128 = 19 # UnsignedLong = 15 # UnsignedLongLong = 17 # UnsignedShort = 11 # UnsignedWChar = 7 # Void = 1 # WChar = 5 # # @staticmethod # def is_char(type): # """ # @type type: BasicTypeCategory # @rtype: bool # """ # return type in (BasicTypeCategory.Char, # BasicTypeCategory.Char16, # BasicTypeCategory.Char32, # BasicTypeCategory.SignedChar, # BasicTypeCategory.UnsignedChar, # BasicTypeCategory.SignedWChar, # BasicTypeCategory.UnsignedWChar, # BasicTypeCategory.WChar) # # Path: tests/conftest.py # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) . Output only the next line.
elif hasattr(type_name, "__call__"):
Based on the snippet: <|code_start|> class ValueEntry(Gtk.Frame): @require_gui_thread def __init__(self, title, text): Gtk.Frame.__init__(self) self.set_label(title) self.set_label_align(0.0, 0.0) self.box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 0) self.box.set_margin_bottom(5) self.box.set_margin_left(2) self.text_entry = Gtk.Entry() self.text_entry.set_text(text) self.confirm_button = Gtk.Button(label="Set") self.get_style_context().add_class("value-entry") self.box.pack_start(self.text_entry, False, False, 0) self.box.pack_start(self.confirm_button, False, False, 5) self.add(self.box) self.show_all() self.confirm_button.connect("clicked", lambda btn: self._handle_confirm_click()) self.on_value_entered = EventBroadcaster() @require_gui_thread <|code_end|> , predict the immediate next line with the help of imports: from gi.repository import Gtk from gui.gui_util import require_gui_thread from debugger.util import EventBroadcaster and context (classes, functions, sometimes code) from other files: # Path: gui/gui_util.py # def require_gui_thread(func): # """ # @type func: callable # @rtype: callable # """ # def check(*args, **kwargs): # assert_is_gui_thread() # return func(*args, **kwargs) # return check # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) . Output only the next line.
def set_value(self, value):
Predict the next line after this snippet: <|code_start|># # This file is part of Devi. # # Devi is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License, or # (at your option) any later version. # # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class ValueEntry(Gtk.Frame): @require_gui_thread def __init__(self, title, text): Gtk.Frame.__init__(self) self.set_label(title) self.set_label_align(0.0, 0.0) self.box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 0) <|code_end|> using the current file's imports: from gi.repository import Gtk from gui.gui_util import require_gui_thread from debugger.util import EventBroadcaster and any relevant context from other files: # Path: gui/gui_util.py # def require_gui_thread(func): # """ # @type func: callable # @rtype: callable # """ # def check(*args, **kwargs): # assert_is_gui_thread() # return func(*args, **kwargs) # return check # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) . Output only the next line.
self.box.set_margin_bottom(5)
Continue the code snippet: <|code_start|># Devi is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License, or # (at your option) any later version. # # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class BreakpointChangeType(Enum): Create = 1 Delete = 2 class BreakpointRenderer(GtkSource.GutterRendererPixbuf): def __init__(self, source_window, breakpoint_img_path, execution_img_path, **properties): super(BreakpointRenderer, self).__init__(**properties) self.source_window = source_window self.bp_pixbuf = GdkPixbuf.Pixbuf.new_from_file(breakpoint_img_path) <|code_end|> . Use current file imports: from gi.repository import Gdk from gi.repository import GdkPixbuf from gi.repository import Gtk from gi.repository import GtkSource from enum import Enum from debugger.analysis.source_analyser import SourceAnalyzer from debugger.util import EventBroadcaster, Logger from debugger.enums import ProcessState, DebuggerState from gui_util import run_on_gui, require_gui_thread import os import paths and context (classes, functions, or code) from other files: # Path: debugger/analysis/source_analyser.py # class SourceAnalyzer(object): # def __init__(self, file_path=None): # self.tu = None # self.file = None # # if file_path: # self.set_file(file_path) # # def _create_tu_from_file(self, file_path): # return cindex.TranslationUnit.from_source(file_path, []) # # def _get_location(self, offset, column=None): # if column: # return cindex.SourceLocation.from_position(self.tu, self.file, # offset, # column) # else: # return cindex.SourceLocation.from_offset(self.tu, self.file, # offset) # # def set_file(self, file_path): # """ # Parses the given file and returns whether the parsing was successful. # @type file_path: str # @rtype: bool # """ # try: # self.tu = self._create_tu_from_file(file_path) # self.file = cindex.File.from_name(self.tu, file_path) # return True # except: # return False # # def get_symbol_name(self, line, column=None): # """ # Get's name of a symbol defined on the given line and column. # Returns None if no symbol was found or if no file is loaded. # @type line: int # @type column: int # @rtype: str | None # """ # if self.tu is None or self.file is None: # return None # # location = self._get_location(line, column) # cursor = cindex.Cursor.from_location(self.tu, location) # # return cursor.spelling # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) # # class Logger(object): # """ # Helper class for logging. # """ # logger = None # # @staticmethod # def init_logger(level): # logging.basicConfig() # Logger.logger = logging.getLogger("debugger") # Logger.logger.setLevel(level) # # @staticmethod # def debug(message, *args, **kwargs): # Logger.logger.debug(message, *args, **kwargs) # # @staticmethod # def info(message, *args, **kwargs): # Logger.logger.info(message, *args, **kwargs) # # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 . Output only the next line.
self.exec_pixbuf = GdkPixbuf.Pixbuf.new_from_file(execution_img_path)
Given snippet: <|code_start|># You should have received a copy of the GNU General Public License # along with Devi. If not, see <http://www.gnu.org/licenses/>. # class BreakpointChangeType(Enum): Create = 1 Delete = 2 class BreakpointRenderer(GtkSource.GutterRendererPixbuf): def __init__(self, source_window, breakpoint_img_path, execution_img_path, **properties): super(BreakpointRenderer, self).__init__(**properties) self.source_window = source_window self.bp_pixbuf = GdkPixbuf.Pixbuf.new_from_file(breakpoint_img_path) self.exec_pixbuf = GdkPixbuf.Pixbuf.new_from_file(execution_img_path) self.set_alignment(0.5, 0.5) self.set_size(15) self.set_padding(5, -1) def do_draw(self, cr, background_area, cell_area, start, end, state): line = start.get_line() if line in self.source_window.get_breakpoint_lines(): self.set_pixbuf(self.bp_pixbuf) <|code_end|> , continue by predicting the next line. Consider current file imports: from gi.repository import Gdk from gi.repository import GdkPixbuf from gi.repository import Gtk from gi.repository import GtkSource from enum import Enum from debugger.analysis.source_analyser import SourceAnalyzer from debugger.util import EventBroadcaster, Logger from debugger.enums import ProcessState, DebuggerState from gui_util import run_on_gui, require_gui_thread import os import paths and context: # Path: debugger/analysis/source_analyser.py # class SourceAnalyzer(object): # def __init__(self, file_path=None): # self.tu = None # self.file = None # # if file_path: # self.set_file(file_path) # # def _create_tu_from_file(self, file_path): # return cindex.TranslationUnit.from_source(file_path, []) # # def _get_location(self, offset, column=None): # if column: # return cindex.SourceLocation.from_position(self.tu, self.file, # offset, # column) # else: # return cindex.SourceLocation.from_offset(self.tu, self.file, # offset) # # def set_file(self, file_path): # """ # Parses the given file and returns whether the parsing was successful. # @type file_path: str # @rtype: bool # """ # try: # self.tu = self._create_tu_from_file(file_path) # self.file = cindex.File.from_name(self.tu, file_path) # return True # except: # return False # # def get_symbol_name(self, line, column=None): # """ # Get's name of a symbol defined on the given line and column. # Returns None if no symbol was found or if no file is loaded. # @type line: int # @type column: int # @rtype: str | None # """ # if self.tu is None or self.file is None: # return None # # location = self._get_location(line, column) # cursor = cindex.Cursor.from_location(self.tu, location) # # return cursor.spelling # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) # # class Logger(object): # """ # Helper class for logging. # """ # logger = None # # @staticmethod # def init_logger(level): # logging.basicConfig() # Logger.logger = logging.getLogger("debugger") # Logger.logger.setLevel(level) # # @staticmethod # def debug(message, *args, **kwargs): # Logger.logger.debug(message, *args, **kwargs) # # @staticmethod # def info(message, *args, **kwargs): # Logger.logger.info(message, *args, **kwargs) # # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 which might include code, classes, or functions. Output only the next line.
GtkSource.GutterRendererPixbuf.do_draw(self, cr, background_area,
Here is a snippet: <|code_start|># class BreakpointChangeType(Enum): Create = 1 Delete = 2 class BreakpointRenderer(GtkSource.GutterRendererPixbuf): def __init__(self, source_window, breakpoint_img_path, execution_img_path, **properties): super(BreakpointRenderer, self).__init__(**properties) self.source_window = source_window self.bp_pixbuf = GdkPixbuf.Pixbuf.new_from_file(breakpoint_img_path) self.exec_pixbuf = GdkPixbuf.Pixbuf.new_from_file(execution_img_path) self.set_alignment(0.5, 0.5) self.set_size(15) self.set_padding(5, -1) def do_draw(self, cr, background_area, cell_area, start, end, state): line = start.get_line() if line in self.source_window.get_breakpoint_lines(): self.set_pixbuf(self.bp_pixbuf) GtkSource.GutterRendererPixbuf.do_draw(self, cr, background_area, cell_area, <|code_end|> . Write the next line using the current file imports: from gi.repository import Gdk from gi.repository import GdkPixbuf from gi.repository import Gtk from gi.repository import GtkSource from enum import Enum from debugger.analysis.source_analyser import SourceAnalyzer from debugger.util import EventBroadcaster, Logger from debugger.enums import ProcessState, DebuggerState from gui_util import run_on_gui, require_gui_thread import os import paths and context from other files: # Path: debugger/analysis/source_analyser.py # class SourceAnalyzer(object): # def __init__(self, file_path=None): # self.tu = None # self.file = None # # if file_path: # self.set_file(file_path) # # def _create_tu_from_file(self, file_path): # return cindex.TranslationUnit.from_source(file_path, []) # # def _get_location(self, offset, column=None): # if column: # return cindex.SourceLocation.from_position(self.tu, self.file, # offset, # column) # else: # return cindex.SourceLocation.from_offset(self.tu, self.file, # offset) # # def set_file(self, file_path): # """ # Parses the given file and returns whether the parsing was successful. # @type file_path: str # @rtype: bool # """ # try: # self.tu = self._create_tu_from_file(file_path) # self.file = cindex.File.from_name(self.tu, file_path) # return True # except: # return False # # def get_symbol_name(self, line, column=None): # """ # Get's name of a symbol defined on the given line and column. # Returns None if no symbol was found or if no file is loaded. # @type line: int # @type column: int # @rtype: str | None # """ # if self.tu is None or self.file is None: # return None # # location = self._get_location(line, column) # cursor = cindex.Cursor.from_location(self.tu, location) # # return cursor.spelling # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) # # class Logger(object): # """ # Helper class for logging. # """ # logger = None # # @staticmethod # def init_logger(level): # logging.basicConfig() # Logger.logger = logging.getLogger("debugger") # Logger.logger.setLevel(level) # # @staticmethod # def debug(message, *args, **kwargs): # Logger.logger.debug(message, *args, **kwargs) # # @staticmethod # def info(message, *args, **kwargs): # Logger.logger.info(message, *args, **kwargs) # # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 , which may include functions, classes, or code. Output only the next line.
start, end, state)
Given the following code snippet before the placeholder: <|code_start|># (at your option) any later version. # # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class BreakpointChangeType(Enum): Create = 1 Delete = 2 class BreakpointRenderer(GtkSource.GutterRendererPixbuf): def __init__(self, source_window, breakpoint_img_path, execution_img_path, **properties): super(BreakpointRenderer, self).__init__(**properties) self.source_window = source_window self.bp_pixbuf = GdkPixbuf.Pixbuf.new_from_file(breakpoint_img_path) self.exec_pixbuf = GdkPixbuf.Pixbuf.new_from_file(execution_img_path) self.set_alignment(0.5, 0.5) self.set_size(15) <|code_end|> , predict the next line using imports from the current file: from gi.repository import Gdk from gi.repository import GdkPixbuf from gi.repository import Gtk from gi.repository import GtkSource from enum import Enum from debugger.analysis.source_analyser import SourceAnalyzer from debugger.util import EventBroadcaster, Logger from debugger.enums import ProcessState, DebuggerState from gui_util import run_on_gui, require_gui_thread import os import paths and context including class names, function names, and sometimes code from other files: # Path: debugger/analysis/source_analyser.py # class SourceAnalyzer(object): # def __init__(self, file_path=None): # self.tu = None # self.file = None # # if file_path: # self.set_file(file_path) # # def _create_tu_from_file(self, file_path): # return cindex.TranslationUnit.from_source(file_path, []) # # def _get_location(self, offset, column=None): # if column: # return cindex.SourceLocation.from_position(self.tu, self.file, # offset, # column) # else: # return cindex.SourceLocation.from_offset(self.tu, self.file, # offset) # # def set_file(self, file_path): # """ # Parses the given file and returns whether the parsing was successful. # @type file_path: str # @rtype: bool # """ # try: # self.tu = self._create_tu_from_file(file_path) # self.file = cindex.File.from_name(self.tu, file_path) # return True # except: # return False # # def get_symbol_name(self, line, column=None): # """ # Get's name of a symbol defined on the given line and column. # Returns None if no symbol was found or if no file is loaded. # @type line: int # @type column: int # @rtype: str | None # """ # if self.tu is None or self.file is None: # return None # # location = self._get_location(line, column) # cursor = cindex.Cursor.from_location(self.tu, location) # # return cursor.spelling # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) # # class Logger(object): # """ # Helper class for logging. # """ # logger = None # # @staticmethod # def init_logger(level): # logging.basicConfig() # Logger.logger = logging.getLogger("debugger") # Logger.logger.setLevel(level) # # @staticmethod # def debug(message, *args, **kwargs): # Logger.logger.debug(message, *args, **kwargs) # # @staticmethod # def info(message, *args, **kwargs): # Logger.logger.info(message, *args, **kwargs) # # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 . Output only the next line.
self.set_padding(5, -1)
Predict the next line for this snippet: <|code_start|> enumB = debugger.variable_manager.get_variable("enumB") assert enumB.value == "EnumB::B" setup_debugger(debugger, TEST_FILE, TEST_LINE, test_enum_cb) def test_union(debugger): def test_union_cb(): uniA = debugger.variable_manager.get_variable("uniA") assert uniA.children[0].value == "5" assert uniA.children[0].value == uniA.children[1].value assert uniA.children[0].address == uniA.children[1].address setup_debugger(debugger, TEST_FILE, TEST_LINE, test_union_cb) def test_function_pointer(debugger): def test_function_pointer_cb(): fn_pointer = debugger.variable_manager.get_variable("fn_pointer") assert fn_pointer.type.name == "int (*)(int, float)" assert re.match("0x(\w)+ <test\(int, float\)>", fn_pointer.value) setup_debugger(debugger, TEST_FILE, TEST_LINE, test_function_pointer_cb) def test_update_variable(debugger): def test_update_variable_cb(): a = debugger.variable_manager.get_variable("a") a.value = "8" <|code_end|> with the help of current file imports: import re from collections import Iterable from debugger.enums import TypeCategory from tests.conftest import setup_debugger and context from other files: # Path: debugger/enums.py # class TypeCategory(Enum): # """ # Represents type of C/C++ type. # """ # Any = -1 # Array = 1 # BlockPointer = 2 # Builtin = 4 # Class = 8 # ComplexFloat = 16 # ComplexInteger = 32 # Enumeration = 64 # Function = 128 # Invalid = 0 # MemberPointer = 256 # ObjCInterface = 1024 # ObjCObject = 512 # ObjCObjectPointer = 2048 # Other = -2147483648 # Pointer = 4096 # CString = 4097 # Reference = 8192 # Struct = 16384 # Typedef = 32768 # Union = 65536 # Vector = 131072 # String = 42 # # def nice_name(self): # name_mappings = { # TypeCategory.Class: "class", # TypeCategory.Struct: "struct" # } # return name_mappings.get(self, str(self)) # # Path: tests/conftest.py # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) , which may contain function names, class names, or code. Output only the next line.
assert debugger.variable_manager.get_variable("a").value == "8"
Next line prediction: <|code_start|>def check_variable(debugger, expression, value=None, size=None): variable = debugger.variable_manager.get_variable(expression) assert variable.path == expression if value is not None: assert variable.value == value if size: if isinstance(size, Iterable): assert variable.type.size in size else: assert variable.type.size == size return variable def test_values(debugger): def test_values_cb(): check_variable(debugger, "a", "5", int_size) check_variable(debugger, "b", "5.5", int_size) check_variable(debugger, "c", "true", 1) check_variable(debugger, "d", "hello") var = check_variable(debugger, "e") assert var.data_address == var.address assert var.max_size == 10 arr_item = debugger.variable_manager.get_variable("e[2]") assert arr_item.value == "3" assert var.get_index_by_address(arr_item.address) == 2 <|code_end|> . Use current file imports: (import re from collections import Iterable from debugger.enums import TypeCategory from tests.conftest import setup_debugger) and context including class names, function names, or small code snippets from other files: # Path: debugger/enums.py # class TypeCategory(Enum): # """ # Represents type of C/C++ type. # """ # Any = -1 # Array = 1 # BlockPointer = 2 # Builtin = 4 # Class = 8 # ComplexFloat = 16 # ComplexInteger = 32 # Enumeration = 64 # Function = 128 # Invalid = 0 # MemberPointer = 256 # ObjCInterface = 1024 # ObjCObject = 512 # ObjCObjectPointer = 2048 # Other = -2147483648 # Pointer = 4096 # CString = 4097 # Reference = 8192 # Struct = 16384 # Typedef = 32768 # Union = 65536 # Vector = 131072 # String = 42 # # def nice_name(self): # name_mappings = { # TypeCategory.Class: "class", # TypeCategory.Struct: "struct" # } # return name_mappings.get(self, str(self)) # # Path: tests/conftest.py # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) . Output only the next line.
check_variable(debugger, "strA.x", "5", int_size)
Based on the snippet: <|code_start|> toolbar_builder.connect_signals(signals) self.toolbar_builder = toolbar_builder self.toolbar = toolbar_builder.get_object("toolbar") self.debugger = debugger self.debugger.on_process_state_changed.subscribe( self._handle_process_state_change) self.debugger.on_debugger_state_changed.subscribe( self._handle_debugger_state_change) self.grp_halt_control = ["stop", "pause"] self.grp_step = ["continue", "step_over", "step_in", "step_out"] self.on_run_process = EventBroadcaster() @require_gui_thread def _get_items(self): return [self.toolbar.get_nth_item(i) for i in xrange(0, self.toolbar.get_n_items())] def _state_exited(self): self._change_grp_state(self.grp_halt_control, False) self._change_grp_state(self.grp_step, False) self._change_state("run", True) def _state_stopped(self): self._change_grp_state(self.grp_halt_control, False) self._change_grp_state(self.grp_step, True) <|code_end|> , predict the immediate next line with the help of imports: from debugger.enums import ProcessState, DebuggerState from debugger.util import EventBroadcaster from gui_util import require_gui_thread, run_on_gui and context (classes, functions, sometimes code) from other files: # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) . Output only the next line.
self._change_state("stop", True)
Predict the next line after this snippet: <|code_start|> self._state_stopped() elif state == ProcessState.Running: self._state_running() def _handle_debugger_state_change(self, state, old_value): if (state.is_set(DebuggerState.BinaryLoaded) and not state.is_set(DebuggerState.Running)): self._change_state("run", True) else: self._change_state("run", False) def _change_state(self, item_name, sensitive=True): run_on_gui(self._change_state_ui, item_name, sensitive) def _change_grp_state(self, group, sensitive=True): for item in group: self._change_state(item, sensitive) @require_gui_thread def _change_state_ui(self, item_name, sensitive=True): item = self.toolbar_builder.get_object(item_name) item.set_sensitive(sensitive) def run(self): self.on_run_process.notify() def cont(self): self.debugger.exec_continue() def stop(self): <|code_end|> using the current file's imports: from debugger.enums import ProcessState, DebuggerState from debugger.util import EventBroadcaster from gui_util import require_gui_thread, run_on_gui and any relevant context from other files: # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) . Output only the next line.
self.debugger.quit_program()
Predict the next line after this snippet: <|code_start|># # You should have received a copy of the GNU General Public License # along with Devi. If not, see <http://www.gnu.org/licenses/>. # class ToolbarManager(object): def __init__(self, toolbar_builder, debugger): signals = { "toolbar-run": lambda *x: self.run(), "toolbar-continue": lambda *x: self.cont(), "toolbar-stop": lambda *x: self.stop(), "toolbar-pause": lambda *x: self.pause(), "toolbar-step-over": lambda *x: self.step_over(), "toolbar-step-in": lambda *x: self.step_in(), "toolbar-step-out": lambda *x: self.step_out() } toolbar_builder.connect_signals(signals) self.toolbar_builder = toolbar_builder self.toolbar = toolbar_builder.get_object("toolbar") self.debugger = debugger self.debugger.on_process_state_changed.subscribe( self._handle_process_state_change) self.debugger.on_debugger_state_changed.subscribe( self._handle_debugger_state_change) <|code_end|> using the current file's imports: from debugger.enums import ProcessState, DebuggerState from debugger.util import EventBroadcaster from gui_util import require_gui_thread, run_on_gui and any relevant context from other files: # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) . Output only the next line.
self.grp_halt_control = ["stop", "pause"]
Given snippet: <|code_start|> self.parent_thread = None self.on_signal = EventBroadcaster() self.msg_queue = Queue.Queue() self.child_pid = None self.last_signal = None def run(self): assert not self.parent_thread self.parent_thread = threading.Thread(target=self._start_process) self.parent_thread.start() def exec_step_single(self): self._add_queue_command("step-single") def exec_continue(self): self._add_queue_command("continue") def exec_interrupt(self): try: os.kill(self.child_pid, signal.SIGUSR1) return True except: return False def exec_kill(self): try: os.kill(self.child_pid, signal.SIGKILL) return True except: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import ptrace import Queue import signal import threading import traceback from debugger.enums import ProcessState from debugger.util import EventBroadcaster and context: # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) which might include code, classes, or functions. Output only the next line.
return False
Given snippet: <|code_start|> def _parent(self): try: while True: pid, status = os.waitpid(self.child_pid, os.WNOHANG) if pid != 0: self._handle_child_status(status) try: command = self.msg_queue.get(True, 0.1) self._handle_command(self.child_pid, status, command) except Queue.Empty: pass except: traceback.print_exc() except OSError: self.on_signal.notify(ProcessState.Exited) except ProcessExitException: pass except: traceback.print_exc() self.child_pid = None self.parent_thread = None def _handle_child_status(self, status): if os.WIFSTOPPED(status): self._on_stop(status) elif os.WIFEXITED(status): self.on_signal.notify(ProcessState.Exited, <|code_end|> , continue by predicting the next line. Consider current file imports: import os import ptrace import Queue import signal import threading import traceback from debugger.enums import ProcessState from debugger.util import EventBroadcaster and context: # Path: debugger/enums.py # class ProcessState(Enum): # """ # Represents the debugged process' state. # """ # Attaching = 3 # Connected = 2 # Crashed = 8 # Detached = 9 # Exited = 10 # Invalid = 0 # Launching = 4 # Running = 6 # Stepping = 7 # Stopped = 5 # Suspended = 11 # Unloaded = 1 # # Path: debugger/util.py # class EventBroadcaster(object): # """ # Object that broadcasts event to it's listeners. # # Evety broadcaster represents a single event type. # """ # def __init__(self): # self.listeners = [] # # def notify(self, *args, **kwargs): # """ # Notifies all listeners that an event has occured. # @param args: arbitraty arguments that will be passed to the listeners # """ # map(lambda listener: listener(*args, **kwargs), self.listeners) # # def subscribe(self, listener): # """ # Subscribes an event listener, who will receive events from the # broadcaster. # @type listener: function # """ # self.listeners.append(listener) # # def unsubscribe(self, listener): # """ # Unsubscribes an event listener. # It will no longer receive events after he unsubscribes. # @param listener: function # """ # self.listeners.remove(listener) # # def clear(self): # """ # Removes all event listeners. # """ # self.listeners = [] # # def redirect(self, broadcaster): # """ # Redirects this broadcaster to the given broadcaster. # # All events fired by this broadcaster will be also delivered to the # given broadcaster. # @type broadcaster: EventBroadcaster # """ # self.subscribe(broadcaster.notify) # # def __call__(self, *args, **kwargs): # self.notify(*args, **kwargs) which might include code, classes, or functions. Output only the next line.
os.WTERMSIG(status),
Given the following code snippet before the placeholder: <|code_start|> file = os.path.abspath(address.file.fullpath) breakpoints.append(Breakpoint(bp.id, file, line)) return breakpoints def toggle_breakpoint(self, location, line): bp = self.find_breakpoint(location, line) if bp: return self.remove_breakpoint(location, line) else: return self.add_breakpoint(location, line) def add_breakpoint(self, location, line): self.debugger.require_state(DebuggerState.BinaryLoaded) location = os.path.abspath(location) bp = self.debugger.target.BreakpointCreateByLocation(location, line) if bp.IsValid() and bp.num_locations > 0: return True else: self.debugger.target.BreakpointDelete(bp.id) return False def find_breakpoint(self, location, line): location = os.path.abspath(location) bps = self.get_breakpoints() for bp in bps: <|code_end|> , predict the next line using imports from the current file: import os from debugger.debugee import Breakpoint from debugger.enums import DebuggerState from debugger import debugger_api and context including class names, function names, and sometimes code from other files: # Path: debugger/debugee.py # class Breakpoint(object): # """ # Represents a breakpoint. # """ # def __init__(self, number, location, line): # """ # @type number: int # @type location: str # @type line: int # """ # self.number = number # self.location = location # self.line = line # # def __repr__(self): # return "BP #{0}: {1}:{2}".format(self.number, self.location, self.line) # # Path: debugger/enums.py # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 # # Path: debugger/debugger_api.py # class ProcessExitedEventData(object): # class ProcessStoppedEventData(object): # class StartupInfo(object): # class HeapManager(object): # class IOManager(object): # class BreakpointManager(object): # class FileManager(object): # class ThreadManager(object): # class VariableManager(object): # class Debugger(object): # def __init__(self, return_code): # def __init__(self, stop_reason): # def __init__(self, cmd_arguments="", working_directory="", env_vars=None): # def copy(self): # def __repr__(self): # def __init__(self, debugger): # def watch(self): # def stop(self): # def find_block_by_address(self, addr): # def get_total_allocations(self): # def get_total_deallocations(self): # def __init__(self): # def handle_io(self): # def stop_io(self): # def __init__(self, debugger): # def add_breakpoint(self, location, line): # def toggle_breakpoint(self, location, line): # def get_breakpoints(self): # def find_breakpoint(self, location, line): # def remove_breakpoint(self, location, line): # def __init__(self, debugger): # def get_main_source_file(self): # def get_current_location(self): # def get_line_address(self, filename, line): # def disassemble(self, filename, line): # def disassemble_raw(self, filename, line): # def __init__(self, debugger): # def get_current_thread(self): # def get_thread_info(self): # def set_thread_by_index(self, thread_id): # def get_current_frame(self, with_variables=False): # def get_frames(self): # def get_frames_with_variables(self): # def change_frame(self, frame_index): # def __init__(self, debugger): # def get_type(self, expression, level=0): # def get_variable(self, expression, level=0): # def update_variable(self, variable): # def get_memory(self, address, count): # def get_registers(self): # def get_vector_items(self, vector): # def __init__(self): # def require_state(self, required_state): # def get_state(self): # def get_process_state(self): # def load_binary(self, binary_path): # def launch(self, startup_info=None): # def exec_continue(self): # def exec_pause(self): # def exec_step_over(self): # def exec_step_in(self): # def exec_step_out(self): # def quit_program(self, return_code=1): # def terminate(self): # def wait_for_stop(self): # def wait_for_exit(self): . Output only the next line.
if bp.location == location and bp.line == line:
Based on the snippet: <|code_start|># # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class LldbBreakpointManager(debugger_api.BreakpointManager): def __init__(self, debugger): super(LldbBreakpointManager, self).__init__(debugger) def get_breakpoints(self): bps = [self.debugger.target.GetBreakpointAtIndex(i) for i in xrange(self.debugger.target.GetNumBreakpoints())] breakpoints = [] for bp in bps: if bp.num_locations > 0: location = bp.GetLocationAtIndex(0) address = location.GetAddress().line_entry line = address.line file = os.path.abspath(address.file.fullpath) breakpoints.append(Breakpoint(bp.id, file, line)) <|code_end|> , predict the immediate next line with the help of imports: import os from debugger.debugee import Breakpoint from debugger.enums import DebuggerState from debugger import debugger_api and context (classes, functions, sometimes code) from other files: # Path: debugger/debugee.py # class Breakpoint(object): # """ # Represents a breakpoint. # """ # def __init__(self, number, location, line): # """ # @type number: int # @type location: str # @type line: int # """ # self.number = number # self.location = location # self.line = line # # def __repr__(self): # return "BP #{0}: {1}:{2}".format(self.number, self.location, self.line) # # Path: debugger/enums.py # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 # # Path: debugger/debugger_api.py # class ProcessExitedEventData(object): # class ProcessStoppedEventData(object): # class StartupInfo(object): # class HeapManager(object): # class IOManager(object): # class BreakpointManager(object): # class FileManager(object): # class ThreadManager(object): # class VariableManager(object): # class Debugger(object): # def __init__(self, return_code): # def __init__(self, stop_reason): # def __init__(self, cmd_arguments="", working_directory="", env_vars=None): # def copy(self): # def __repr__(self): # def __init__(self, debugger): # def watch(self): # def stop(self): # def find_block_by_address(self, addr): # def get_total_allocations(self): # def get_total_deallocations(self): # def __init__(self): # def handle_io(self): # def stop_io(self): # def __init__(self, debugger): # def add_breakpoint(self, location, line): # def toggle_breakpoint(self, location, line): # def get_breakpoints(self): # def find_breakpoint(self, location, line): # def remove_breakpoint(self, location, line): # def __init__(self, debugger): # def get_main_source_file(self): # def get_current_location(self): # def get_line_address(self, filename, line): # def disassemble(self, filename, line): # def disassemble_raw(self, filename, line): # def __init__(self, debugger): # def get_current_thread(self): # def get_thread_info(self): # def set_thread_by_index(self, thread_id): # def get_current_frame(self, with_variables=False): # def get_frames(self): # def get_frames_with_variables(self): # def change_frame(self, frame_index): # def __init__(self, debugger): # def get_type(self, expression, level=0): # def get_variable(self, expression, level=0): # def update_variable(self, variable): # def get_memory(self, address, count): # def get_registers(self): # def get_vector_items(self, vector): # def __init__(self): # def require_state(self, required_state): # def get_state(self): # def get_process_state(self): # def load_binary(self, binary_path): # def launch(self, startup_info=None): # def exec_continue(self): # def exec_pause(self): # def exec_step_over(self): # def exec_step_in(self): # def exec_step_out(self): # def quit_program(self, return_code=1): # def terminate(self): # def wait_for_stop(self): # def wait_for_exit(self): . Output only the next line.
return breakpoints
Predict the next line for this snippet: <|code_start|> class LldbBreakpointManager(debugger_api.BreakpointManager): def __init__(self, debugger): super(LldbBreakpointManager, self).__init__(debugger) def get_breakpoints(self): bps = [self.debugger.target.GetBreakpointAtIndex(i) for i in xrange(self.debugger.target.GetNumBreakpoints())] breakpoints = [] for bp in bps: if bp.num_locations > 0: location = bp.GetLocationAtIndex(0) address = location.GetAddress().line_entry line = address.line file = os.path.abspath(address.file.fullpath) breakpoints.append(Breakpoint(bp.id, file, line)) return breakpoints def toggle_breakpoint(self, location, line): bp = self.find_breakpoint(location, line) if bp: return self.remove_breakpoint(location, line) else: return self.add_breakpoint(location, line) def add_breakpoint(self, location, line): self.debugger.require_state(DebuggerState.BinaryLoaded) <|code_end|> with the help of current file imports: import os from debugger.debugee import Breakpoint from debugger.enums import DebuggerState from debugger import debugger_api and context from other files: # Path: debugger/debugee.py # class Breakpoint(object): # """ # Represents a breakpoint. # """ # def __init__(self, number, location, line): # """ # @type number: int # @type location: str # @type line: int # """ # self.number = number # self.location = location # self.line = line # # def __repr__(self): # return "BP #{0}: {1}:{2}".format(self.number, self.location, self.line) # # Path: debugger/enums.py # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 # # Path: debugger/debugger_api.py # class ProcessExitedEventData(object): # class ProcessStoppedEventData(object): # class StartupInfo(object): # class HeapManager(object): # class IOManager(object): # class BreakpointManager(object): # class FileManager(object): # class ThreadManager(object): # class VariableManager(object): # class Debugger(object): # def __init__(self, return_code): # def __init__(self, stop_reason): # def __init__(self, cmd_arguments="", working_directory="", env_vars=None): # def copy(self): # def __repr__(self): # def __init__(self, debugger): # def watch(self): # def stop(self): # def find_block_by_address(self, addr): # def get_total_allocations(self): # def get_total_deallocations(self): # def __init__(self): # def handle_io(self): # def stop_io(self): # def __init__(self, debugger): # def add_breakpoint(self, location, line): # def toggle_breakpoint(self, location, line): # def get_breakpoints(self): # def find_breakpoint(self, location, line): # def remove_breakpoint(self, location, line): # def __init__(self, debugger): # def get_main_source_file(self): # def get_current_location(self): # def get_line_address(self, filename, line): # def disassemble(self, filename, line): # def disassemble_raw(self, filename, line): # def __init__(self, debugger): # def get_current_thread(self): # def get_thread_info(self): # def set_thread_by_index(self, thread_id): # def get_current_frame(self, with_variables=False): # def get_frames(self): # def get_frames_with_variables(self): # def change_frame(self, frame_index): # def __init__(self, debugger): # def get_type(self, expression, level=0): # def get_variable(self, expression, level=0): # def update_variable(self, variable): # def get_memory(self, address, count): # def get_registers(self): # def get_vector_items(self, vector): # def __init__(self): # def require_state(self, required_state): # def get_state(self): # def get_process_state(self): # def load_binary(self, binary_path): # def launch(self, startup_info=None): # def exec_continue(self): # def exec_pause(self): # def exec_step_over(self): # def exec_step_in(self): # def exec_step_out(self): # def quit_program(self, return_code=1): # def terminate(self): # def wait_for_stop(self): # def wait_for_exit(self): , which may contain function names, class names, or code. Output only the next line.
location = os.path.abspath(location)
Given the code snippet: <|code_start|> cont=False) def test_thread_switch(debugger): def test_thread_switch_cb(): selected = select_other_thread(debugger) thread_info = debugger.thread_manager.get_thread_info() assert thread_info.selected_thread.id == selected.id debugger.quit_program() setup_debugger(debugger, TEST_FILE, TEST_LINE, test_thread_switch_cb, cont=False) def test_thread_location(debugger): def test_thread_location_cb(): assert debugger.file_manager.get_current_location()[1] in range(27, 35) select_other_thread(debugger) assert debugger.file_manager.get_current_location()[1] in range(9, 18) debugger.quit_program() setup_debugger(debugger, TEST_FILE, TEST_LINE, test_thread_location_cb, cont=False) <|code_end|> , generate the next line using the imports in this file: from tests.conftest import setup_debugger and context (functions, classes, or occasionally code) from other files: # Path: tests/conftest.py # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) . Output only the next line.
def test_thread_frame(debugger):
Next line prediction: <|code_start|> def add_breakpoint(self, file, line): file = os.path.abspath(file) assert self.debugger.program_info.has_location(file, line) for bp in self.breakpoints: # assumes different (file, line) maps to # different addresses if bp.location == file and bp.line == line: return self.breakpoints.append(Breakpoint(BreakpointManager.BREAKPOINT_ID, file, line)) BreakpointManager.BREAKPOINT_ID += 1 def set_breakpoints(self, pid): for bp in self.breakpoints: if bp.number not in self.original_instructions: addr = self.debugger.program_info.get_address(bp.location, bp.line) inst = ptrace.ptrace_get_instruction(pid, addr) self.original_instructions[bp.number] = inst inst = (inst & 0xFFFFFF00) | 0xCC assert ptrace.ptrace_set_instruction(pid, addr, inst) def has_breakpoint_for_address(self, address): return self._get_breakpoint_for_address(address) is not None def restore_instruction(self, pid, address): bp = self._get_breakpoint_for_address(address) inst = self.original_instructions[bp.number] <|code_end|> . Use current file imports: (import os import ptrace from debugger.debugee import Breakpoint) and context including class names, function names, or small code snippets from other files: # Path: debugger/debugee.py # class Breakpoint(object): # """ # Represents a breakpoint. # """ # def __init__(self, number, location, line): # """ # @type number: int # @type location: str # @type line: int # """ # self.number = number # self.location = location # self.line = line # # def __repr__(self): # return "BP #{0}: {1}:{2}".format(self.number, self.location, self.line) . Output only the next line.
assert ptrace.ptrace_set_instruction(pid, address, inst)
Here is a snippet: <|code_start|> gdb.INLINE_FRAME] def handle_malloc(self, stop_event): frame = gdb.newest_frame() frame_name = frame.name() if not self.is_valid_memory_frame(frame): return args = self.gdb_helper.get_args() if len(args) == 1: byte_count = args[0].value finish = gdb.FinishBreakpoint(internal=False) if not finish.is_valid(): return self.finish() if not finish.is_valid(): return address = str(finish.return_value) self.memory.malloc(address, byte_count, frame_name) if finish.is_valid(): finish.delete() def handle_free(self, stop_event): <|code_end|> . Write the next line using the current file imports: import gdb import sys from gdb_helper import GdbHelper from gdb_thread_manager import GdbThreadManager from gdb_frame_manager import GdbFrameManager from gdb_file_manager import GdbFileManager from gdb_breakpoint_manager import GdbBreakpointManager from memory import Memory from debugger.enums import DebuggerState and context from other files: # Path: debugger/enums.py # class DebuggerState(Enum): # """ # Represents debugger state. # """ # Started = 1 # BinaryLoaded = 2 # Running = 3 , which may include functions, classes, or code. Output only the next line.
frame = gdb.newest_frame()
Given the code snippet: <|code_start|>def test_step_over(debugger): state = AsyncState() def test_step_over_cb(): if state.state == 0: state.inc() debugger.exec_step_over() else: assert debugger.file_manager.get_current_location() ==\ make_location(12) debugger.quit_program() setup_debugger(debugger, TEST_FILE, 11, test_step_over_cb, cont=False) def test_step_in(debugger): state = AsyncState() def test_step_in_cb(): if state.state == 0: state.inc() debugger.exec_step_in() else: assert debugger.file_manager.get_current_location() ==\ make_location(5) debugger.quit_program() setup_debugger(debugger, TEST_FILE, 11, test_step_in_cb, cont=False) <|code_end|> , generate the next line using the imports in this file: import os import time from tests.conftest import AsyncState, setup_debugger and context (functions, classes, or occasionally code) from other files: # Path: tests/conftest.py # class AsyncState(object): # def __init__(self): # self.state = 0 # # def inc(self): # self.state += 1 # # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) . Output only the next line.
def test_step_out(debugger):
Here is a snippet: <|code_start|> setup_debugger(debugger, TEST_FILE, 11, test_step_in_cb, cont=False) def test_step_out(debugger): state = AsyncState() def test_step_out_cb(): if state.state == 0: state.inc() debugger.exec_step_out() else: location = debugger.file_manager.get_current_location() assert location[0] == make_location(11)[0] assert location[1] in (11, 12) debugger.quit_program() setup_debugger(debugger, TEST_FILE, 5, test_step_out_cb, cont=False) def test_continue(debugger): state = AsyncState() def test_continue_cb(): if state.state == 0: state.inc() debugger.exec_continue() else: assert debugger.file_manager.get_current_location() ==\ make_location(13) <|code_end|> . Write the next line using the current file imports: import os import time from tests.conftest import AsyncState, setup_debugger and context from other files: # Path: tests/conftest.py # class AsyncState(object): # def __init__(self): # self.state = 0 # # def inc(self): # self.state += 1 # # def setup_debugger(debugger, binary, lines, on_state_change=None, # startup_info=None, cont=True, wait=True): # assert debugger.load_binary("src/{}".format(binary)) # # test_exception = [] # # if not isinstance(lines, Iterable): # lines = [lines] # # for line in lines: # assert debugger.breakpoint_manager.add_breakpoint( # "src/{}.cpp".format(binary), line) # # if on_state_change: # def on_stop(state, data): # if state == ProcessState.Stopped: # try: # on_state_change() # if cont: # debugger.exec_continue() # except Exception as exc: # test_exception.append(traceback.format_exc(exc)) # debugger.quit_program() # # debugger.on_process_state_changed.subscribe(on_stop) # # assert debugger.launch(startup_info) # # if wait: # debugger.wait_for_exit() # # if len(test_exception) > 0: # pytest.fail(test_exception[0], pytrace=False) , which may include functions, classes, or code. Output only the next line.
debugger.quit_program()
Given the following code snippet before the placeholder: <|code_start|># # Copyright (C) 2015-2016 Jakub Beranek # # This file is part of Devi. # # Devi is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License, or # (at your option) any later version. # # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class Parser(object): def __init__(self): pass def parse_breakpoint(self, data): return self._instantiate_breakpoint(self.parse(data)["bkpt"]) <|code_end|> , predict the next line using imports from the current file: import json import re from debugger.debugee import Breakpoint, InferiorThread, ThreadInfo, Frame from debugger.enums import ThreadState and context including class names, function names, and sometimes code from other files: # Path: debugger/debugee.py # class Breakpoint(object): # """ # Represents a breakpoint. # """ # def __init__(self, number, location, line): # """ # @type number: int # @type location: str # @type line: int # """ # self.number = number # self.location = location # self.line = line # # def __repr__(self): # return "BP #{0}: {1}:{2}".format(self.number, self.location, self.line) # # class InferiorThread(object): # """ # Represents a thread of the debugged process. # """ # def __init__(self, id, name, state, frame=None): # """ # @type id: int # @type name: str # @type state: enums.ProcessState # @type frame: Frame # """ # self.id = id # self.name = name # self.state = state # self.frame = frame # # def __repr__(self): # return "Thread #{0} ({1}): {2}".format(self.id, self.name, self.state) # # class ThreadInfo(object): # """ # Represents thread state (list of threads and the selected thread) of the # debugged process. # """ # def __init__(self, selected_thread, threads): # """ # @type selected_thread: InferiorThread # @type threads: list of InferiorThread # """ # self.selected_thread = selected_thread # self.threads = threads # # def __repr__(self): # return "Thread info: active: {0}, threads: {1}".format( # str(self.selected_thread), str(self.threads)) # # class Frame(object): # """ # Represents a stack frame of the debugged process. # """ # def __init__(self, level, func, file, line): # """ # @type level: int # @type func: str # @type file: str # @type line: int # """ # self.level = level # self.func = func # self.file = file # self.line = line # self.variables = [] # """@type variables: debugger.debugee.Variable""" # # def __repr__(self): # return "Frame #{0} ({1} at {2}:{3}".format(self.level, self.func, # self.file, self.line) # # Path: debugger/enums.py # class ThreadState(Enum): # """ # Represents thread state. # """ # Running = 1 # Stopped = 2 # Exited = 3 . Output only the next line.
def parse_breakpoints(self, data):
Given snippet: <|code_start|># Copyright (C) 2015-2016 Jakub Beranek # # This file is part of Devi. # # Devi is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License, or # (at your option) any later version. # # Devi 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 Devi. If not, see <http://www.gnu.org/licenses/>. # class Parser(object): def __init__(self): pass def parse_breakpoint(self, data): return self._instantiate_breakpoint(self.parse(data)["bkpt"]) def parse_breakpoints(self, data): <|code_end|> , continue by predicting the next line. Consider current file imports: import json import re from debugger.debugee import Breakpoint, InferiorThread, ThreadInfo, Frame from debugger.enums import ThreadState and context: # Path: debugger/debugee.py # class Breakpoint(object): # """ # Represents a breakpoint. # """ # def __init__(self, number, location, line): # """ # @type number: int # @type location: str # @type line: int # """ # self.number = number # self.location = location # self.line = line # # def __repr__(self): # return "BP #{0}: {1}:{2}".format(self.number, self.location, self.line) # # class InferiorThread(object): # """ # Represents a thread of the debugged process. # """ # def __init__(self, id, name, state, frame=None): # """ # @type id: int # @type name: str # @type state: enums.ProcessState # @type frame: Frame # """ # self.id = id # self.name = name # self.state = state # self.frame = frame # # def __repr__(self): # return "Thread #{0} ({1}): {2}".format(self.id, self.name, self.state) # # class ThreadInfo(object): # """ # Represents thread state (list of threads and the selected thread) of the # debugged process. # """ # def __init__(self, selected_thread, threads): # """ # @type selected_thread: InferiorThread # @type threads: list of InferiorThread # """ # self.selected_thread = selected_thread # self.threads = threads # # def __repr__(self): # return "Thread info: active: {0}, threads: {1}".format( # str(self.selected_thread), str(self.threads)) # # class Frame(object): # """ # Represents a stack frame of the debugged process. # """ # def __init__(self, level, func, file, line): # """ # @type level: int # @type func: str # @type file: str # @type line: int # """ # self.level = level # self.func = func # self.file = file # self.line = line # self.variables = [] # """@type variables: debugger.debugee.Variable""" # # def __repr__(self): # return "Frame #{0} ({1} at {2}:{3}".format(self.level, self.func, # self.file, self.line) # # Path: debugger/enums.py # class ThreadState(Enum): # """ # Represents thread state. # """ # Running = 1 # Stopped = 2 # Exited = 3 which might include code, classes, or functions. Output only the next line.
return [self._instantiate_breakpoint(bp)