Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> raise RuntimeError("You must set a config file area if no depthfile is present and you are running a sub-region") self._set_vars_from_dict(gal_stats, check_none=True) if self.limmag_catalog is None: self.limmag_catalog = self.limmag_ref # Get wcen numbers if available self.set_wcen_vals() # Set some defaults if self.specfile_train is None: self.specfile_train = self.specfile # Record the cluster dtype for convenience self.cluster_dtype = copy.copy(cluster_dtype_base) self.cluster_dtype.extend([('MAG', 'f4', self.nmag), ('MAG_ERR', 'f4', self.nmag), ('PZBINS', 'f4', self.npzbins), ('PZ', 'f4', self.npzbins), ('RA_CENT', 'f8', self.percolation_maxcen), ('DEC_CENT', 'f8', self.percolation_maxcen), ('ID_CENT', 'i8', self.percolation_maxcen), ('LAMBDA_CENT', 'f4', self.percolation_maxcen), ('ZLAMBDA_CENT', 'f4', self.percolation_maxcen), ('P_CEN', 'f4', self.percolation_maxcen), ('Q_CEN', 'f4', self.percolation_maxcen), ('P_FG', 'f4', self.percolation_maxcen), ('Q_MISS', 'f4'), ('P_SAT', 'f4', self.percolation_maxcen), ('P_C', 'f4', self.percolation_maxcen)]) <|code_end|> , predict the next line using imports from the current file: import yaml import fitsio import copy import numpy as np import re import os import logging from esutil.cosmology import Cosmo from .cluster import cluster_dtype_base, member_dtype_base from ._version import __version__ and context including class names, function names, and sometimes code from other files: # Path: redmapper/cluster.py # class Cluster(Entry): # class ClusterCatalog(Catalog): # def __init__(self, cat_vals=None, r0=None, beta=None, config=None, zredstr=None, bkg=None, cbkg=None, neighbors=None, zredbkg=None, dtype=None): # def reset(self): # def set_neighbors(self, neighbors): # def find_neighbors(self, radius, galcat, megaparsec=False, maxmag=None): # def update_neighbors_dist(self): # def clear_neighbors(self): # def _calc_radial_profile(self, idx=None, rscale=0.15): # def _calc_luminosity(self, normmag, idx=None): # def calc_bkg_density(self, r, chisq, refmag): # def calc_cbkg_density(self, r, col_index, col, refmag): # def calc_zred_bkg_density(self, r, zred, refmag): # def compute_bkg_local(self, mask, depth): # def calc_richness(self, mask, calc_err=True, index=None): # def calc_lambdacerr(self, maskgals, mstar, lam, rlam, pmem, cval, gamma): # def calc_richness_fit(self, mask, col_index, centcolor_in=None, rcut=0.5, mingal=5, sigint=0.05, calc_err=False): # def redshift(self): # def redshift(self, value): # def mstar(self): # def _update_mstar(self): # def mpc_scale(self): # def _update_mpc_scale(self): # def _compute_neighbor_r(self): # def copy(self): # def __copy__(self): # def __init__(self, array, **kwargs): # def from_catfile(cls, filename, **kwargs): # def zeros(cls, size, **kwargs): # def __getitem__(self, key): # # Path: redmapper/_version.py . Output only the next line.
self.member_dtype = copy.copy(member_dtype_base)
Given the code snippet: <|code_start|> class DuplicatableConfig(object): """ Class to hold instances of variables that need to be duplicated for parallelism. """ def __init__(self, config): """ Instantiate a DuplicatableConfig. Parameters ---------- config: `redmapper.Configuration` Configuration struct to copy values from """ self.outbase = config.outbase self.hpix = config.hpix self.nside = config.nside class Configuration(object): """ Configuration class for redmapper. This class holds all the relevant configuration information, and had convenient methods for validating parameters as well as generating filenames, etc. """ <|code_end|> , generate the next line using the imports in this file: import yaml import fitsio import copy import numpy as np import re import os import logging from esutil.cosmology import Cosmo from .cluster import cluster_dtype_base, member_dtype_base from ._version import __version__ and context (functions, classes, or occasionally code) from other files: # Path: redmapper/cluster.py # class Cluster(Entry): # class ClusterCatalog(Catalog): # def __init__(self, cat_vals=None, r0=None, beta=None, config=None, zredstr=None, bkg=None, cbkg=None, neighbors=None, zredbkg=None, dtype=None): # def reset(self): # def set_neighbors(self, neighbors): # def find_neighbors(self, radius, galcat, megaparsec=False, maxmag=None): # def update_neighbors_dist(self): # def clear_neighbors(self): # def _calc_radial_profile(self, idx=None, rscale=0.15): # def _calc_luminosity(self, normmag, idx=None): # def calc_bkg_density(self, r, chisq, refmag): # def calc_cbkg_density(self, r, col_index, col, refmag): # def calc_zred_bkg_density(self, r, zred, refmag): # def compute_bkg_local(self, mask, depth): # def calc_richness(self, mask, calc_err=True, index=None): # def calc_lambdacerr(self, maskgals, mstar, lam, rlam, pmem, cval, gamma): # def calc_richness_fit(self, mask, col_index, centcolor_in=None, rcut=0.5, mingal=5, sigint=0.05, calc_err=False): # def redshift(self): # def redshift(self, value): # def mstar(self): # def _update_mstar(self): # def mpc_scale(self): # def _update_mpc_scale(self): # def _compute_neighbor_r(self): # def copy(self): # def __copy__(self): # def __init__(self, array, **kwargs): # def from_catfile(cls, filename, **kwargs): # def zeros(cls, size, **kwargs): # def __getitem__(self, key): # # Path: redmapper/_version.py . Output only the next line.
version = ConfigField(default=__version__, required=True)
Given the code snippet: <|code_start|> res = scipy.optimize.minimize(self, p0, method='L-BFGS-B', bounds=bounds, jac=False, options={'maxfun': 2000, 'maxiter': 2000, 'maxcor': 20, 'eps': 1e-5, 'gtol': 1e-8}, callback=None) pars = res.x return pars def __call__(self, pars): """ Compute the median cost function for f(pars) Parameters ---------- pars: `np.array` Fit parameters, with same number of elements as nodes Returns ------- t: `float` Median cost """ <|code_end|> , generate the next line using the imports in this file: import numpy as np import scipy.optimize import esutil import warnings from scipy import special from .utilities import CubicSpline, interpol and context (functions, classes, or occasionally code) from other files: # Path: redmapper/utilities.py # class CubicSpline(object): # """ # CubicSpline interpolation class. # """ # def __init__(self, x, y, yp=None, fixextrap=False): # """ # Instantiate a CubicSpline object. # # Parameters # ---------- # x: `np.array` # Float array of node positions # y: `np.array` # Float array of node values # yp: `str` # Type of spline. Default is None, which is "natural" # fixextrap: `bool`, optional # Fix the extrapolation at the end of the node positions. # Default is False. # """ # npts = len(x) # mat = np.zeros((3, npts)) # # enforce continuity of 1st derivatives # mat[1,1:-1] = (x[2: ]-x[0:-2])/3. # mat[2,0:-2] = (x[1:-1]-x[0:-2])/6. # mat[0,2: ] = (x[2: ]-x[1:-1])/6. # bb = np.zeros(npts) # bb[1:-1] = ((y[2: ]-y[1:-1])/(x[2: ]-x[1:-1]) - # (y[1:-1]-y[0:-2])/(x[1:-1]-x[0:-2])) # if yp is None: # natural cubic spline # mat[1,0] = 1. # mat[1,-1] = 1. # bb[0] = 0. # bb[-1] = 0. # elif yp == '3d=0': # mat[1, 0] = -1./(x[1]-x[0]) # mat[0, 1] = 1./(x[1]-x[0]) # mat[1,-1] = 1./(x[-2]-x[-1]) # mat[2,-2] = -1./(x[-2]-x[-1]) # bb[ 0] = 0. # bb[-1] = 0. # else: # mat[1, 0] = -1./3.*(x[1]-x[0]) # mat[0, 1] = -1./6.*(x[1]-x[0]) # mat[2,-2] = 1./6.*(x[-1]-x[-2]) # mat[1,-1] = 1./3.*(x[-1]-x[-2]) # bb[ 0] = yp[0]-1.*(y[ 1]-y[ 0])/(x[ 1]-x[ 0]) # bb[-1] = yp[1]-1.*(y[-1]-y[-2])/(x[-1]-x[-2]) # y2 = solve_banded((1,1), mat, bb) # self.x, self.y, self.y2 = (x, y, y2) # # self.fixextrap = fixextrap # # def splint(self,x): # """ # Compute spline interpolation. # # Parameters # ---------- # x: `np.array` # Float array of x values to compute interpolation # # Returns # ------- # y: `np.array` # Spline interpolated values at x # """ # npts = len(self.x) # lo = np.searchsorted(self.x, x)-1 # lo = np.clip(lo, 0, npts-2) # hi = lo + 1 # dx = self.x[hi] - self.x[lo] # a = (self.x[hi] - x)/dx # b = (x-self.x[lo])/dx # y = (a*self.y[lo]+b*self.y[hi]+ # ((a**3-a)*self.y2[lo]+(b**3-b)*self.y2[hi])*dx**2./6.) # return y # # def __call__(self, x): # """ # Compute spline interpolation. # # Parameters # ---------- # x: `np.array` # Float array of x values to compute interpolation # # Returns # ------- # y: `np.array` # Spline interpolated values at x # """ # # if not self.fixextrap: # return self.splint(x) # else: # vals = self.splint(x) # # lo, = np.where(x < self.x[0]) # vals[lo] = self.y[0] # # hi, = np.where(x > self.x[-1]) # vals[hi] = self.y[-1] # # return vals # # def interpol(v, x, xout): # """ # Port of IDL interpol.py. Does fast and simple linear interpolation. # # Parameters # ---------- # v: `np.array` # Float array of y (dependent) values to interpolate between # x: `np.array` # Float array of x (independent) values to interpolate between # xout: `np.array` # Float array of x values to compute interpolated values # # Returns # ------- # yout: `np.array` # Float array of y output values associated with xout # """ # # m = v.size # nOut = m # # s = np.clip(np.searchsorted(x, xout) - 1, 0, m - 2) # # diff = v[s + 1] - v[s] # # return (xout - x[s]) * diff / (x[s + 1] - x[s]) + v[s] . Output only the next line.
spl = CubicSpline(self._z_nodes, pars)
Using the snippet: <|code_start|> if pval is None: result = numpy.pv(rate=nrate/100/pyr, nper=nper, fv=fval, pmt=pmt, when=due) elif fval is None: result = numpy.fv(rate=nrate/100/pyr, nper=nper, pv=pval, pmt=pmt, when=due) elif nper is None: result = numpy.nper(rate=nrate/100/pyr, pv=pval, fv=fval, pmt=pmt, when=due) elif pmt is None: result = numpy.pmt(rate=nrate/100/pyr, nper=nper, pv=pval, fv=fval, when=due) else: result = numpy.rate(pv=pval, nper=nper, fv=fval, pmt=pmt, when=due) * 100 * pyr if noprint is True: if isinstance(result, numpy.ndarray): return result.tolist() return result nrate = nrate.tolist() if pval is None: pval = result elif fval is None: fval = result elif nper is None: nper = result elif pmt is None: pmt = result else: nrate = result <|code_end|> , determine the next line of code. You have imports: import numpy import doctest from cashflows.common import _vars2list and context (class names, function names, or code) available: # Path: cashflows/common.py # def _vars2list(params): # """ Converts the variables on lists of the same length # """ # length = 1 # for param in params: # if isinstance(param, list): # length = max(length, len(param)) # if length > 1: # for param in params: # if isinstance(param, list) and len(param) != length: # raise Exception('Lists in parameters must the same length') # result = [] # for param in params: # if isinstance(param, list): # result.append(param) # else: # result.append([param] * length) # return result . Output only the next line.
params = _vars2list([pval, fval, nper, pmt, nrate])
Continue the code snippet: <|code_start|> admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^$', 'ssheepdog.views.view_access_summary'), url(r'^new_key/$', 'ssheepdog.views.generate_new_application_key'), url(r'^sync_keys/$', 'ssheepdog.views.sync_keys'), url(r'^manual_sync/(?P<id>[0-9]+)/$', 'ssheepdog.views.manual_sync'), url(r'^(?P<action>permit|deny)/(?P<user_pk>[0-9]+)/(?P<login_pk>[0-9]+)/$', 'ssheepdog.views.change_access'), url(r'^user/(?P<id>[0-9]+)/$', 'ssheepdog.views.user_admin_view'), url(r'^login/(?P<id>[0-9]+)/$','ssheepdog.views.login_admin_view'), url(r'^openid/', include('django_openid_auth.urls')), url(r'^accounts/login/$', login, {}, name='login'), url(r'^accounts/logout/$', logout, {}, name='logout'), <|code_end|> . Use current file imports: from django.conf.urls import patterns, url, include from django.contrib.auth.views import login, logout from django.contrib import admin from aws_policy_manager import urls as awsurls and context (classes, functions, or code) from other files: # Path: aws_policy_manager/urls.py . Output only the next line.
url(r'^awspolicies/', include(awsurls.aws_patterns, namespace='aws_urls')),
Given snippet: <|code_start|> add_introspection_rules([], ["^ssheepdog\.fields\.PublicKeyField"]) KEYS_DIR = os.path.join(os.path.dirname(__file__), '..', 'deploy', 'keys') ALL_FABRIC_WARNINGS = ['everything', 'status', 'aborts'] FABRIC_WARNINGS = [] <|code_end|> , continue by predicting the next line. Consider current file imports: import os, base64 import fabric.exceptions from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save, m2m_changed from django.db.utils import DatabaseError from fabric.api import env, run, hide, settings from fabric.network import disconnect_all from django.conf import settings as app_settings from ssheepdog.utils import DirtyFieldsMixin, capture_output from django.core.urlresolvers import reverse from south.signals import post_migrate from south.modelsinspector import add_introspection_rules from Crypto.PublicKey import RSA from Crypto import Random from ssheepdog.fields import PublicKeyField from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ValidationError and context: # Path: ssheepdog/utils.py # class DirtyFieldsMixin(object): # """ # Supplies method get_dirty_fields() which is a dict of those fields which # have changed since object creation, mapping field names to original values. # # A foreign key field is dirty if its pk changes; changes to the other object # are not detected. The dirty field is listed as fieldname_pk, and the # original value is either the pk itself or None. # # Many-to-many fields are ignored. # """ # def __init__(self, *args, **kwargs): # super(DirtyFieldsMixin, self).__init__(*args, **kwargs) # self._original_state = self._as_dict() # # def _as_dict(self): # def name(f): # return "%s_pk" % f.name if f.rel else f.name # # def value(f): # if f.rel: # Usually the primary key is the "_id"... # try: # return getattr(self, f.name + "_id") # except AttributeError: # pass # # try: # val = getattr(self, f.name) # except ObjectDoesNotExist: # foreign key relation not yet set # val = None # if f.rel and val: # return val.pk # else: # return val # return dict([(name(f), value(f)) for f in self._meta.local_fields]) # # def get_dirty_fields(self): # new_state = self._as_dict() # return dict([(key, value) # for key, value in self._original_state.iteritems() # if value != new_state[key]]) # # class capture_output(object): # """ # Usage: # with capture_output() as captured: # do_stuff() # Now captured.stderr and captured.stdout contain the output generated during # do_stuff(). capture_output(stderr=False) turns the latter off. # """ # # backup = None # result = None # # def __init__(self, stderr=True, stdout=True): # self.capture_stdout = stdout # self.capture_stderr = stderr # # def __enter__(self): # class Result(object): # stdout = "" # stderr = "" # self.result = Result() # if self.capture_stderr: # self.stderr = sys.stderr # sys.stderr = StringIO() # if self.capture_stdout: # self.stdout = sys.stdout # sys.stdout = StringIO() # return self.result # # def __exit__(self, type, value, traceback): # if self.capture_stderr: # self.result.stderr = sys.stderr.getvalue() # sys.stderr.close() # sys.stderr = self.stderr # if self.capture_stdout: # self.result.stdout = sys.stdout.getvalue() # sys.stdout.close() # sys.stdout = self.stdout # # Path: ssheepdog/fields.py # class PublicKeyField(TextField): # def validate(self, value, model_instance): # """ # Confirm that each row is a valid ssh key # """ # def _validate_key(value): # """ # Just confirm that the first field is something like ssh-rsa or ssh-dss, # and the second field is reasonably long and can be base64 decoded. # """ # if value.strip() == "": # return True # try: # type_, key_string = value.split()[:2] # assert (type_[:4] == 'ssh-') # assert (len(key_string) > 100) # base64.decodestring(key_string) # return True # except: # False # # super(PublicKeyField, self).validate(value, model_instance) # keys = value.rstrip().split("\n") # l = len(keys) # i = 0 # for s in value.split("\n"): # i += 1 # if not _validate_key(s): # if l == 1: # message = _("This does not appear to be an ssh public key") # else: # message = _("Row %d does not appear" # " to be an ssh public key") % i # raise exceptions.ValidationError(message) # # def clean(self, value, model_instance): # """ # Clean up any whitespace. # """ # lines = value.strip().split("\n") # lines = [" ".join(line.strip().split()) for line in lines] # value = "\n".join([line for line in lines if line]) # return super(PublicKeyField, self).clean(value, model_instance) which might include code, classes, or functions. Output only the next line.
class UserProfile(DirtyFieldsMixin, models.Model):
Using the snippet: <|code_start|> add_introspection_rules([], ["^ssheepdog\.fields\.PublicKeyField"]) KEYS_DIR = os.path.join(os.path.dirname(__file__), '..', 'deploy', 'keys') ALL_FABRIC_WARNINGS = ['everything', 'status', 'aborts'] FABRIC_WARNINGS = [] class UserProfile(DirtyFieldsMixin, models.Model): nickname = models.CharField(max_length=256) user = models.OneToOneField(User, primary_key=True, related_name='_profile_cache') <|code_end|> , determine the next line of code. You have imports: import os, base64 import fabric.exceptions from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save, m2m_changed from django.db.utils import DatabaseError from fabric.api import env, run, hide, settings from fabric.network import disconnect_all from django.conf import settings as app_settings from ssheepdog.utils import DirtyFieldsMixin, capture_output from django.core.urlresolvers import reverse from south.signals import post_migrate from south.modelsinspector import add_introspection_rules from Crypto.PublicKey import RSA from Crypto import Random from ssheepdog.fields import PublicKeyField from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ValidationError and context (class names, function names, or code) available: # Path: ssheepdog/utils.py # class DirtyFieldsMixin(object): # """ # Supplies method get_dirty_fields() which is a dict of those fields which # have changed since object creation, mapping field names to original values. # # A foreign key field is dirty if its pk changes; changes to the other object # are not detected. The dirty field is listed as fieldname_pk, and the # original value is either the pk itself or None. # # Many-to-many fields are ignored. # """ # def __init__(self, *args, **kwargs): # super(DirtyFieldsMixin, self).__init__(*args, **kwargs) # self._original_state = self._as_dict() # # def _as_dict(self): # def name(f): # return "%s_pk" % f.name if f.rel else f.name # # def value(f): # if f.rel: # Usually the primary key is the "_id"... # try: # return getattr(self, f.name + "_id") # except AttributeError: # pass # # try: # val = getattr(self, f.name) # except ObjectDoesNotExist: # foreign key relation not yet set # val = None # if f.rel and val: # return val.pk # else: # return val # return dict([(name(f), value(f)) for f in self._meta.local_fields]) # # def get_dirty_fields(self): # new_state = self._as_dict() # return dict([(key, value) # for key, value in self._original_state.iteritems() # if value != new_state[key]]) # # class capture_output(object): # """ # Usage: # with capture_output() as captured: # do_stuff() # Now captured.stderr and captured.stdout contain the output generated during # do_stuff(). capture_output(stderr=False) turns the latter off. # """ # # backup = None # result = None # # def __init__(self, stderr=True, stdout=True): # self.capture_stdout = stdout # self.capture_stderr = stderr # # def __enter__(self): # class Result(object): # stdout = "" # stderr = "" # self.result = Result() # if self.capture_stderr: # self.stderr = sys.stderr # sys.stderr = StringIO() # if self.capture_stdout: # self.stdout = sys.stdout # sys.stdout = StringIO() # return self.result # # def __exit__(self, type, value, traceback): # if self.capture_stderr: # self.result.stderr = sys.stderr.getvalue() # sys.stderr.close() # sys.stderr = self.stderr # if self.capture_stdout: # self.result.stdout = sys.stdout.getvalue() # sys.stdout.close() # sys.stdout = self.stdout # # Path: ssheepdog/fields.py # class PublicKeyField(TextField): # def validate(self, value, model_instance): # """ # Confirm that each row is a valid ssh key # """ # def _validate_key(value): # """ # Just confirm that the first field is something like ssh-rsa or ssh-dss, # and the second field is reasonably long and can be base64 decoded. # """ # if value.strip() == "": # return True # try: # type_, key_string = value.split()[:2] # assert (type_[:4] == 'ssh-') # assert (len(key_string) > 100) # base64.decodestring(key_string) # return True # except: # False # # super(PublicKeyField, self).validate(value, model_instance) # keys = value.rstrip().split("\n") # l = len(keys) # i = 0 # for s in value.split("\n"): # i += 1 # if not _validate_key(s): # if l == 1: # message = _("This does not appear to be an ssh public key") # else: # message = _("Row %d does not appear" # " to be an ssh public key") % i # raise exceptions.ValidationError(message) # # def clean(self, value, model_instance): # """ # Clean up any whitespace. # """ # lines = value.strip().split("\n") # lines = [" ".join(line.strip().split()) for line in lines] # value = "\n".join([line for line in lines if line]) # return super(PublicKeyField, self).clean(value, model_instance) . Output only the next line.
ssh_key = PublicKeyField(blank=True)
Given snippet: <|code_start|> admin.site.register(models.Client) def unregister(Model): try: admin.site.unregister(Model) except: pass def reregister(Model, AdminModel): unregister(Model) admin.site.register(Model, AdminModel) class LoginAdmin(admin.ModelAdmin): model = models.Login <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from django.contrib.auth.admin import UserAdmin, User from ssheepdog import models, forms from django.utils.translation import ugettext_lazy as _ and context: # Path: ssheepdog/models.py # KEYS_DIR = os.path.join(os.path.dirname(__file__), # '..', 'deploy', 'keys') # ALL_FABRIC_WARNINGS = ['everything', 'status', 'aborts'] # FABRIC_WARNINGS = [] # class UserProfile(DirtyFieldsMixin, models.Model): # class Machine(DirtyFieldsMixin, models.Model): # class LoginLog(models.Model): # class Meta: # class Login(DirtyFieldsMixin, models.Model): # class Meta: # class Client(models.Model): # class NamedApplicationKey(models.Model): # class ApplicationKey(models.Model): # def formatted_public_key(self): # def __str__(self): # def __unicode__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def get_change_url(self): # def clean(self, *args, **kwargs): # def save(self, *args, **kwargs): # def get_address(self): # def get_last_log(self): # def get_change_url(self): # def sync_all(actor=None): # def __unicode__(self): # def get_application_key(self): # def formatted_public_key(self): # def save(self, *args, **kwargs): # def run(self, command, private_key=None): # def get_client(self): # def get_authorized_keys(self): # def formatted_keys(self): # def flag_as_manually_synced_by(self, actor): # def sync(self, actor=None): # def get_change_url(self): # def __unicode__(self): # def __unicode__(self): # def save(self, *args, **kwargs): # def save(self, *args, **kwargs): # def formatted_public_key(self): # def __unicode__(self): # def generate_key_pair(self): # def get_latest(create_new=False): # def create_user_profile(sender, instance, created, **kwargs): # def user_login_changed(sender, instance=None, reverse=None, model=None, # action=None, **kwargs): # def force_one_app_key(app, **kwargs): # # Path: ssheepdog/forms.py # class AccessFilterForm(forms.Form): # class LoginForm(forms.ModelForm): # class Meta: # class UserProfileForm(forms.ModelForm): # class Meta: # def save(self, *args, **kwargs): which might include code, classes, or functions. Output only the next line.
form = forms.LoginForm
Using the snippet: <|code_start|># encoding: utf-8 NEW_PERMISSIONS = ( # Managed by South so added by data migration! ("can_view_all_users", "Can view other users"), ("can_view_all_logins", "Can view other's logins"), ) class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Login.additional_public_keys' db.add_column('ssheepdog_login', 'additional_public_keys', self.gf('ssheepdog.fields.PublicKeyField')(default='', blank=True), keep_default=False) # Changing field 'UserProfile.ssh_key' db.alter_column('ssheepdog_userprofile', 'ssh_key', self.gf('ssheepdog.fields.PublicKeyField')(blank=True)) # Delete permission which was unintionally injected by previous migration orm['auth.Permission'].objects.filter(name='Verbose Name').delete() ct, created = orm['contenttypes.ContentType'].objects.get_or_create( model='login', app_label='ssheepdog') for codename, name in NEW_PERMISSIONS: <|code_end|> , determine the next line of code. You have imports: import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from ssheepdog.utils import add_permission and context (class names, function names, or code) available: # Path: ssheepdog/utils.py # def add_permission(orm, codename, name, app_label='ssheepdog', model='login'): # ct, created = orm['contenttypes.ContentType'].objects.get_or_create( # model=model, app_label=app_label) # orm['auth.permission'].objects.get_or_create( # content_type=ct, codename=codename, defaults=dict(name=name)) . Output only the next line.
add_permission(orm, codename, name)
Given the following code snippet before the placeholder: <|code_start|> class AccessFilterForm(forms.Form): user = forms.CharField(label="User", required=False) login = forms.CharField(label="Login/Machine", required=False) class LoginForm(forms.ModelForm): named_application_key = forms.ModelChoiceField( required=False, label="Force reset to named key", <|code_end|> , predict the next line using imports from the current file: from django import forms from ssheepdog import models and context including class names, function names, and sometimes code from other files: # Path: ssheepdog/models.py # KEYS_DIR = os.path.join(os.path.dirname(__file__), # '..', 'deploy', 'keys') # ALL_FABRIC_WARNINGS = ['everything', 'status', 'aborts'] # FABRIC_WARNINGS = [] # class UserProfile(DirtyFieldsMixin, models.Model): # class Machine(DirtyFieldsMixin, models.Model): # class LoginLog(models.Model): # class Meta: # class Login(DirtyFieldsMixin, models.Model): # class Meta: # class Client(models.Model): # class NamedApplicationKey(models.Model): # class ApplicationKey(models.Model): # def formatted_public_key(self): # def __str__(self): # def __unicode__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def get_change_url(self): # def clean(self, *args, **kwargs): # def save(self, *args, **kwargs): # def get_address(self): # def get_last_log(self): # def get_change_url(self): # def sync_all(actor=None): # def __unicode__(self): # def get_application_key(self): # def formatted_public_key(self): # def save(self, *args, **kwargs): # def run(self, command, private_key=None): # def get_client(self): # def get_authorized_keys(self): # def formatted_keys(self): # def flag_as_manually_synced_by(self, actor): # def sync(self, actor=None): # def get_change_url(self): # def __unicode__(self): # def __unicode__(self): # def save(self, *args, **kwargs): # def save(self, *args, **kwargs): # def formatted_public_key(self): # def __unicode__(self): # def generate_key_pair(self): # def get_latest(create_new=False): # def create_user_profile(sender, instance, created, **kwargs): # def user_login_changed(sender, instance=None, reverse=None, model=None, # action=None, **kwargs): # def force_one_app_key(app, **kwargs): . Output only the next line.
queryset=models.NamedApplicationKey.objects.all(),
Predict the next line after this snippet: <|code_start|># encoding: utf-8 PERMISSIONS = ( # Managed by South so added by data migration! ("can_view_access_summary", "Can view access summary"), ("can_sync", "Can sync login keys"), ("can_edit_own_public_key", "Can edit one's own public key"), ) class Migration(DataMigration): def forwards(self, orm): ct, created = orm['contenttypes.ContentType'].objects.get_or_create( model='login', app_label='ssheepdog') for codename, name in PERMISSIONS: <|code_end|> using the current file's imports: import datetime from south.db import db from south.v2 import DataMigration from django.db import models from ssheepdog.utils import add_permission and any relevant context from other files: # Path: ssheepdog/utils.py # def add_permission(orm, codename, name, app_label='ssheepdog', model='login'): # ct, created = orm['contenttypes.ContentType'].objects.get_or_create( # model=model, app_label=app_label) # orm['auth.permission'].objects.get_or_create( # content_type=ct, codename=codename, defaults=dict(name=name)) . Output only the next line.
add_permission(orm, codename, name)
Predict the next line for this snippet: <|code_start|># def updateRedirector(redirector): """ Correct the redirector in case the protocol and/or trailing slash are missing """ if not redirector.startswith("root://"): redirector = "root://" + redirector <|code_end|> with the help of current file imports: import os import commands from pUtil import tolog, readpar from FileHandling import readJSON, writeJSON from json import loads and context from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) # # Path: FileHandling.py # def readJSON(file_name): # """ Read a dictionary from a JSON file """ # # dictionary = {} # from json import load # f = openFile(file_name, 'r') # if f: # # Read the dictionary # try: # dictionary = load(f) # except Exception, e: # tolog("!!WARNING!!2332!! Failed to read dictionary from file %s: %s" % (file_name, e)) # else: # f.close() # # return dictionary # # def writeJSON(file_name, dictionary): # """ Write the dictionary to a JSON file """ # # status = False # # from json import dump # try: # fp = open(file_name, "w") # except Exception, e: # tolog("!!WARNING!!2323!! Failed to open file %s: %s" % (file_name, e)) # else: # # Write the dictionary # try: # dump(dictionary, fp, sort_keys=True, indent=4, separators=(',', ': ')) # except Exception, e: # tolog("!!WARNING!!2324!! Failed to write dictionary to file %s: %s" % (file_name, e)) # else: # tolog("Wrote dictionary to file %s" % (file_name)) # status = True # fp.close() # # return status , which may contain function names, class names, or code. Output only the next line.
tolog("Updated redirector for missing protocol: %s" % (redirector))
Given the code snippet: <|code_start|> cmd = "curl --silent --connect-timeout 100 --max-time 120 -X POST --data \'computingsite=%s&sourcesite=%s&pandaID=%s\' %s" % (computingSite, sourceSite, pandaID, url) tolog("Trying to get FAX redirectors: %s" % (cmd)) dictionary_string = commands.getoutput(cmd) if dictionary_string != "": # try to convert to a python dictionary try: fax_redirectors_dictionary = loads(dictionary_string) except Exception, e: tolog("!!WARNING!!4444!! Failed to parse fax redirector json: %s" % (e)) else: tolog("Backing up dictionary") status = writeJSON("fax_redirectors.json", fax_redirectors_dictionary) if not status: tolog("Failed to backup the FAX redirectors") return fax_redirectors_dictionary def getFAXRedirectors(computingSite, sourceSite, jobId): """ Get the FAX redirectors primarily from the google server, fall back to schedconfig.faxredirector value """ fax_redirectors_dictionary = {} # Is the sourceSite set? if sourceSite and sourceSite.lower() != 'null': # Get the FAX redirectors (if the method returns an empty dictionary, the keys and values will be set below) fax_redirectors_dictionary = _getFAXRedirectors(computingSite, sourceSite, jobId) # Verify the dictionary if fax_redirectors_dictionary.has_key('computingsite') and fax_redirectors_dictionary['computingsite'] != None: if fax_redirectors_dictionary['computingsite'] == "" or fax_redirectors_dictionary['computingsite'].lower() == "null": <|code_end|> , generate the next line using the imports in this file: import os import commands from pUtil import tolog, readpar from FileHandling import readJSON, writeJSON from json import loads and context (functions, classes, or occasionally code) from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) # # Path: FileHandling.py # def readJSON(file_name): # """ Read a dictionary from a JSON file """ # # dictionary = {} # from json import load # f = openFile(file_name, 'r') # if f: # # Read the dictionary # try: # dictionary = load(f) # except Exception, e: # tolog("!!WARNING!!2332!! Failed to read dictionary from file %s: %s" % (file_name, e)) # else: # f.close() # # return dictionary # # def writeJSON(file_name, dictionary): # """ Write the dictionary to a JSON file """ # # status = False # # from json import dump # try: # fp = open(file_name, "w") # except Exception, e: # tolog("!!WARNING!!2323!! Failed to open file %s: %s" % (file_name, e)) # else: # # Write the dictionary # try: # dump(dictionary, fp, sort_keys=True, indent=4, separators=(',', ': ')) # except Exception, e: # tolog("!!WARNING!!2324!! Failed to write dictionary to file %s: %s" % (file_name, e)) # else: # tolog("Wrote dictionary to file %s" % (file_name)) # status = True # fp.close() # # return status . Output only the next line.
fax_redirectors_dictionary['computingsite'] = readpar('faxredirector')
Based on the snippet: <|code_start|># def updateRedirector(redirector): """ Correct the redirector in case the protocol and/or trailing slash are missing """ if not redirector.startswith("root://"): redirector = "root://" + redirector tolog("Updated redirector for missing protocol: %s" % (redirector)) if not redirector.endswith("/"): redirector = redirector + "/" tolog("Updated redirector for missing trailing /: %s" % (redirector)) # Protect against triple slashes redirector = redirector.replace('///','//') return redirector def _getFAXRedirectors(computingSite, sourceSite, pandaID, url='http://waniotest.appspot.com/SiteToFaxEndpointTranslator'): """ Get the FAX redirectors via curl or JSON """ fax_redirectors_dictionary = {} file_name = "fax_redirectors.json" if os.path.exists(file_name): # Read back the FAX redirectors from file <|code_end|> , predict the immediate next line with the help of imports: import os import commands from pUtil import tolog, readpar from FileHandling import readJSON, writeJSON from json import loads and context (classes, functions, sometimes code) from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) # # Path: FileHandling.py # def readJSON(file_name): # """ Read a dictionary from a JSON file """ # # dictionary = {} # from json import load # f = openFile(file_name, 'r') # if f: # # Read the dictionary # try: # dictionary = load(f) # except Exception, e: # tolog("!!WARNING!!2332!! Failed to read dictionary from file %s: %s" % (file_name, e)) # else: # f.close() # # return dictionary # # def writeJSON(file_name, dictionary): # """ Write the dictionary to a JSON file """ # # status = False # # from json import dump # try: # fp = open(file_name, "w") # except Exception, e: # tolog("!!WARNING!!2323!! Failed to open file %s: %s" % (file_name, e)) # else: # # Write the dictionary # try: # dump(dictionary, fp, sort_keys=True, indent=4, separators=(',', ': ')) # except Exception, e: # tolog("!!WARNING!!2324!! Failed to write dictionary to file %s: %s" % (file_name, e)) # else: # tolog("Wrote dictionary to file %s" % (file_name)) # status = True # fp.close() # # return status . Output only the next line.
fax_redirectors_dictionary = readJSON(file_name)
Based on the snippet: <|code_start|> redirector = redirector + "/" tolog("Updated redirector for missing trailing /: %s" % (redirector)) # Protect against triple slashes redirector = redirector.replace('///','//') return redirector def _getFAXRedirectors(computingSite, sourceSite, pandaID, url='http://waniotest.appspot.com/SiteToFaxEndpointTranslator'): """ Get the FAX redirectors via curl or JSON """ fax_redirectors_dictionary = {} file_name = "fax_redirectors.json" if os.path.exists(file_name): # Read back the FAX redirectors from file fax_redirectors_dictionary = readJSON(file_name) if fax_redirectors_dictionary == {}: # Attempt to get fax redirectors from Ilija Vukotic's google server cmd = "curl --silent --connect-timeout 100 --max-time 120 -X POST --data \'computingsite=%s&sourcesite=%s&pandaID=%s\' %s" % (computingSite, sourceSite, pandaID, url) tolog("Trying to get FAX redirectors: %s" % (cmd)) dictionary_string = commands.getoutput(cmd) if dictionary_string != "": # try to convert to a python dictionary try: fax_redirectors_dictionary = loads(dictionary_string) except Exception, e: tolog("!!WARNING!!4444!! Failed to parse fax redirector json: %s" % (e)) else: tolog("Backing up dictionary") <|code_end|> , predict the immediate next line with the help of imports: import os import commands from pUtil import tolog, readpar from FileHandling import readJSON, writeJSON from json import loads and context (classes, functions, sometimes code) from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) # # Path: FileHandling.py # def readJSON(file_name): # """ Read a dictionary from a JSON file """ # # dictionary = {} # from json import load # f = openFile(file_name, 'r') # if f: # # Read the dictionary # try: # dictionary = load(f) # except Exception, e: # tolog("!!WARNING!!2332!! Failed to read dictionary from file %s: %s" % (file_name, e)) # else: # f.close() # # return dictionary # # def writeJSON(file_name, dictionary): # """ Write the dictionary to a JSON file """ # # status = False # # from json import dump # try: # fp = open(file_name, "w") # except Exception, e: # tolog("!!WARNING!!2323!! Failed to open file %s: %s" % (file_name, e)) # else: # # Write the dictionary # try: # dump(dictionary, fp, sort_keys=True, indent=4, separators=(',', ': ')) # except Exception, e: # tolog("!!WARNING!!2324!! Failed to write dictionary to file %s: %s" % (file_name, e)) # else: # tolog("Wrote dictionary to file %s" % (file_name)) # status = True # fp.close() # # return status . Output only the next line.
status = writeJSON("fax_redirectors.json", fax_redirectors_dictionary)
Given the following code snippet before the placeholder: <|code_start|> logging.basicConfig(level=logging.DEBUG) class HPCManager: def __init__(self, logFileName=None): self.__globalWorkingDir = None self.__localWorkingDir = None self.__jobStateFile = 'HPCManagerState.json' self.__logFileName = logFileName <|code_end|> , predict the next line using imports from the current file: import commands import os import shutil import sys import time import traceback import json import pickle import logging from Logger import Logger from pandayoda.yodacore import Database and context including class names, function names, and sometimes code from other files: # Path: Logger.py # class Logger: # # sh1 = None # sh2 = None # # def __init__(self, filename=None): # # # get logger name # print inspect.stack() # frm = inspect.stack()[1] # mod = inspect.getmodule(frm[2]) # if mod == None or mod.__name__ == '__main__': # modName = 'main' # else: # modName = '.'.join(mod.__name__.split('.')[-2:]) # global loggerMap # if modName in loggerMap: # # use existing logger # self.log = loggerMap[modName] # else: # # make handler # fmt = MyFormatter() # fmt.converter = time.gmtime # to convert timestamps to UTC # # if filename: # # sh = logging.FileHandler(filename, mode='a') # # else: # # sh = logging.StreamHandler(sys.stdout) # self.sh1 = logging.FileHandler(filename, mode='a') # self.sh2 = logging.StreamHandler(sys.stdout) # self.sh1.setLevel(logging.DEBUG) # self.sh1.setFormatter(fmt) # self.sh2.setLevel(logging.DEBUG) # self.sh2.setFormatter(fmt) # # # make logger # self.log = logging.getLogger(modName) # self.log.propagate = False # self.log.addHandler(self.sh1) # self.log.addHandler(self.sh2) # loggerMap[modName] = self.log # # def info(self, msg): # self.log.info(msg) # #self.sh1.flush() # #self.sh2.flush() # # def debug(self, msg): # self.log.debug(msg) # # def warning(self, msg): # self.log.warning(msg) # # def error(self, msg): # self.log.error(msg) # # def critical(self, msg): # self.log.critical(msg) . Output only the next line.
self.__log= Logger(logFileName)
Predict the next line for this snippet: <|code_start|> if jobinfo.has_key("output_fields"): self.__env['jobDic'][k][1].output_fields = pUtil.stringToFields(jobinfo["output_fields"]) pUtil.tolog("Got output_fields=%s" % str(self.__env['jobDic'][k][1].output_fields)) pUtil.tolog("Converted from output_fields=%s" % str(jobinfo["output_fields"])) # corrupted files if jobinfo.has_key("corruptedFiles"): self.__env['jobDic'][k][1].corruptedFiles = jobinfo["corruptedFiles"] # hpc status if jobinfo.has_key("mode"): self.__env['jobDic'][k][1].mode = jobinfo['mode'] if jobinfo.has_key("hpcStatus"): self.__env['jobDic'][k][1].hpcStatus = jobinfo['hpcStatus'] if jobinfo.has_key("yodaJobMetrics"): self.__env['jobDic'][k][1].yodaJobMetrics = json.loads(jobinfo['yodaJobMetrics']) if jobinfo.has_key("coreCount"): self.__env['jobDic'][k][1].coreCount = jobinfo['coreCount'] if jobinfo.has_key("HPCJobId"): self.__env['jobDic'][k][1].HPCJobId = jobinfo['HPCJobId'] # zip output if jobinfo.has_key("outputZipName"): self.__env['jobDic'][k][1].outputZipName = jobinfo['outputZipName'] if jobinfo.has_key("outputZipBucketID"): self.__env['jobDic'][k][1].outputZipBucketID = jobinfo['outputZipBucketID'] if (self.__env['jobDic'][k][1].result[2] and self.__env['jobDic'][k][1].result[2] != old_pilotecode) or\ (self.__env['jobDic'][k][1].pilotErrorDiag and len(self.__env['jobDic'][k][1].pilotErrorDiag) and self.__env['jobDic'][k][1].pilotErrorDiag != old_pilotErrorDiag): <|code_end|> with the help of current file imports: import os import json import time import traceback import pUtil from SocketServer import BaseRequestHandler from Configuration import Configuration from FileHandling import updatePilotErrorReport and context from other files: # Path: FileHandling.py # def updatePilotErrorReport(pilotErrorCode, pilotErrorDiag, priority, jobID, workdir): # """ Write pilot error info to file """ # # Report format: # # { jobID1: { priority1: [{ pilotErrorCode1:<nr>, pilotErrorDiag1:<str> }, .. ], .. }, .. } # # The pilot will report only the first of the highest priority error when it reports the error at the end of the job # # Use the following priority convention: # # "0": highest priority [e.g. errors that originate from the main pilot module (unless otherwise necessary)] # # "1": high priority [e.g. errors that originate from the Monitor module (-||-)] # # "2": normal priority [errors that originate from other modules (-||-)] # # etc # # # Convert to string if integer is sent for priority # if type(priority) != str: # priority = str(priority) # # filename = getPilotErrorReportFilename(workdir) # if os.path.exists(filename): # # The file already exists, read it back (with unicode to utf-8 conversion) # dictionary = getJSONDictionary(filename) # else: # dictionary = {} # # # Sort the new error # if dictionary.has_key(jobID): # jobID_dictionary = dictionary[jobID] # # # Update with the latest error info # if not jobID_dictionary.has_key(priority): # dictionary[jobID][priority] = [] # # new_dictionary = { 'pilotErrorCode':pilotErrorCode, 'pilotErrorDiag':pilotErrorDiag } # # # Update the dictionary with the new info # dictionary[jobID][priority].append(new_dictionary) # print dictionary # # else: # # Create a first entry into the error report # dictionary[jobID] = {} # dictionary[jobID][priority] = [] # dictionary[jobID][priority].append({}) # dictionary[jobID][priority][0] = { 'pilotErrorCode':pilotErrorCode, 'pilotErrorDiag':pilotErrorDiag } # # # Finally update the file # status = writeJSON(filename, dictionary) , which may contain function names, class names, or code. Output only the next line.
updatePilotErrorReport(self.__env['jobDic'][k][1].result[2], self.__env['jobDic'][k][1].pilotErrorDiag, "2", self.__env['jobDic'][k][1].jobId, self.__env['pilot_initdir'])
Next line prediction: <|code_start|> E.g. a file with state = "created", "not_registered" should first be transferred and then registered in the LFC. The file state dictionary should be created with "not_created" states as soon as the output files are known (pilot). The "created" states should be set after the payload has run and if the file in question were actually created. "transferred" should be set by the mover once the file in question has been transferred. "registered" should be added to the file state once the file has been registered. "copy_to_scratch" is to set for all input files by default. In case remote IO / FileStager instructions are found in copysetup[in] the state will be changed to "remote_io" / "file_stager". Brokerage can also decide that remote IO is to be used. In that case, "remote_io" will be set for the relevant input files (e.g. DBRelease and lib files are excluded, i.e. they will have "copy_to_scratch" transfer mode). """ def __init__(self, workDir, jobId="0", mode="", ftype="output", fileName=""): """ Default init """ self.fileStateDictionary = {} # file dictionary holding all objects self.mode = mode # test mode # use default filename unless specified by initiator if fileName == "" and ftype != "": # assume output files self.filename = os.path.join(workDir, "fileState-%s-%s.pickle" % (ftype, jobId)) else: self.filename = os.path.join(workDir, fileName) # add mode variable if needed (e.g. mode="test") if self.mode != "": self.filename = self.filename.replace(".pickle", "-%s.pickle" % (self.mode)) # load the dictionary from file if it exists if os.path.exists(self.filename): <|code_end|> . Use current file imports: (import os import commands from pUtil import tolog from pickle import load from pickle import dump) and context including class names, function names, or small code snippets from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() . Output only the next line.
tolog("Using file state dictionary: %s" % (self.filename))
Given snippet: <|code_start|> class JobState: """ This class is used to set the current job state. When the job is running, the file jobState-<JobID>.[pickle|json] is created which contains the state of the Site, Job and Node objects. The job state file is updated at every heartbeat. """ def __init__(self): """ Default init """ self.job = None # Job class object self.site = None # Site class object self.node = None # Node class object self.filename = "" # jobState-<jobId>.[pickle|json] self.recoveryAttempt = 0 # recovery attempt number self.objectDictionary = {} # file dictionary holding all objects def decode(self): """ Decode the job state file """ if self.objectDictionary: try: # setup the internal structure (needed for cleanup) self.job = self.objectDictionary['job'] self.site = self.objectDictionary['site'] self.node = self.objectDictionary['node'] except: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import commands from pUtil import tolog from FileHandling import getExtension from json import load from pickle import load from json import dump from pickle import dump from glob import glob and context: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # Path: FileHandling.py # def getExtension(alternative='pickle'): # """ get the file extension (json or whatever 'alternative' is set to, pickle by default) """ # # try: # from json import load # except: # extension = alternative # else: # extension = "json" # # return extension which might include code, classes, or functions. Output only the next line.
tolog("JOBSTATE WARNING: Objects are missing in the recovery file (abort recovery)")
Predict the next line after this snippet: <|code_start|># This module contains functions related to file handling. def openFile(filename, mode): """ Open and return a file pointer for the given mode """ # Note: caller needs to close the file f = None if os.path.exists(filename): try: f = open(filename, mode) except IOError, e: <|code_end|> using the current file's imports: import os import hashlib from time import time from commands import getoutput from pUtil import tolog, convert, readpar from json import load from json import dump from json import load from json import load from glob import glob from re import compile, findall from re import compile from re import compile, findall from commands import getoutput from SiteMover import SiteMover from xml.dom import minidom and any relevant context from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def convert(data): # """ Convert unicode data to utf-8 """ # # # Dictionary: # # data = {u'Max': {u'maxRSS': 3664, u'maxSwap': 0, u'maxVMEM': 142260, u'maxPSS': 1288}, u'Avg': {u'avgVMEM': 94840, u'avgPSS': 850, u'avgRSS': 2430, u'avgSwap': 0}} # # convert(data) # # {'Max': {'maxRSS': 3664, 'maxSwap': 0, 'maxVMEM': 142260, 'maxPSS': 1288}, 'Avg': {'avgVMEM': 94840, 'avgPSS': 850, 'avgRSS': 2430, 'avgSwap': 0}} # # String: # # data = u'hello' # # convert(data) # # 'hello' # # List: # # data = [u'1',u'2','3'] # # convert(data) # # ['1', '2', '3'] # # import collections # if isinstance(data, basestring): # return str(data) # elif isinstance(data, collections.Mapping): # return dict(map(convert, data.iteritems())) # elif isinstance(data, collections.Iterable): # return type(data)(map(convert, data)) # else: # return data # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) . Output only the next line.
tolog("!!WARNING!!2997!! Caught exception: %s" % (e))
Here is a snippet: <|code_start|> """ Open and return a file pointer for the given mode """ # Note: caller needs to close the file f = None if os.path.exists(filename): try: f = open(filename, mode) except IOError, e: tolog("!!WARNING!!2997!! Caught exception: %s" % (e)) else: tolog("!!WARNING!!2998!! File does not exist: %s" % (filename)) return f def getJSONDictionary(filename): """ Read a dictionary with unicode to utf-8 conversion """ dictionary = None f = openFile(filename, 'r') if f: try: dictionary = load(f) except Exception, e: tolog("!!WARNING!!2222!! Failed to load json dictionary: %s" % (e)) else: f.close() # Try to convert the dictionary from unicode to utf-8 if dictionary != {}: try: <|code_end|> . Write the next line using the current file imports: import os import hashlib from time import time from commands import getoutput from pUtil import tolog, convert, readpar from json import load from json import dump from json import load from json import load from glob import glob from re import compile, findall from re import compile from re import compile, findall from commands import getoutput from SiteMover import SiteMover from xml.dom import minidom and context from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def convert(data): # """ Convert unicode data to utf-8 """ # # # Dictionary: # # data = {u'Max': {u'maxRSS': 3664, u'maxSwap': 0, u'maxVMEM': 142260, u'maxPSS': 1288}, u'Avg': {u'avgVMEM': 94840, u'avgPSS': 850, u'avgRSS': 2430, u'avgSwap': 0}} # # convert(data) # # {'Max': {'maxRSS': 3664, 'maxSwap': 0, 'maxVMEM': 142260, 'maxPSS': 1288}, 'Avg': {'avgVMEM': 94840, 'avgPSS': 850, 'avgRSS': 2430, 'avgSwap': 0}} # # String: # # data = u'hello' # # convert(data) # # 'hello' # # List: # # data = [u'1',u'2','3'] # # convert(data) # # ['1', '2', '3'] # # import collections # if isinstance(data, basestring): # return str(data) # elif isinstance(data, collections.Mapping): # return dict(map(convert, data.iteritems())) # elif isinstance(data, collections.Iterable): # return type(data)(map(convert, data)) # else: # return data # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) , which may include functions, classes, or code. Output only the next line.
dictionary = convert(dictionary)
Here is a snippet: <|code_start|> directInLAN = useDirectAccessLAN() directInWAN = useDirectAccessWAN() directInType = 'None' directIn = False if directInLAN: directInType = 'LAN' directIn = True if directInWAN: # if (directInWAN and not analyjob) or (directInWAN and directInLAN and analyjob): directInType = 'WAN' # Overrides LAN if both booleans are set to True directIn = True return directIn, directInType def _useDirectAccess(LAN=True, WAN=False): """ Should direct i/o be used over LAN or WAN? """ useDA = False if LAN: par = 'direct_access_lan' elif WAN: par = 'direct_access_wan' else: tolog("!!WARNING!!3443!! Bad LAN/WAN combination: LAN=%s, WAN=%s" % (str(LAN), str(WAN))) par = '' if par != '': <|code_end|> . Write the next line using the current file imports: import os import hashlib from time import time from commands import getoutput from pUtil import tolog, convert, readpar from json import load from json import dump from json import load from json import load from glob import glob from re import compile, findall from re import compile from re import compile, findall from commands import getoutput from SiteMover import SiteMover from xml.dom import minidom and context from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def convert(data): # """ Convert unicode data to utf-8 """ # # # Dictionary: # # data = {u'Max': {u'maxRSS': 3664, u'maxSwap': 0, u'maxVMEM': 142260, u'maxPSS': 1288}, u'Avg': {u'avgVMEM': 94840, u'avgPSS': 850, u'avgRSS': 2430, u'avgSwap': 0}} # # convert(data) # # {'Max': {'maxRSS': 3664, 'maxSwap': 0, 'maxVMEM': 142260, 'maxPSS': 1288}, 'Avg': {'avgVMEM': 94840, 'avgPSS': 850, 'avgRSS': 2430, 'avgSwap': 0}} # # String: # # data = u'hello' # # convert(data) # # 'hello' # # List: # # data = [u'1',u'2','3'] # # convert(data) # # ['1', '2', '3'] # # import collections # if isinstance(data, basestring): # return str(data) # elif isinstance(data, collections.Mapping): # return dict(map(convert, data.iteritems())) # elif isinstance(data, collections.Iterable): # return type(data)(map(convert, data)) # else: # return data # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) , which may include functions, classes, or code. Output only the next line.
da = readpar(par)
Next line prediction: <|code_start|> tolog("!!WARNING!!1190!! Since at least one move to the external disk failed, the original work area") tolog("!!WARNING!!1190!! will not be removed and should be picked up by a later pilot doing the recovery") status = False else: tolog("All files were successfully transferred to the external recovery area") else: tolog("!!WARNING!!1190!! Could not open job state file: %s" % (job_state_file)) status = False return status def cleanup(wd, initdir, wrflag, rmwkdir): """ cleanup function """ tolog("Overall cleanup function is called") # collect any zombie processes wd.collectZombieJob(tn=10) tolog("Collected zombie processes") # get the current work dir wkdir = readStringFromFile(os.path.join(initdir, "CURRENT_SITEWORKDIR")) # is there an exit code? ec = readCodeFromFile(os.path.join(wkdir, "EXITCODE")) # is there a process id pid = readCodeFromFile(os.path.join(wkdir, "PROCESSID")) if pid != 0: tolog("Found process id %d in PROCESSID file, will now attempt to kill all of its subprocesses" % (pid)) <|code_end|> . Use current file imports: (import sys, os, signal, time, shutil, cgi import commands, re import urllib import json import traceback import environment import datetime import logging import inspect import JobInfoXML import traceback import socket import collections from xml.dom import minidom from xml.dom.minidom import Document from xml.dom.minidom import parse, parseString from xml.etree import ElementTree from processes import killProcesses from PilotErrors import PilotErrors from Logger import Logger from SiteMover import SiteMover from xml.sax import make_parser from xml.sax.handler import feature_namespaces from SiteMover import SiteMover from SiteMover import SiteMover from SiteMover import SiteMover from TimerCommand import TimerCommand from SiteInformation import SiteInformation from SiteInformation import SiteInformation from JobState import JobState from DBReleaseHandler import DBReleaseHandler from SiteMover import SiteMover from glob import glob from ExperimentFactory import ExperimentFactory from SiteInformationFactory import SiteInformationFactory from urllib import urlencode from urlparse import parse_qs from cgi import parse_qs from FileHandling import findLatestTRFLogFile from glob import glob from JobLog import JobLog from JobState import JobState from glob import glob from FileHandling import getExtension from PandaServerClient import PandaServerClient from EventServiceFactory import EventServiceFactory from re import split) and context including class names, function names, or small code snippets from other files: # Path: processes.py # def killProcesses(pid, pgrp): # """ kill a job upon request """ # # pUtil.tolog("killProcesses() called") # # # if there is a known subprocess pgrp, then it should be enough to kill the group in one go # status = False # # _sleep = True # if pgrp != 0: # # kill the process gracefully # pUtil.tolog("Killing group process %d" % (pgrp)) # try: # os.killpg(pgrp, signal.SIGTERM) # except Exception,e: # pUtil.tolog("WARNING: Exception thrown when killing the child group process with SIGTERM: %s" % (e)) # _sleep = False # else: # pUtil.tolog("(SIGTERM sent)") # # if _sleep: # _t = 30 # pUtil.tolog("Sleeping %d s to allow processes to exit" % (_t)) # time.sleep(_t) # # try: # os.killpg(pgrp, signal.SIGKILL) # except Exception,e: # pUtil.tolog("WARNING: Exception thrown when killing the child group process with SIGKILL: %s" % (e)) # else: # pUtil.tolog("(SIGKILL sent)") # status = True # # if not status: # # firstly find all the children process IDs to be killed # children = [] # findProcessesInGroup(children, pid) # # # reverse the process order so that the athena process is killed first (otherwise the stdout will be truncated) # children.reverse() # pUtil.tolog("Process IDs to be killed: %s (in reverse order)" % str(children)) # # # find which commands are still running # try: # cmds = getProcessCommands(os.geteuid(), children) # except Exception, e: # pUtil.tolog("getProcessCommands() threw an exception: %s" % str(e)) # else: # if len(cmds) <= 1: # pUtil.tolog("Found no corresponding commands to process id(s)") # else: # pUtil.tolog("Found commands still running:") # for cmd in cmds: # pUtil.tolog(cmd) # # # loop over all child processes # for i in children: # # dump the stack trace before killing it # dumpStackTrace(i) # # # kill the process gracefully # try: # os.kill(i, signal.SIGTERM) # except Exception,e: # pUtil.tolog("WARNING: Exception thrown when killing the child process %d under SIGTERM, wait for kill -9 later: %s" % (i, str(e))) # pass # else: # pUtil.tolog("Killed pid: %d (SIGTERM)" % (i)) # # _t = 10 # pUtil.tolog("Sleeping %d s to allow process to exit" % (_t)) # time.sleep(_t) # # # now do a hardkill just in case some processes haven't gone away # try: # os.kill(i, signal.SIGKILL) # except Exception,e: # pUtil.tolog("WARNING: Exception thrown when killing the child process %d under SIGKILL, ignore this if it is already killed by previous SIGTERM: %s" % (i, str(e))) # pass # else: # pUtil.tolog("Killed pid: %d (SIGKILL)" % (i)) # # pUtil.tolog("Killing any remaining orphan processes") # killOrphans() . Output only the next line.
killProcesses(pid, os.getpgrp())
Given snippet: <|code_start|> utime = proctimes.split(' ')[13] # get stime from proc/<pid>/stat, 15 item stime = proctimes.split(' ')[14] # count total process used time proctotal = int(utime) + int(stime) return(float(proctotal)) except: # self.__log.debug("Rank %s: Failed to get cpu consumption time for pid %s: %s" % (self.__rank, pid, traceback.format_exc())) return 0 def getCPUConsumptionTimeFromProc(self): cpuConsumptionTime = 0L try: CLOCK_TICKS = os.sysconf("SC_CLK_TCK") if self.__child_pid: self.__childProcs = [] self.getChildren(self.__child_pid) for process in self.__childProcs: if process not in self.__child_cpuTime.keys(): self.__child_cpuTime[process] = 0 for process in self.__child_cpuTime.keys(): cpuTime = self.getCPUConsumptionTimeFromProcPid(process) / CLOCK_TICKS if cpuTime > self.__child_cpuTime[process]: self.__child_cpuTime[process] = cpuTime cpuConsumptionTime += self.__child_cpuTime[process] except: self.__log.debug("Rank %s: Failed to get cpu consumption time from proc: %s" % (self.__rank, traceback.format_exc())) return cpuConsumptionTime def getCPUConsumptionTimeReal(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import inspect import commands import os import re import signal import sys import time import Queue import multiprocessing import subprocess import threading import json import traceback import yampl from pandayoda.yodacore import Logger from FileHandling import getCPUTimes from signal_block.signal_block import block_sig, unblock_sig and context: # Path: FileHandling.py # def getCPUTimes(workDir): # """ Extract and add up the total CPU times from the job report """ # # Note: this is used with Event Service jobs # # # Input: workDir (location of jobReport.json) # # Output: cpuCU (unit), totalCPUTime, conversionFactor # # totalCPUTime = 0L # # jobReport_dictionary = getJobReport(workDir) # if jobReport_dictionary != {}: # if jobReport_dictionary.has_key('resource'): # resource_dictionary = jobReport_dictionary['resource'] # if resource_dictionary.has_key('executor'): # executor_dictionary = resource_dictionary['executor'] # for format in executor_dictionary.keys(): # "RAWtoESD", .. # if executor_dictionary[format].has_key('cpuTime'): # try: # totalCPUTime += executor_dictionary[format]['cpuTime'] # except: # pass # else: # tolog("Format %s has no such key: cpuTime" % (format)) # else: # tolog("No such key: executor") # else: # tolog("No such key: resource") # # conversionFactor = 1.0 # cpuCU = "s" # # return cpuCU, totalCPUTime, conversionFactor which might include code, classes, or functions. Output only the next line.
cpuConsumptionUnit, cpuConsumptionTime, cpuConversionFactor = getCPUTimes(os.getcwd())
Here is a snippet: <|code_start|> class Node: """ worker node information """ def __init__(self): self.cpu = 0 self.nodename = None self.mem = 0 self.disk = 0 self.numberOfCores = self.setNumberOfCores() self.benchmarks = None # set the batch job and machine features self.collectMachineFeatures() def setNodeName(self, nm): self.nodename = nm def displayNodeInfo(self): <|code_end|> . Write the next line using the current file imports: import string import os import re import commands from pUtil import tolog, readpar from FileHandling import getMaxWorkDirSize and context from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) # # Path: FileHandling.py # def getMaxWorkDirSize(path, jobId): # """ Return the maximum disk space used by a payload """ # # filename = os.path.join(path, getWorkDirSizeFilename(jobId)) # maxdirsize = 0 # # if os.path.exists(filename): # # Read back the workdir space dictionary # dictionary = readJSON(filename) # if dictionary != {}: # # Get the workdir space list # try: # workdir_size_list = dictionary['workdir_size'] # except Exception, e: # tolog("!!WARNING!!4557!! Could not read back work dir space list: %s" % (e)) # else: # # Get the maximum value from the list # maxdirsize = max(workdir_size_list) # else: # tolog("!!WARNING!!4555!! Failed to read back work dir space from file: %s" % (filename)) # else: # tolog("!!WARNING!!4556!! No such file: %s" % (filename)) # # return maxdirsize , which may include functions, classes, or code. Output only the next line.
tolog("CPU: %0.2f, memory: %0.2f, disk space: %0.2f" % (self.cpu, self.mem, self.disk))
Predict the next line for this snippet: <|code_start|> """ Add a substring field to the job metrics string """ jobMetrics = "" if value != "": jobMetrics += "%s=%s " % (name, value) return jobMetrics def addToJobMetrics(self, jobResult, path, jobId): """ Add the batch job and machine features to the job metrics """ jobMetrics = "" # jobMetrics += self.addFieldToJobMetrics("hs06", self.hs06) # jobMetrics += self.addFieldToJobMetrics("shutdowntime", self.shutdownTime) # jobMetrics += self.addFieldToJobMetrics("jobslots", self.jobSlots) # jobMetrics += self.addFieldToJobMetrics("phys_cores", self.physCores) # jobMetrics += self.addFieldToJobMetrics("log_cores", self.logCores) # jobMetrics += self.addFieldToJobMetrics("cpufactor_lrms", self.cpuFactorLrms) # jobMetrics += self.addFieldToJobMetrics("cpu_limit_secs_lrms", self.cpuLimitSecsLrms) # jobMetrics += self.addFieldToJobMetrics("cpu_limit_secs", self.cpuLimitSecs) # jobMetrics += self.addFieldToJobMetrics("wall_limit_secs_lrms", self.wallLimitSecsLrms) # jobMetrics += self.addFieldToJobMetrics("wall_limit_secs", self.wallLimitSecs) # jobMetrics += self.addFieldToJobMetrics("disk_limit_GB", self.diskLimitGB) # jobMetrics += self.addFieldToJobMetrics("jobstart_secs", self.jobStartSecs) # jobMetrics += self.addFieldToJobMetrics("mem_limit_MB", self.memLimitMB) # jobMetrics += self.addFieldToJobMetrics("allocated_CPU", self.allocatedCPU) # Get the max disk space used by the payload (at the end of a job) if jobResult == "finished" or jobResult == "failed" or jobResult == "holding": <|code_end|> with the help of current file imports: import string import os import re import commands from pUtil import tolog, readpar from FileHandling import getMaxWorkDirSize and context from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) # # Path: FileHandling.py # def getMaxWorkDirSize(path, jobId): # """ Return the maximum disk space used by a payload """ # # filename = os.path.join(path, getWorkDirSizeFilename(jobId)) # maxdirsize = 0 # # if os.path.exists(filename): # # Read back the workdir space dictionary # dictionary = readJSON(filename) # if dictionary != {}: # # Get the workdir space list # try: # workdir_size_list = dictionary['workdir_size'] # except Exception, e: # tolog("!!WARNING!!4557!! Could not read back work dir space list: %s" % (e)) # else: # # Get the maximum value from the list # maxdirsize = max(workdir_size_list) # else: # tolog("!!WARNING!!4555!! Failed to read back work dir space from file: %s" % (filename)) # else: # tolog("!!WARNING!!4556!! No such file: %s" % (filename)) # # return maxdirsize , which may contain function names, class names, or code. Output only the next line.
max_space = getMaxWorkDirSize(path, jobId)
Predict the next line after this snippet: <|code_start|> if self._loglevel is not None: if self._loglevel.isdigit(): if int(self._loglevel) >= 4: self._loglevel = logging.DEBUG elif int(self._loglevel) == 3: self._loglevel = logging.INFO elif int(self._loglevel) == 2: self._loglevel = logging.WARNING elif int(self._loglevel) == 1: self._loglevel = logging.ERROR elif int(self._loglevel) == 0: self._loglevel = logging.CRITICAL else: raise ValueError ('%s is not a valid value for %s_VERBOSE.' \ % (self._loglevel, self._uc_name)) else: if self._loglevel.lower() == 'debug': self._loglevel = logging.DEBUG elif self._loglevel.lower() == 'info': self._loglevel = logging.INFO elif self._loglevel.lower() == 'warning': self._loglevel = logging.WARNING elif self._loglevel.lower() == 'error': self._loglevel = logging.ERROR elif self._loglevel.lower() == 'critical': self._loglevel = logging.CRITICAL else: raise ValueError ('%s is not a valid value for %s_VERBOSE.' \ % (self._loglevel, self._uc_name)) # create the handlers (target + formatter + filter) for target in self._targets: if target.lower() == 'stdout': # create a console stream logger # Only enable colour if support was loaded properly if has_color_stream_handler is True: handler = ColorStreamHandler() else: handler = logging.StreamHandler() else: # got to be a file logger <|code_end|> using the current file's imports: import re import logging import radical.utils as ru import radical.utils.config as ruc from radical.utils.logger.colorstreamhandler import * from radical.utils.logger.filehandler import FileHandler from radical.utils.logger.defaultformatter import DefaultFormatter and any relevant context from other files: # Path: radical/utils/logger/filehandler.py # class FileHandler(LFileHandler): # """ A output FileHandler. """ # pass . Output only the next line.
handler = FileHandler(target)
Based on the snippet: <|code_start|> class PilotTCPServer(threading.Thread): """ TCP server used to send TCP messages from runJob to pilot """ def __init__(self, handler, name='PilotTCPServer'): """ constructor, setting initial variables """ # find an available port to create the TCPServer n = 0 while n < 20: # try 20 times before giving up, which means run 20 pilots on one machine simultaneously :) n += 1 self.port = random.randrange(1, 800, 1) + 8888 # avoid known port used for local monitoring (req. by A. de Salvo) if self.port == 9256: self.port += 1 try: self.srv = TCPServer(('localhost',self.port), handler) except socket.error, e: <|code_end|> , predict the immediate next line with the help of imports: from SocketServer import TCPServer from pUtil import tolog import threading import random import socket and context (classes, functions, sometimes code) from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() . Output only the next line.
tolog("WARNING: Can not create TCP server on port %d, re-try... : %s" % (self.port, str(e)))
Using the snippet: <|code_start|> def extractSingularityOptions(): """ Extract any singularity options from catchall """ # e.g. catchall = "somestuff singularity_options=\'-B /etc/grid-security/certificates,/var/spool/slurmd,/cvmfs,/ceph/grid,/data0,/sys/fs/cgroup\'" #catchall = "singularity_options=\'-B /etc/grid-security/certificates,/cvmfs,${workdir} --contain\'" #readpar("catchall") # ${workdir} should be there, otherwise the pilot cannot add the current workdir # if not there, add it # First try with reading new parameters from schedconfig container_options = readpar("container_options") if container_options == "": <|code_end|> , determine the next line of code. You have imports: import re import os from pUtil import tolog, readpar, getExperiment and context (class names, function names, or code) available: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) # # def getExperiment(experiment): # """ Return a reference to an experiment class """ # # from ExperimentFactory import ExperimentFactory # factory = ExperimentFactory() # _exp = None # # try: # experimentClass = factory.newExperiment(experiment) # except Exception, e: # tolog("!!WARNING!!1114!! Experiment factory threw an exception: %s" % (e)) # else: # _exp = experimentClass() # # return _exp . Output only the next line.
tolog("container_options either does not exist in queuedata or is empty, trying with catchall instead")
Given the code snippet: <|code_start|> #catchall = "singularity_options=\'-B /etc/grid-security/certificates,/cvmfs,${workdir} --contain\'" #readpar("catchall") # ${workdir} should be there, otherwise the pilot cannot add the current workdir # if not there, add it # First try with reading new parameters from schedconfig container_options = readpar("container_options") if container_options == "": tolog("container_options either does not exist in queuedata or is empty, trying with catchall instead") catchall = readpar("catchall") #catchall = "singularity_options=\'-B /etc/grid-security/certificates,/cvmfs,${workdir} --contain\'" pattern = re.compile(r"singularity\_options\=\'?\"?(.+)\'?\"?") found = re.findall(pattern, catchall) if len(found) > 0: container_options = found[0] if container_options != "": if container_options.endswith("'") or container_options.endswith('"'): container_options = container_options[:-1] # add the workdir if missing if not "${workdir}" in container_options and " --contain" in container_options: container_options = container_options.replace(" --contain", ",${workdir} --contain") tolog("Note: added missing ${workdir} to singularity_options") return container_options def getFileSystemRootPath(experiment): """ Return the proper file system root path (cvmfs) """ <|code_end|> , generate the next line using the imports in this file: import re import os from pUtil import tolog, readpar, getExperiment and context (functions, classes, or occasionally code) from other files: # Path: pUtil.py # def tolog(msg, tofile=True, label='INFO', essential=False): # """ Write date+msg to pilot log and to stdout """ # # try: # import inspect # # MAXLENGTH = 12 # # getting the name of the module that is invoking tolog() and adjust the length # try: # module_name = os.path.basename(inspect.stack()[1][1]) # except Exception, e: # module_name = "unknown" # #print "Exception caught by tolog(): ", e, # module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH) # msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg) # # t = timeStampUTC(format='%Y-%m-%d %H:%M:%S') # if tofile: # appendToLog("%s|%s\n" % (t, msg)) # # # remove backquotes from the msg since they cause problems with batch submission of pilot # # (might be present in error messages from the OS) # msg = msg.replace("`","'") # msg = msg.replace('"','\\"') # print "%s| %s" % (t, msg) # # # write any FAILED messages to stderr # if "!!FAILED!!" in msg: # try: # print >> sys.stderr, "%s| %s" % (t, msg) # except: # print "Failed to print to sys.stderr: %s" % (t, msg) # except: # print "!!WARNING!!4000!! %s" % traceback.format_exc() # # def readpar(parameter, alt=False, version=0, queuename=None): # """ Read 'parameter' from queuedata via SiteInformation class """ # # from SiteInformation import SiteInformation # si = SiteInformation() # # return si.readpar(parameter, alt=alt, version=version, queuename=queuename) # # def getExperiment(experiment): # """ Return a reference to an experiment class """ # # from ExperimentFactory import ExperimentFactory # factory = ExperimentFactory() # _exp = None # # try: # experimentClass = factory.newExperiment(experiment) # except Exception, e: # tolog("!!WARNING!!1114!! Experiment factory threw an exception: %s" % (e)) # else: # _exp = experimentClass() # # return _exp . Output only the next line.
e = getExperiment(experiment)
Given the following code snippet before the placeholder: <|code_start|>if t.TYPE_CHECKING: def _join_param_hints( param_hint: t.Optional[t.Union[t.Sequence[str], str]] ) -> t.Optional[str]: if param_hint is not None and not isinstance(param_hint, str): return " / ".join(repr(x) for x in param_hint) return param_hint class ClickException(Exception): """An exception that Click can handle and show to the user.""" #: The exit code for this exception. exit_code = 1 def __init__(self, message: str) -> None: super().__init__(message) self.message = message def format_message(self) -> str: return self.message def __str__(self) -> str: return self.message def show(self, file: t.Optional[t.IO] = None) -> None: if file is None: <|code_end|> , predict the next line using imports from the current file: import os import typing as t from gettext import gettext as _ from gettext import ngettext from ._compat import get_text_stderr from .utils import echo from .core import Context from .core import Parameter and context including class names, function names, and sometimes code from other files: # Path: src/click/_compat.py # def get_text_stderr( # encoding: t.Optional[str] = None, errors: t.Optional[str] = None # ) -> t.TextIO: # rv = _get_windows_console_stream(sys.stderr, encoding, errors) # if rv is not None: # return rv # return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) # # Path: src/click/utils.py # def echo( # message: t.Optional[t.Any] = None, # file: t.Optional[t.IO[t.Any]] = None, # nl: bool = True, # err: bool = False, # color: t.Optional[bool] = None, # ) -> None: # """Print a message and newline to stdout or a file. This should be # used instead of :func:`print` because it provides better support # for different data, files, and environments. # # Compared to :func:`print`, this does the following: # # - Ensures that the output encoding is not misconfigured on Linux. # - Supports Unicode in the Windows console. # - Supports writing to binary outputs, and supports writing bytes # to text outputs. # - Supports colors and styles on Windows. # - Removes ANSI color and style codes if the output does not look # like an interactive terminal. # - Always flushes the output. # # :param message: The string or bytes to output. Other objects are # converted to strings. # :param file: The file to write to. Defaults to ``stdout``. # :param err: Write to ``stderr`` instead of ``stdout``. # :param nl: Print a newline after the message. Enabled by default. # :param color: Force showing or hiding colors and other styles. By # default Click will remove color if the output does not look like # an interactive terminal. # # .. versionchanged:: 6.0 # Support Unicode output on the Windows console. Click does not # modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` # will still not support Unicode. # # .. versionchanged:: 4.0 # Added the ``color`` parameter. # # .. versionadded:: 3.0 # Added the ``err`` parameter. # # .. versionchanged:: 2.0 # Support colors on Windows if colorama is installed. # """ # if file is None: # if err: # file = _default_text_stderr() # else: # file = _default_text_stdout() # # # Convert non bytes/text into the native string type. # if message is not None and not isinstance(message, (str, bytes, bytearray)): # out: t.Optional[t.Union[str, bytes]] = str(message) # else: # out = message # # if nl: # out = out or "" # if isinstance(out, str): # out += "\n" # else: # out += b"\n" # # if not out: # file.flush() # return # # # If there is a message and the value looks like bytes, we manually # # need to find the binary stream and write the message in there. # # This is done separately so that most stream types will work as you # # would expect. Eg: you can write to StringIO for other cases. # if isinstance(out, (bytes, bytearray)): # binary_file = _find_binary_writer(file) # # if binary_file is not None: # file.flush() # binary_file.write(out) # binary_file.flush() # return # # # ANSI style code support. For no message or bytes, nothing happens. # # When outputting to a file instead of a terminal, strip codes. # else: # color = resolve_color_default(color) # # if should_strip_ansi(file, color): # out = strip_ansi(out) # elif WIN: # if auto_wrap_for_ansi is not None: # file = auto_wrap_for_ansi(file) # type: ignore # elif not color: # out = strip_ansi(out) # # file.write(out) # type: ignore # file.flush() . Output only the next line.
file = get_text_stderr()
Predict the next line for this snippet: <|code_start|> def _join_param_hints( param_hint: t.Optional[t.Union[t.Sequence[str], str]] ) -> t.Optional[str]: if param_hint is not None and not isinstance(param_hint, str): return " / ".join(repr(x) for x in param_hint) return param_hint class ClickException(Exception): """An exception that Click can handle and show to the user.""" #: The exit code for this exception. exit_code = 1 def __init__(self, message: str) -> None: super().__init__(message) self.message = message def format_message(self) -> str: return self.message def __str__(self) -> str: return self.message def show(self, file: t.Optional[t.IO] = None) -> None: if file is None: file = get_text_stderr() <|code_end|> with the help of current file imports: import os import typing as t from gettext import gettext as _ from gettext import ngettext from ._compat import get_text_stderr from .utils import echo from .core import Context from .core import Parameter and context from other files: # Path: src/click/_compat.py # def get_text_stderr( # encoding: t.Optional[str] = None, errors: t.Optional[str] = None # ) -> t.TextIO: # rv = _get_windows_console_stream(sys.stderr, encoding, errors) # if rv is not None: # return rv # return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) # # Path: src/click/utils.py # def echo( # message: t.Optional[t.Any] = None, # file: t.Optional[t.IO[t.Any]] = None, # nl: bool = True, # err: bool = False, # color: t.Optional[bool] = None, # ) -> None: # """Print a message and newline to stdout or a file. This should be # used instead of :func:`print` because it provides better support # for different data, files, and environments. # # Compared to :func:`print`, this does the following: # # - Ensures that the output encoding is not misconfigured on Linux. # - Supports Unicode in the Windows console. # - Supports writing to binary outputs, and supports writing bytes # to text outputs. # - Supports colors and styles on Windows. # - Removes ANSI color and style codes if the output does not look # like an interactive terminal. # - Always flushes the output. # # :param message: The string or bytes to output. Other objects are # converted to strings. # :param file: The file to write to. Defaults to ``stdout``. # :param err: Write to ``stderr`` instead of ``stdout``. # :param nl: Print a newline after the message. Enabled by default. # :param color: Force showing or hiding colors and other styles. By # default Click will remove color if the output does not look like # an interactive terminal. # # .. versionchanged:: 6.0 # Support Unicode output on the Windows console. Click does not # modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` # will still not support Unicode. # # .. versionchanged:: 4.0 # Added the ``color`` parameter. # # .. versionadded:: 3.0 # Added the ``err`` parameter. # # .. versionchanged:: 2.0 # Support colors on Windows if colorama is installed. # """ # if file is None: # if err: # file = _default_text_stderr() # else: # file = _default_text_stdout() # # # Convert non bytes/text into the native string type. # if message is not None and not isinstance(message, (str, bytes, bytearray)): # out: t.Optional[t.Union[str, bytes]] = str(message) # else: # out = message # # if nl: # out = out or "" # if isinstance(out, str): # out += "\n" # else: # out += b"\n" # # if not out: # file.flush() # return # # # If there is a message and the value looks like bytes, we manually # # need to find the binary stream and write the message in there. # # This is done separately so that most stream types will work as you # # would expect. Eg: you can write to StringIO for other cases. # if isinstance(out, (bytes, bytearray)): # binary_file = _find_binary_writer(file) # # if binary_file is not None: # file.flush() # binary_file.write(out) # binary_file.flush() # return # # # ANSI style code support. For no message or bytes, nothing happens. # # When outputting to a file instead of a terminal, strip codes. # else: # color = resolve_color_default(color) # # if should_strip_ansi(file, color): # out = strip_ansi(out) # elif WIN: # if auto_wrap_for_ansi is not None: # file = auto_wrap_for_ansi(file) # type: ignore # elif not color: # out = strip_ansi(out) # # file.write(out) # type: ignore # file.flush() , which may contain function names, class names, or code. Output only the next line.
echo(_("Error: {message}").format(message=self.format_message()), file=file)
Predict the next line after this snippet: <|code_start|> # Can force a width. This is used by the test system FORCED_WIDTH: t.Optional[int] = None def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]: widths: t.Dict[int, int] = {} for row in rows: for idx, col in enumerate(row): <|code_end|> using the current file's imports: import typing as t import shutil from contextlib import contextmanager from gettext import gettext as _ from ._compat import term_len from .parser import split_opt from ._textwrap import TextWrapper and any relevant context from other files: # Path: src/click/_compat.py # def term_len(x: str) -> int: # return len(strip_ansi(x)) # # Path: src/click/parser.py # def split_opt(opt: str) -> t.Tuple[str, str]: # first = opt[:1] # if first.isalnum(): # return "", opt # if opt[1:2] == first: # return opt[:2], opt[2:] # return first, opt[1:] . Output only the next line.
widths[idx] = max(widths.get(idx, 0), term_len(col))
Next line prediction: <|code_start|> self.indent() try: yield finally: self.dedent() @contextmanager def indentation(self) -> t.Iterator[None]: """A context manager that increases the indentation.""" self.indent() try: yield finally: self.dedent() def getvalue(self) -> str: """Returns the buffer contents.""" return "".join(self.buffer) def join_options(options: t.Sequence[str]) -> t.Tuple[str, bool]: """Given a list of option strings this joins them in the most appropriate way and returns them in the form ``(formatted_string, any_prefix_is_slash)`` where the second item in the tuple is a flag that indicates if any of the option prefixes was a slash. """ rv = [] any_prefix_is_slash = False for opt in options: <|code_end|> . Use current file imports: (import typing as t import shutil from contextlib import contextmanager from gettext import gettext as _ from ._compat import term_len from .parser import split_opt from ._textwrap import TextWrapper) and context including class names, function names, or small code snippets from other files: # Path: src/click/_compat.py # def term_len(x: str) -> int: # return len(strip_ansi(x)) # # Path: src/click/parser.py # def split_opt(opt: str) -> t.Tuple[str, str]: # first = opt[:1] # if first.isalnum(): # return "", opt # if opt[1:2] == first: # return opt[:2], opt[2:] # return first, opt[1:] . Output only the next line.
prefix = split_opt(opt)[0]
Predict the next line for this snippet: <|code_start|> self.buffer = byte_stream @property def name(self) -> str: return self.buffer.name def write(self, x: t.AnyStr) -> int: if isinstance(x, str): return self._text_stream.write(x) try: self.flush() except Exception: pass return self.buffer.write(x) def writelines(self, lines: t.Iterable[t.AnyStr]) -> None: for line in lines: self.write(line) def __getattr__(self, name: str) -> t.Any: return getattr(self._text_stream, name) def isatty(self) -> bool: return self.buffer.isatty() def __repr__(self): return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>" def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO: <|code_end|> with the help of current file imports: import io import sys import time import typing as t import msvcrt # noqa: E402 from ctypes import byref from ctypes import c_char from ctypes import c_char_p from ctypes import c_int from ctypes import c_ssize_t from ctypes import c_ulong from ctypes import c_void_p from ctypes import POINTER from ctypes import py_object from ctypes import Structure from ctypes.wintypes import DWORD from ctypes.wintypes import HANDLE from ctypes.wintypes import LPCWSTR from ctypes.wintypes import LPWSTR from ._compat import _NonClosingTextIOWrapper from ctypes import windll # noqa: E402 from ctypes import WINFUNCTYPE # noqa: E402 from ctypes import pythonapi and context from other files: # Path: src/click/_compat.py # class _NonClosingTextIOWrapper(io.TextIOWrapper): # def __init__( # self, # stream: t.BinaryIO, # encoding: t.Optional[str], # errors: t.Optional[str], # force_readable: bool = False, # force_writable: bool = False, # **extra: t.Any, # ) -> None: # self._stream = stream = t.cast( # t.BinaryIO, _FixupStream(stream, force_readable, force_writable) # ) # super().__init__(stream, encoding, errors, **extra) # # def __del__(self) -> None: # try: # self.detach() # except Exception: # pass # # def isatty(self) -> bool: # # https://bitbucket.org/pypy/pypy/issue/1803 # return self._stream.isatty() , which may contain function names, class names, or code. Output only the next line.
text_stream = _NonClosingTextIOWrapper(
Given the code snippet: <|code_start|> elif self.action == "store_const": state.opts[self.dest] = self.const # type: ignore elif self.action == "append": state.opts.setdefault(self.dest, []).append(value) # type: ignore elif self.action == "append_const": state.opts.setdefault(self.dest, []).append(self.const) # type: ignore elif self.action == "count": state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore else: raise ValueError(f"unknown action '{self.action}'") state.order.append(self.obj) class Argument: def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1): self.dest = dest self.nargs = nargs self.obj = obj def process( self, value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]], state: "ParsingState", ) -> None: if self.nargs > 1: assert value is not None holes = sum(1 for x in value if x is None) if holes == len(value): value = None elif holes != 0: <|code_end|> , generate the next line using the imports in this file: import typing as t import typing_extensions as te import shlex from collections import deque from gettext import gettext as _ from gettext import ngettext from .exceptions import BadArgumentUsage from .exceptions import BadOptionUsage from .exceptions import NoSuchOption from .exceptions import UsageError from .core import Argument as CoreArgument from .core import Context from .core import Option as CoreOption from .core import Parameter as CoreParameter from difflib import get_close_matches and context (functions, classes, or occasionally code) from other files: # Path: src/click/exceptions.py # class BadArgumentUsage(UsageError): # """Raised if an argument is generally supplied but the use of the argument # was incorrect. This is for instance raised if the number of values # for an argument is not correct. # # .. versionadded:: 6.0 # """ # # Path: src/click/exceptions.py # class BadOptionUsage(UsageError): # """Raised if an option is generally supplied but the use of the option # was incorrect. This is for instance raised if the number of arguments # for an option is not correct. # # .. versionadded:: 4.0 # # :param option_name: the name of the option being used incorrectly. # """ # # def __init__( # self, option_name: str, message: str, ctx: t.Optional["Context"] = None # ) -> None: # super().__init__(message, ctx) # self.option_name = option_name # # Path: src/click/exceptions.py # class NoSuchOption(UsageError): # """Raised if click attempted to handle an option that does not # exist. # # .. versionadded:: 4.0 # """ # # def __init__( # self, # option_name: str, # message: t.Optional[str] = None, # possibilities: t.Optional[t.Sequence[str]] = None, # ctx: t.Optional["Context"] = None, # ) -> None: # if message is None: # message = _("No such option: {name}").format(name=option_name) # # super().__init__(message, ctx) # self.option_name = option_name # self.possibilities = possibilities # # def format_message(self) -> str: # if not self.possibilities: # return self.message # # possibility_str = ", ".join(sorted(self.possibilities)) # suggest = ngettext( # "Did you mean {possibility}?", # "(Possible options: {possibilities})", # len(self.possibilities), # ).format(possibility=possibility_str, possibilities=possibility_str) # return f"{self.message} {suggest}" # # Path: src/click/exceptions.py # class UsageError(ClickException): # """An internal exception that signals a usage error. This typically # aborts any further handling. # # :param message: the error message to display. # :param ctx: optionally the context that caused this error. Click will # fill in the context automatically in some situations. # """ # # exit_code = 2 # # def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None: # super().__init__(message) # self.ctx = ctx # self.cmd = self.ctx.command if self.ctx else None # # def show(self, file: t.Optional[t.IO] = None) -> None: # if file is None: # file = get_text_stderr() # color = None # hint = "" # if ( # self.ctx is not None # and self.ctx.command.get_help_option(self.ctx) is not None # ): # hint = _("Try '{command} {option}' for help.").format( # command=self.ctx.command_path, option=self.ctx.help_option_names[0] # ) # hint = f"{hint}\n" # if self.ctx is not None: # color = self.ctx.color # echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) # echo( # _("Error: {message}").format(message=self.format_message()), # file=file, # color=color, # ) . Output only the next line.
raise BadArgumentUsage(
Next line prediction: <|code_start|> # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset! def _match_long_opt( self, opt: str, explicit_value: t.Optional[str], state: ParsingState ) -> None: if opt not in self._long_opt: possibilities = get_close_matches(opt, self._long_opt) raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx) option = self._long_opt[opt] if option.takes_value: # At this point it's safe to modify rargs by injecting the # explicit value, because no exception is raised in this # branch. This means that the inserted value will be fully # consumed. if explicit_value is not None: state.rargs.insert(0, explicit_value) value = self._get_value_from_state(opt, option, state) elif explicit_value is not None: <|code_end|> . Use current file imports: (import typing as t import typing_extensions as te import shlex from collections import deque from gettext import gettext as _ from gettext import ngettext from .exceptions import BadArgumentUsage from .exceptions import BadOptionUsage from .exceptions import NoSuchOption from .exceptions import UsageError from .core import Argument as CoreArgument from .core import Context from .core import Option as CoreOption from .core import Parameter as CoreParameter from difflib import get_close_matches) and context including class names, function names, or small code snippets from other files: # Path: src/click/exceptions.py # class BadArgumentUsage(UsageError): # """Raised if an argument is generally supplied but the use of the argument # was incorrect. This is for instance raised if the number of values # for an argument is not correct. # # .. versionadded:: 6.0 # """ # # Path: src/click/exceptions.py # class BadOptionUsage(UsageError): # """Raised if an option is generally supplied but the use of the option # was incorrect. This is for instance raised if the number of arguments # for an option is not correct. # # .. versionadded:: 4.0 # # :param option_name: the name of the option being used incorrectly. # """ # # def __init__( # self, option_name: str, message: str, ctx: t.Optional["Context"] = None # ) -> None: # super().__init__(message, ctx) # self.option_name = option_name # # Path: src/click/exceptions.py # class NoSuchOption(UsageError): # """Raised if click attempted to handle an option that does not # exist. # # .. versionadded:: 4.0 # """ # # def __init__( # self, # option_name: str, # message: t.Optional[str] = None, # possibilities: t.Optional[t.Sequence[str]] = None, # ctx: t.Optional["Context"] = None, # ) -> None: # if message is None: # message = _("No such option: {name}").format(name=option_name) # # super().__init__(message, ctx) # self.option_name = option_name # self.possibilities = possibilities # # def format_message(self) -> str: # if not self.possibilities: # return self.message # # possibility_str = ", ".join(sorted(self.possibilities)) # suggest = ngettext( # "Did you mean {possibility}?", # "(Possible options: {possibilities})", # len(self.possibilities), # ).format(possibility=possibility_str, possibilities=possibility_str) # return f"{self.message} {suggest}" # # Path: src/click/exceptions.py # class UsageError(ClickException): # """An internal exception that signals a usage error. This typically # aborts any further handling. # # :param message: the error message to display. # :param ctx: optionally the context that caused this error. Click will # fill in the context automatically in some situations. # """ # # exit_code = 2 # # def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None: # super().__init__(message) # self.ctx = ctx # self.cmd = self.ctx.command if self.ctx else None # # def show(self, file: t.Optional[t.IO] = None) -> None: # if file is None: # file = get_text_stderr() # color = None # hint = "" # if ( # self.ctx is not None # and self.ctx.command.get_help_option(self.ctx) is not None # ): # hint = _("Try '{command} {option}' for help.").format( # command=self.ctx.command_path, option=self.ctx.help_option_names[0] # ) # hint = f"{hint}\n" # if self.ctx is not None: # color = self.ctx.color # echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) # echo( # _("Error: {message}").format(message=self.format_message()), # file=file, # color=color, # ) . Output only the next line.
raise BadOptionUsage(
Here is a snippet: <|code_start|> else: state.rargs.insert(0, arg) return # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset! def _match_long_opt( self, opt: str, explicit_value: t.Optional[str], state: ParsingState ) -> None: if opt not in self._long_opt: possibilities = get_close_matches(opt, self._long_opt) <|code_end|> . Write the next line using the current file imports: import typing as t import typing_extensions as te import shlex from collections import deque from gettext import gettext as _ from gettext import ngettext from .exceptions import BadArgumentUsage from .exceptions import BadOptionUsage from .exceptions import NoSuchOption from .exceptions import UsageError from .core import Argument as CoreArgument from .core import Context from .core import Option as CoreOption from .core import Parameter as CoreParameter from difflib import get_close_matches and context from other files: # Path: src/click/exceptions.py # class BadArgumentUsage(UsageError): # """Raised if an argument is generally supplied but the use of the argument # was incorrect. This is for instance raised if the number of values # for an argument is not correct. # # .. versionadded:: 6.0 # """ # # Path: src/click/exceptions.py # class BadOptionUsage(UsageError): # """Raised if an option is generally supplied but the use of the option # was incorrect. This is for instance raised if the number of arguments # for an option is not correct. # # .. versionadded:: 4.0 # # :param option_name: the name of the option being used incorrectly. # """ # # def __init__( # self, option_name: str, message: str, ctx: t.Optional["Context"] = None # ) -> None: # super().__init__(message, ctx) # self.option_name = option_name # # Path: src/click/exceptions.py # class NoSuchOption(UsageError): # """Raised if click attempted to handle an option that does not # exist. # # .. versionadded:: 4.0 # """ # # def __init__( # self, # option_name: str, # message: t.Optional[str] = None, # possibilities: t.Optional[t.Sequence[str]] = None, # ctx: t.Optional["Context"] = None, # ) -> None: # if message is None: # message = _("No such option: {name}").format(name=option_name) # # super().__init__(message, ctx) # self.option_name = option_name # self.possibilities = possibilities # # def format_message(self) -> str: # if not self.possibilities: # return self.message # # possibility_str = ", ".join(sorted(self.possibilities)) # suggest = ngettext( # "Did you mean {possibility}?", # "(Possible options: {possibilities})", # len(self.possibilities), # ).format(possibility=possibility_str, possibilities=possibility_str) # return f"{self.message} {suggest}" # # Path: src/click/exceptions.py # class UsageError(ClickException): # """An internal exception that signals a usage error. This typically # aborts any further handling. # # :param message: the error message to display. # :param ctx: optionally the context that caused this error. Click will # fill in the context automatically in some situations. # """ # # exit_code = 2 # # def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None: # super().__init__(message) # self.ctx = ctx # self.cmd = self.ctx.command if self.ctx else None # # def show(self, file: t.Optional[t.IO] = None) -> None: # if file is None: # file = get_text_stderr() # color = None # hint = "" # if ( # self.ctx is not None # and self.ctx.command.get_help_option(self.ctx) is not None # ): # hint = _("Try '{command} {option}' for help.").format( # command=self.ctx.command_path, option=self.ctx.help_option_names[0] # ) # hint = f"{hint}\n" # if self.ctx is not None: # color = self.ctx.color # echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) # echo( # _("Error: {message}").format(message=self.format_message()), # file=file, # color=color, # ) , which may include functions, classes, or code. Output only the next line.
raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
Next line prediction: <|code_start|> option = Option(obj, opts, dest, action=action, nargs=nargs, const=const) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option def add_argument( self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1 ) -> None: """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ self._args.append(Argument(obj, dest=dest, nargs=nargs)) def parse_args( self, args: t.List[str] ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]: """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well. """ state = ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) <|code_end|> . Use current file imports: (import typing as t import typing_extensions as te import shlex from collections import deque from gettext import gettext as _ from gettext import ngettext from .exceptions import BadArgumentUsage from .exceptions import BadOptionUsage from .exceptions import NoSuchOption from .exceptions import UsageError from .core import Argument as CoreArgument from .core import Context from .core import Option as CoreOption from .core import Parameter as CoreParameter from difflib import get_close_matches) and context including class names, function names, or small code snippets from other files: # Path: src/click/exceptions.py # class BadArgumentUsage(UsageError): # """Raised if an argument is generally supplied but the use of the argument # was incorrect. This is for instance raised if the number of values # for an argument is not correct. # # .. versionadded:: 6.0 # """ # # Path: src/click/exceptions.py # class BadOptionUsage(UsageError): # """Raised if an option is generally supplied but the use of the option # was incorrect. This is for instance raised if the number of arguments # for an option is not correct. # # .. versionadded:: 4.0 # # :param option_name: the name of the option being used incorrectly. # """ # # def __init__( # self, option_name: str, message: str, ctx: t.Optional["Context"] = None # ) -> None: # super().__init__(message, ctx) # self.option_name = option_name # # Path: src/click/exceptions.py # class NoSuchOption(UsageError): # """Raised if click attempted to handle an option that does not # exist. # # .. versionadded:: 4.0 # """ # # def __init__( # self, # option_name: str, # message: t.Optional[str] = None, # possibilities: t.Optional[t.Sequence[str]] = None, # ctx: t.Optional["Context"] = None, # ) -> None: # if message is None: # message = _("No such option: {name}").format(name=option_name) # # super().__init__(message, ctx) # self.option_name = option_name # self.possibilities = possibilities # # def format_message(self) -> str: # if not self.possibilities: # return self.message # # possibility_str = ", ".join(sorted(self.possibilities)) # suggest = ngettext( # "Did you mean {possibility}?", # "(Possible options: {possibilities})", # len(self.possibilities), # ).format(possibility=possibility_str, possibilities=possibility_str) # return f"{self.message} {suggest}" # # Path: src/click/exceptions.py # class UsageError(ClickException): # """An internal exception that signals a usage error. This typically # aborts any further handling. # # :param message: the error message to display. # :param ctx: optionally the context that caused this error. Click will # fill in the context automatically in some situations. # """ # # exit_code = 2 # # def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None: # super().__init__(message) # self.ctx = ctx # self.cmd = self.ctx.command if self.ctx else None # # def show(self, file: t.Optional[t.IO] = None) -> None: # if file is None: # file = get_text_stderr() # color = None # hint = "" # if ( # self.ctx is not None # and self.ctx.command.get_help_option(self.ctx) is not None # ): # hint = _("Try '{command} {option}' for help.").format( # command=self.ctx.command_path, option=self.ctx.help_option_names[0] # ) # hint = f"{hint}\n" # if self.ctx is not None: # color = self.ctx.color # echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) # echo( # _("Error: {message}").format(message=self.format_message()), # file=file, # color=color, # ) . Output only the next line.
except UsageError:
Given snippet: <|code_start|>#! -*- coding: utf-8 -*- # test module # client module if six.PY2: else: # else __author__ = 'kensuke-mi' class TestServerHandler(unittest.TestCase): @classmethod def setUpClass(cls): if six.PY3: cls.test_senetence = '紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優。' else: cls.test_senetence = u'紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優。' cls.jumanpp_command = "/usr/local/bin/jumanpp" def test_jumanpp_process_hanlder_normal(self): """It tests jumanpp process handler""" # normal test # <|code_end|> , continue by predicting the next line. Consider current file imports: from JapaneseTokenizer.common import sever_handler from JapaneseTokenizer.jumanpp_wrapper.__jumanpp_wrapper_python2 import JumanppWrapper from JapaneseTokenizer.jumanpp_wrapper.__jumanpp_wrapper_python3 import JumanppWrapper import six import sys import unittest import os import time and context: # Path: JapaneseTokenizer/common/sever_handler.py # class ProcessDownException(Exception): # class UnixProcessHandler(object): # class JumanppHnadler(UnixProcessHandler): # def __init__(self, # command, # option=None, # pattern='EOS', # timeout_second=10): # def __del__(self): # def launch_process(self, command): # def restart_process(self): # def stop_process(self): # def __query(self, input_string): # def __notify_handler(self, signum, frame): # def query(self, input_string): # def __init__(self, # jumanpp_command, # option = None, # pattern = 'EOS', # timeout_second = 10): # def launch_jumanpp_process(self, command): which might include code, classes, or functions. Output only the next line.
jumanpp_process_handler = sever_handler.JumanppHnadler(jumanpp_command=self.jumanpp_command)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from __future__ import division <|code_end|> . Use current file imports: from six import text_type from JapaneseTokenizer import init_logger import jaconv import six import re import unicodedata import logging import neologdn and context (classes, functions, or code) from other files: # Path: JapaneseTokenizer/init_logger.py # def init_logger(logger): # # type: (logging.Logger) -> logging.Logger # logger.addHandler(st_handler) # logger.propagate = False # # return logger . Output only the next line.
logger = init_logger.init_logger(logging.getLogger(init_logger.LOGGER_NAME))
Continue the code snippet: <|code_start|> raise Exception('Pos condition expects tuple of string. However = {}'.format(p_c_tuple)) converted = [text_type] * len(p_c_tuple) for i, pos_element in enumerate(p_c_tuple): if six.PY2 and isinstance(pos_element, str): """str into unicode if python2.x""" converted[i] = pos_element.decode(self.string_encoding) elif six.PY2 and isinstance(pos_element, text_type): converted[i] = pos_element elif six.PY3: converted[i] = pos_element else: raise Exception() return tuple(converted) def __check_pos_condition(self, pos_condistion): # type: (List[Tuple[text_type, ...]])->List[Tuple[text_type, ...]] """* What you can do - Check your pos condition - It converts character type into unicode if python version is 2.x """ assert isinstance(pos_condistion, list) return [self.__convert_string_type(p_c_tuple) for p_c_tuple in pos_condistion] def filter(self, pos_condition=None, stopwords=None, is_normalize=True, <|code_end|> . Use current file imports: from JapaneseTokenizer.common.text_preprocess import normalize_text, denormalize_text from MeCab import Node from typing import List, Union, Any, Tuple, Dict, Callable, Optional from future.utils import text_type, string_types import sys import six and context (classes, functions, or code) from other files: # Path: JapaneseTokenizer/common/text_preprocess.py # def normalize_text(input_text, # dictionary_mode='ipadic', # new_line_replaced='。', # is_replace_eos=True, # is_kana=True, # is_ascii=True, # is_digit=True): # # type: (text_type,text_type,text_type,bool,bool,bool,bool)->text_type # """* What you can do # - It converts input-text into normalized-text which is good for tokenizer input. # # * Params # - new_line_replaced: a string which replaces from \n string. # """ # if is_replace_eos: # without_new_line = input_text.replace('\n', new_line_replaced) # else: # without_new_line = new_line_replaced # # if dictionary_mode=='neologd' and is_neologdn_valid: # return neologdn.normalize(normalize_text_normal_ipadic(without_new_line)) # elif dictionary_mode=='neologd' and is_neologdn_valid == False: # raise Exception("You could not call neologd dictionary bacause you do NOT install the package neologdn.") # else: # return normalize_text_normal_ipadic(without_new_line, kana=is_kana, ascii=is_ascii, digit=is_digit) # # def denormalize_text(input_text): # # type: (text_type)->text_type # """* What you can do # - It converts text into standard japanese writing way # # * Note # - hankaku-katakana is to zenkaku-katakana # - zenkaku-eisu is to hankaku-eisu # """ # if input_text in STRING_EXCEPTION: # return input_text # else: # return jaconv.z2h(input_text, kana=False, ascii=True, digit=True) . Output only the next line.
func_normalizer=normalize_text,
Here is a snippet: <|code_start|> self.is_feature = is_feature self.misc_info = misc_info self.analyzed_line = analyzed_line if isinstance(tuple_pos, tuple): self.tuple_pos = tuple_pos elif isinstance(tuple_pos, string_types): self.tuple_pos = ('*', ) else: raise Exception('Error while parsing feature object. {}'.format(tuple_pos)) class TokenizedSenetence(object): def __init__(self, sentence, tokenized_objects, string_encoding='utf-8'): # type: (text_type, List[TokenizedResult], text_type)->None """* Parameters - sentence: sentence - tokenized_objects: list of TokenizedResult object - string_encoding: Encoding type of string type. This option is used only under python2.x """ assert isinstance(sentence, text_type) assert isinstance(tokenized_objects, list) self.sentence = sentence self.tokenized_objects = tokenized_objects self.string_encoding = string_encoding def __extend_token_object(self, token_object, is_denormalize=True, <|code_end|> . Write the next line using the current file imports: from JapaneseTokenizer.common.text_preprocess import normalize_text, denormalize_text from MeCab import Node from typing import List, Union, Any, Tuple, Dict, Callable, Optional from future.utils import text_type, string_types import sys import six and context from other files: # Path: JapaneseTokenizer/common/text_preprocess.py # def normalize_text(input_text, # dictionary_mode='ipadic', # new_line_replaced='。', # is_replace_eos=True, # is_kana=True, # is_ascii=True, # is_digit=True): # # type: (text_type,text_type,text_type,bool,bool,bool,bool)->text_type # """* What you can do # - It converts input-text into normalized-text which is good for tokenizer input. # # * Params # - new_line_replaced: a string which replaces from \n string. # """ # if is_replace_eos: # without_new_line = input_text.replace('\n', new_line_replaced) # else: # without_new_line = new_line_replaced # # if dictionary_mode=='neologd' and is_neologdn_valid: # return neologdn.normalize(normalize_text_normal_ipadic(without_new_line)) # elif dictionary_mode=='neologd' and is_neologdn_valid == False: # raise Exception("You could not call neologd dictionary bacause you do NOT install the package neologdn.") # else: # return normalize_text_normal_ipadic(without_new_line, kana=is_kana, ascii=is_ascii, digit=is_digit) # # def denormalize_text(input_text): # # type: (text_type)->text_type # """* What you can do # - It converts text into standard japanese writing way # # * Note # - hankaku-katakana is to zenkaku-katakana # - zenkaku-eisu is to hankaku-eisu # """ # if input_text in STRING_EXCEPTION: # return input_text # else: # return jaconv.z2h(input_text, kana=False, ascii=True, digit=True) , which may include functions, classes, or code. Output only the next line.
func_denormalizer=denormalize_text):
Next line prediction: <|code_start|> class Fortune(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=200, blank=False) slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') content = models.TextField(blank=False) pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) votes = models.IntegerField(default=0) comments = generic.GenericRelation( Comment, content_type_field='content_type', object_id_field='object_pk' ) <|code_end|> . Use current file imports: (from datetime import datetime from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from django_fortunes.managers import FortuneManager) and context including class names, function names, or small code snippets from other files: # Path: django_fortunes/managers.py # class FortuneManager(models.Manager): # def latest(self): # "Generates a query to retrieve latest fortunes" # return self.published().order_by('-pub_date') # # def latest_by_author(self, author): # "Generates a query to retrieve latest fortunes by a given author" # return self.published().filter(author__username=author).order_by('-pub_date') # # def published(self): # "Generates a query to retrieve published fortunes" # return self.get_query_set().filter(pub_date__lte=datetime.datetime.now()) # # def top_authors(self): # "Generates a query to retrieve top fortune authors" # return self.published().values('author__username')\ # .annotate(nb=models.Count('id'))\ # .order_by('-nb') . Output only the next line.
objects = FortuneManager()
Predict the next line for this snippet: <|code_start|> class FortuneTransactionTestCase(TransactionTestCase): def create(self, title, author='Anon', content='', pub_date=datetime.now()): try: user = User.objects.get(username=author) except User.DoesNotExist: user = User(username=author, email='foo@bar.com', is_active=True) user.save() <|code_end|> with the help of current file imports: import unittest from datetime import datetime from django.contrib.auth.models import User from django.test.testcases import TransactionTestCase from django_fortunes.models import Fortune and context from other files: # Path: django_fortunes/models.py # class Fortune(models.Model): # author = models.ForeignKey(User) # title = models.CharField(max_length=200, blank=False) # slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') # content = models.TextField(blank=False) # pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) # votes = models.IntegerField(default=0) # comments = generic.GenericRelation( # Comment, # content_type_field='content_type', # object_id_field='object_pk' # ) # # objects = FortuneManager() # # def __unicode__(self): # return _("%(title)s, from %(author)s") % { # 'title': self.title, # 'author': self.author.username , # } # # def check_slug(self): # """ # If no slug has been generated yet for the current Fortune, tries to generate a # unique one # """ # if not self.slug: # prefix = "" # i = 0 # while True: # self.slug = prefix + slugify(self.title) # try: # self._default_manager.values('id').get(slug=self.slug) # i += 1 # prefix = str(i) + "-" # except Fortune.DoesNotExist: # break # return self.slug # # @models.permalink # def get_absolute_url(self): # "Retrieves the absolute django url of a fortune" # return ('fortune_detail', (), { # 'slug': self.slug, # 'year': self.pub_date.year, # 'month': self.pub_date.month, # 'day': self.pub_date.day # }) # # def save(self): # "Saves a fortune after havng checked and generated its slug" # self.check_slug() # super(Fortune, self).save() , which may contain function names, class names, or code. Output only the next line.
f = Fortune(title=title, author=user, content=content, pub_date=pub_date)
Given the following code snippet before the placeholder: <|code_start|> class FortuneExtraTest(TestCase): def test_fortunize(self): self.assertEquals(fortunize(u'<niko> foo'), u'<dl><dt class="odd">&lt;niko&gt;</dt><dd><q>foo</q></dd>\n</dl>') self.assertEquals(fortunize(u'<niko> foo\n<david> bar'), u'<dl><dt class="odd">&lt;niko&gt;</dt><dd><q>foo</q></dd>\n<dt class="even">&lt;david&gt;</dt><dd><q>bar</q></dd>\n</dl>') self.assertEquals(fortunize(u'<script>foo</script>'), u'<dl><dt class="odd">&lt;script&gt;</dt><dd><q>foo&lt;/script&gt;</q></dd>\n</dl>') def test_top_contributors(self): <|code_end|> , predict the next line using imports from the current file: import unittest from django.test.testcases import TestCase from django_fortunes.templatetags.fortune_extras import fortunize, top_contributors and context including class names, function names, and sometimes code from other files: # Path: django_fortunes/templatetags/fortune_extras.py # @register.filter # @stringfilter # def fortunize(value): # """ # Transforms a fortune plain text into htmlized (but safe) one. # """ # r = "" # for i, line in enumerate(value.splitlines()): # m = re.findall(r"^<(\w+)>\s?(.*)$", line.strip()) # className = "odd" if i % 2 == 0 else "even" # if (len(m) > 0): # for match in m: # nick = match[0] # quote = escape(match[1]) # r += "<dt class=\"%s\">&lt;%s&gt;</dt><dd><q>%s</q></dd>\n" % (className, nick, quote) # else: # r += "<dt>&nbsp;</dt><dd>%s</dd>\n" % (escape(line)) # return "<dl>%s</dl>" % r # # @register.inclusion_tag('partials/topcontributors.html') # def top_contributors(): # """ # Displays the list of MAX_TOP_CONTRIBUTORS top contributors # """ # max = getattr(settings, 'FORTUNES_MAX_TOP_CONTRIBUTORS', 5) # return {'authors': Fortune.objects.top_authors()[:max]} . Output only the next line.
authors = top_contributors()['authors'];
Given snippet: <|code_start|> class FortuneTest(FortuneTransactionTestCase): def test_check_slug(self): f1 = self.create(title='plop') self.assertEquals(f1.slug, 'plop') f2 = self.create(title='plop') self.assertEquals(f2.slug, '1-plop') f3 = self.create(title='plop') self.assertEquals(f3.slug, '2-plop') f2.delete() f4 = self.create(title='plop') self.assertEquals(f4.slug, '1-plop') <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from utils import FortuneTransactionTestCase from datetime import datetime from django.test.testcases import TestCase, TransactionTestCase from django_fortunes.models import Fortune and context: # Path: django_fortunes/models.py # class Fortune(models.Model): # author = models.ForeignKey(User) # title = models.CharField(max_length=200, blank=False) # slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') # content = models.TextField(blank=False) # pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) # votes = models.IntegerField(default=0) # comments = generic.GenericRelation( # Comment, # content_type_field='content_type', # object_id_field='object_pk' # ) # # objects = FortuneManager() # # def __unicode__(self): # return _("%(title)s, from %(author)s") % { # 'title': self.title, # 'author': self.author.username , # } # # def check_slug(self): # """ # If no slug has been generated yet for the current Fortune, tries to generate a # unique one # """ # if not self.slug: # prefix = "" # i = 0 # while True: # self.slug = prefix + slugify(self.title) # try: # self._default_manager.values('id').get(slug=self.slug) # i += 1 # prefix = str(i) + "-" # except Fortune.DoesNotExist: # break # return self.slug # # @models.permalink # def get_absolute_url(self): # "Retrieves the absolute django url of a fortune" # return ('fortune_detail', (), { # 'slug': self.slug, # 'year': self.pub_date.year, # 'month': self.pub_date.month, # 'day': self.pub_date.day # }) # # def save(self): # "Saves a fortune after havng checked and generated its slug" # self.check_slug() # super(Fortune, self).save() which might include code, classes, or functions. Output only the next line.
Fortune.objects.get(slug='plop').delete()
Given snippet: <|code_start|> def fortune_detail(request, year, month, day, slug, template_name='detail.html', template_object_name='fortune', **kwargs): ''' Display one fortune, and provides a comment form wich will be handled and persisted if request is POST ''' return date_based.object_detail( request, year = year, month = month, day = day, date_field = 'pub_date', slug = slug, <|code_end|> , continue by predicting the next line. Consider current file imports: from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404, redirect, render_to_response from django.conf import settings from django.views.generic import date_based, list_detail from django.template import RequestContext from django.contrib.auth.decorators import login_required from django_fortunes.models import Fortune from django_fortunes.forms import PublicFortuneForm and context: # Path: django_fortunes/models.py # class Fortune(models.Model): # author = models.ForeignKey(User) # title = models.CharField(max_length=200, blank=False) # slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') # content = models.TextField(blank=False) # pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) # votes = models.IntegerField(default=0) # comments = generic.GenericRelation( # Comment, # content_type_field='content_type', # object_id_field='object_pk' # ) # # objects = FortuneManager() # # def __unicode__(self): # return _("%(title)s, from %(author)s") % { # 'title': self.title, # 'author': self.author.username , # } # # def check_slug(self): # """ # If no slug has been generated yet for the current Fortune, tries to generate a # unique one # """ # if not self.slug: # prefix = "" # i = 0 # while True: # self.slug = prefix + slugify(self.title) # try: # self._default_manager.values('id').get(slug=self.slug) # i += 1 # prefix = str(i) + "-" # except Fortune.DoesNotExist: # break # return self.slug # # @models.permalink # def get_absolute_url(self): # "Retrieves the absolute django url of a fortune" # return ('fortune_detail', (), { # 'slug': self.slug, # 'year': self.pub_date.year, # 'month': self.pub_date.month, # 'day': self.pub_date.day # }) # # def save(self): # "Saves a fortune after havng checked and generated its slug" # self.check_slug() # super(Fortune, self).save() # # Path: django_fortunes/forms.py # class PublicFortuneForm(FortuneForm): # class Meta(FortuneForm.Meta): # exclude = ('author', 'pub_date', 'votes', 'slug',) which might include code, classes, or functions. Output only the next line.
queryset = Fortune.objects.published(),
Based on the snippet: <|code_start|> queryset = Fortune.objects.latest() # Ordering if order_type == 'top': queryset = queryset.order_by('-votes') elif order_type == 'worst': queryset = queryset.order_by('votes') else: # latest queryset = queryset.order_by('-pub_date') extra['order_type'] = order_type return list_detail.object_list( request, queryset = queryset, paginate_by = getattr(settings, 'FORTUNES_MAX_PER_PAGE', 3), template_name = template_name, template_object_name = template_object_name, extra_context = extra, **kwargs ) @login_required def fortune_new(request, template_name='new.html'): ''' Provides a Fortune creation form, validates the form if values posted and saves a new Fortune in the database if everything's okay ''' if request.method == 'POST': <|code_end|> , predict the immediate next line with the help of imports: from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404, redirect, render_to_response from django.conf import settings from django.views.generic import date_based, list_detail from django.template import RequestContext from django.contrib.auth.decorators import login_required from django_fortunes.models import Fortune from django_fortunes.forms import PublicFortuneForm and context (classes, functions, sometimes code) from other files: # Path: django_fortunes/models.py # class Fortune(models.Model): # author = models.ForeignKey(User) # title = models.CharField(max_length=200, blank=False) # slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') # content = models.TextField(blank=False) # pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) # votes = models.IntegerField(default=0) # comments = generic.GenericRelation( # Comment, # content_type_field='content_type', # object_id_field='object_pk' # ) # # objects = FortuneManager() # # def __unicode__(self): # return _("%(title)s, from %(author)s") % { # 'title': self.title, # 'author': self.author.username , # } # # def check_slug(self): # """ # If no slug has been generated yet for the current Fortune, tries to generate a # unique one # """ # if not self.slug: # prefix = "" # i = 0 # while True: # self.slug = prefix + slugify(self.title) # try: # self._default_manager.values('id').get(slug=self.slug) # i += 1 # prefix = str(i) + "-" # except Fortune.DoesNotExist: # break # return self.slug # # @models.permalink # def get_absolute_url(self): # "Retrieves the absolute django url of a fortune" # return ('fortune_detail', (), { # 'slug': self.slug, # 'year': self.pub_date.year, # 'month': self.pub_date.month, # 'day': self.pub_date.day # }) # # def save(self): # "Saves a fortune after havng checked and generated its slug" # self.check_slug() # super(Fortune, self).save() # # Path: django_fortunes/forms.py # class PublicFortuneForm(FortuneForm): # class Meta(FortuneForm.Meta): # exclude = ('author', 'pub_date', 'votes', 'slug',) . Output only the next line.
form = PublicFortuneForm(request.POST)
Here is a snippet: <|code_start|> class FortuneAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('author', 'title', 'slug', 'content', 'votes') }), ('Advanced options', { 'classes': ('collapse',), 'fields': ('pub_date',) }), ) list_display = ('title', 'slug', 'author', 'votes') prepopulated_fields = {"slug": ("title",)} <|code_end|> . Write the next line using the current file imports: from django_fortunes.models import Fortune from django.contrib import admin and context from other files: # Path: django_fortunes/models.py # class Fortune(models.Model): # author = models.ForeignKey(User) # title = models.CharField(max_length=200, blank=False) # slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') # content = models.TextField(blank=False) # pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) # votes = models.IntegerField(default=0) # comments = generic.GenericRelation( # Comment, # content_type_field='content_type', # object_id_field='object_pk' # ) # # objects = FortuneManager() # # def __unicode__(self): # return _("%(title)s, from %(author)s") % { # 'title': self.title, # 'author': self.author.username , # } # # def check_slug(self): # """ # If no slug has been generated yet for the current Fortune, tries to generate a # unique one # """ # if not self.slug: # prefix = "" # i = 0 # while True: # self.slug = prefix + slugify(self.title) # try: # self._default_manager.values('id').get(slug=self.slug) # i += 1 # prefix = str(i) + "-" # except Fortune.DoesNotExist: # break # return self.slug # # @models.permalink # def get_absolute_url(self): # "Retrieves the absolute django url of a fortune" # return ('fortune_detail', (), { # 'slug': self.slug, # 'year': self.pub_date.year, # 'month': self.pub_date.month, # 'day': self.pub_date.day # }) # # def save(self): # "Saves a fortune after havng checked and generated its slug" # self.check_slug() # super(Fortune, self).save() , which may include functions, classes, or code. Output only the next line.
admin.site.register(Fortune, FortuneAdmin)
Next line prediction: <|code_start|> class FortuneFeed(Feed): author_name = 'The django_fortunes application' _site = Site.objects.get_current() <|code_end|> . Use current file imports: (from django.contrib.syndication.views import Feed from django.contrib.sites.models import Site from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import get_object_or_404 from django.conf import settings from django.core.urlresolvers import reverse from django_fortunes.models import Fortune from django_fortunes.templatetags.fortune_extras import fortunize) and context including class names, function names, or small code snippets from other files: # Path: django_fortunes/models.py # class Fortune(models.Model): # author = models.ForeignKey(User) # title = models.CharField(max_length=200, blank=False) # slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') # content = models.TextField(blank=False) # pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) # votes = models.IntegerField(default=0) # comments = generic.GenericRelation( # Comment, # content_type_field='content_type', # object_id_field='object_pk' # ) # # objects = FortuneManager() # # def __unicode__(self): # return _("%(title)s, from %(author)s") % { # 'title': self.title, # 'author': self.author.username , # } # # def check_slug(self): # """ # If no slug has been generated yet for the current Fortune, tries to generate a # unique one # """ # if not self.slug: # prefix = "" # i = 0 # while True: # self.slug = prefix + slugify(self.title) # try: # self._default_manager.values('id').get(slug=self.slug) # i += 1 # prefix = str(i) + "-" # except Fortune.DoesNotExist: # break # return self.slug # # @models.permalink # def get_absolute_url(self): # "Retrieves the absolute django url of a fortune" # return ('fortune_detail', (), { # 'slug': self.slug, # 'year': self.pub_date.year, # 'month': self.pub_date.month, # 'day': self.pub_date.day # }) # # def save(self): # "Saves a fortune after havng checked and generated its slug" # self.check_slug() # super(Fortune, self).save() # # Path: django_fortunes/templatetags/fortune_extras.py # @register.filter # @stringfilter # def fortunize(value): # """ # Transforms a fortune plain text into htmlized (but safe) one. # """ # r = "" # for i, line in enumerate(value.splitlines()): # m = re.findall(r"^<(\w+)>\s?(.*)$", line.strip()) # className = "odd" if i % 2 == 0 else "even" # if (len(m) > 0): # for match in m: # nick = match[0] # quote = escape(match[1]) # r += "<dt class=\"%s\">&lt;%s&gt;</dt><dd><q>%s</q></dd>\n" % (className, nick, quote) # else: # r += "<dt>&nbsp;</dt><dd>%s</dd>\n" % (escape(line)) # return "<dl>%s</dl>" % r . Output only the next line.
manager = Fortune.objects
Next line prediction: <|code_start|> class FortuneFeed(Feed): author_name = 'The django_fortunes application' _site = Site.objects.get_current() manager = Fortune.objects def item_author_name(self, item): return item.author def item_description(self, item): <|code_end|> . Use current file imports: (from django.contrib.syndication.views import Feed from django.contrib.sites.models import Site from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import get_object_or_404 from django.conf import settings from django.core.urlresolvers import reverse from django_fortunes.models import Fortune from django_fortunes.templatetags.fortune_extras import fortunize) and context including class names, function names, or small code snippets from other files: # Path: django_fortunes/models.py # class Fortune(models.Model): # author = models.ForeignKey(User) # title = models.CharField(max_length=200, blank=False) # slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') # content = models.TextField(blank=False) # pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) # votes = models.IntegerField(default=0) # comments = generic.GenericRelation( # Comment, # content_type_field='content_type', # object_id_field='object_pk' # ) # # objects = FortuneManager() # # def __unicode__(self): # return _("%(title)s, from %(author)s") % { # 'title': self.title, # 'author': self.author.username , # } # # def check_slug(self): # """ # If no slug has been generated yet for the current Fortune, tries to generate a # unique one # """ # if not self.slug: # prefix = "" # i = 0 # while True: # self.slug = prefix + slugify(self.title) # try: # self._default_manager.values('id').get(slug=self.slug) # i += 1 # prefix = str(i) + "-" # except Fortune.DoesNotExist: # break # return self.slug # # @models.permalink # def get_absolute_url(self): # "Retrieves the absolute django url of a fortune" # return ('fortune_detail', (), { # 'slug': self.slug, # 'year': self.pub_date.year, # 'month': self.pub_date.month, # 'day': self.pub_date.day # }) # # def save(self): # "Saves a fortune after havng checked and generated its slug" # self.check_slug() # super(Fortune, self).save() # # Path: django_fortunes/templatetags/fortune_extras.py # @register.filter # @stringfilter # def fortunize(value): # """ # Transforms a fortune plain text into htmlized (but safe) one. # """ # r = "" # for i, line in enumerate(value.splitlines()): # m = re.findall(r"^<(\w+)>\s?(.*)$", line.strip()) # className = "odd" if i % 2 == 0 else "even" # if (len(m) > 0): # for match in m: # nick = match[0] # quote = escape(match[1]) # r += "<dt class=\"%s\">&lt;%s&gt;</dt><dd><q>%s</q></dd>\n" % (className, nick, quote) # else: # r += "<dt>&nbsp;</dt><dd>%s</dd>\n" % (escape(line)) # return "<dl>%s</dl>" % r . Output only the next line.
return fortunize(item.content)
Predict the next line for this snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<page>\d)?$', fortune_list, name='fortune_index_type'), url(r'^new$', fortune_new, name='fortune_new'), url(r'^show/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$', fortune_detail, name='fortune_detail'), url(r'^vote/(?P<object_pk>\d+)/(?P<direction>(up|down))$', fortune_vote, name='fortune_vote'), url(r'^feed/latest/$', <|code_end|> with the help of current file imports: from django.conf.urls.defaults import * from django.conf import settings from django_fortunes.feeds import LatestFortunes, LatestFortunesByAuthor from django_fortunes.views import fortune_list, fortune_detail, \ fortune_vote, fortune_new and context from other files: # Path: django_fortunes/feeds.py # class LatestFortunes(FortuneFeed): # title = "Latest fortunes" # description = "Latest fortunes added." # # def items(self): # return self.manager.latest() # # def link(self, obj): # return reverse('fortune_index_type', kwargs={'order_type': 'latest'}) # # class LatestFortunesByAuthor(FortuneFeed): # def get_object(self, request, username): # ''' Retrieve simple param in url, waiting for authenticated user ''' # return get_object_or_404(User, username=username) # # def title(self, obj): # return "Latest fortunes by %s" % obj # # def link(self, obj): # if not obj: # raise FeedDoesNotExist # return reverse('fortune_index_author', kwargs={'author': obj}) # # def description(self, obj): # return "Latest fortunes added by %s." % obj # # def items(self, obj): # return obj.fortune_set.all()[:getattr(settings, 'FORTUNES_MAX_PER_PAGE', 5)] # # Path: django_fortunes/views.py # def fortune_list(request, order_type='latest', author=None, template_name='index.html', # template_object_name='fortune', **kwargs): # ''' # Lists Fortunes # ''' # # extra = {} # # # Filtering # if author: # queryset = Fortune.objects.latest_by_author(author) # extra['author'] = author # else: # queryset = Fortune.objects.latest() # # # Ordering # if order_type == 'top': # queryset = queryset.order_by('-votes') # elif order_type == 'worst': # queryset = queryset.order_by('votes') # else: # # latest # queryset = queryset.order_by('-pub_date') # # extra['order_type'] = order_type # # return list_detail.object_list( # request, # queryset = queryset, # paginate_by = getattr(settings, 'FORTUNES_MAX_PER_PAGE', 3), # template_name = template_name, # template_object_name = template_object_name, # extra_context = extra, # **kwargs # ) # # def fortune_detail(request, year, month, day, slug, # template_name='detail.html', template_object_name='fortune', # **kwargs): # ''' # Display one fortune, and provides a comment form wich will # be handled and persisted if request is POST # ''' # return date_based.object_detail( # request, # year = year, # month = month, # day = day, # date_field = 'pub_date', # slug = slug, # queryset = Fortune.objects.published(), # month_format = '%m', # template_object_name = template_object_name, # template_name = template_name, # **kwargs # ) # # def fortune_vote(request, object_pk, direction): # ''' # Votes up or down a fortune # ''' # fortune = get_object_or_404(Fortune, pk=object_pk) # fortune.votes += 1 if direction == 'up' else -1 # fortune.save() # # return redirect(fortune) # # @login_required # def fortune_new(request, template_name='new.html'): # ''' # Provides a Fortune creation form, validates the form if values posted # and saves a new Fortune in the database if everything's okay # ''' # if request.method == 'POST': # form = PublicFortuneForm(request.POST) # if form.is_valid(): # fortune = form.save(commit=False) # fortune.author = request.user # fortune.save() # return redirect(fortune) # else: # form = PublicFortuneForm() # return render_to_response(template_name, # {'form': form, 'section': 'new'}, # context_instance=RequestContext(request)) , which may contain function names, class names, or code. Output only the next line.
LatestFortunes(),
Continue the code snippet: <|code_start|>urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<page>\d)?$', fortune_list, name='fortune_index_type'), url(r'^new$', fortune_new, name='fortune_new'), url(r'^show/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$', fortune_detail, name='fortune_detail'), url(r'^vote/(?P<object_pk>\d+)/(?P<direction>(up|down))$', fortune_vote, name='fortune_vote'), url(r'^feed/latest/$', LatestFortunes(), name='feed_latest_fortunes'), url(r'^feed/author/(?P<username>\w+)/$', <|code_end|> . Use current file imports: from django.conf.urls.defaults import * from django.conf import settings from django_fortunes.feeds import LatestFortunes, LatestFortunesByAuthor from django_fortunes.views import fortune_list, fortune_detail, \ fortune_vote, fortune_new and context (classes, functions, or code) from other files: # Path: django_fortunes/feeds.py # class LatestFortunes(FortuneFeed): # title = "Latest fortunes" # description = "Latest fortunes added." # # def items(self): # return self.manager.latest() # # def link(self, obj): # return reverse('fortune_index_type', kwargs={'order_type': 'latest'}) # # class LatestFortunesByAuthor(FortuneFeed): # def get_object(self, request, username): # ''' Retrieve simple param in url, waiting for authenticated user ''' # return get_object_or_404(User, username=username) # # def title(self, obj): # return "Latest fortunes by %s" % obj # # def link(self, obj): # if not obj: # raise FeedDoesNotExist # return reverse('fortune_index_author', kwargs={'author': obj}) # # def description(self, obj): # return "Latest fortunes added by %s." % obj # # def items(self, obj): # return obj.fortune_set.all()[:getattr(settings, 'FORTUNES_MAX_PER_PAGE', 5)] # # Path: django_fortunes/views.py # def fortune_list(request, order_type='latest', author=None, template_name='index.html', # template_object_name='fortune', **kwargs): # ''' # Lists Fortunes # ''' # # extra = {} # # # Filtering # if author: # queryset = Fortune.objects.latest_by_author(author) # extra['author'] = author # else: # queryset = Fortune.objects.latest() # # # Ordering # if order_type == 'top': # queryset = queryset.order_by('-votes') # elif order_type == 'worst': # queryset = queryset.order_by('votes') # else: # # latest # queryset = queryset.order_by('-pub_date') # # extra['order_type'] = order_type # # return list_detail.object_list( # request, # queryset = queryset, # paginate_by = getattr(settings, 'FORTUNES_MAX_PER_PAGE', 3), # template_name = template_name, # template_object_name = template_object_name, # extra_context = extra, # **kwargs # ) # # def fortune_detail(request, year, month, day, slug, # template_name='detail.html', template_object_name='fortune', # **kwargs): # ''' # Display one fortune, and provides a comment form wich will # be handled and persisted if request is POST # ''' # return date_based.object_detail( # request, # year = year, # month = month, # day = day, # date_field = 'pub_date', # slug = slug, # queryset = Fortune.objects.published(), # month_format = '%m', # template_object_name = template_object_name, # template_name = template_name, # **kwargs # ) # # def fortune_vote(request, object_pk, direction): # ''' # Votes up or down a fortune # ''' # fortune = get_object_or_404(Fortune, pk=object_pk) # fortune.votes += 1 if direction == 'up' else -1 # fortune.save() # # return redirect(fortune) # # @login_required # def fortune_new(request, template_name='new.html'): # ''' # Provides a Fortune creation form, validates the form if values posted # and saves a new Fortune in the database if everything's okay # ''' # if request.method == 'POST': # form = PublicFortuneForm(request.POST) # if form.is_valid(): # fortune = form.save(commit=False) # fortune.author = request.user # fortune.save() # return redirect(fortune) # else: # form = PublicFortuneForm() # return render_to_response(template_name, # {'form': form, 'section': 'new'}, # context_instance=RequestContext(request)) . Output only the next line.
LatestFortunesByAuthor(),
Given the code snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<page>\d)?$', fortune_list, name='fortune_index_type'), url(r'^new$', fortune_new, name='fortune_new'), url(r'^show/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$', <|code_end|> , generate the next line using the imports in this file: from django.conf.urls.defaults import * from django.conf import settings from django_fortunes.feeds import LatestFortunes, LatestFortunesByAuthor from django_fortunes.views import fortune_list, fortune_detail, \ fortune_vote, fortune_new and context (functions, classes, or occasionally code) from other files: # Path: django_fortunes/feeds.py # class LatestFortunes(FortuneFeed): # title = "Latest fortunes" # description = "Latest fortunes added." # # def items(self): # return self.manager.latest() # # def link(self, obj): # return reverse('fortune_index_type', kwargs={'order_type': 'latest'}) # # class LatestFortunesByAuthor(FortuneFeed): # def get_object(self, request, username): # ''' Retrieve simple param in url, waiting for authenticated user ''' # return get_object_or_404(User, username=username) # # def title(self, obj): # return "Latest fortunes by %s" % obj # # def link(self, obj): # if not obj: # raise FeedDoesNotExist # return reverse('fortune_index_author', kwargs={'author': obj}) # # def description(self, obj): # return "Latest fortunes added by %s." % obj # # def items(self, obj): # return obj.fortune_set.all()[:getattr(settings, 'FORTUNES_MAX_PER_PAGE', 5)] # # Path: django_fortunes/views.py # def fortune_list(request, order_type='latest', author=None, template_name='index.html', # template_object_name='fortune', **kwargs): # ''' # Lists Fortunes # ''' # # extra = {} # # # Filtering # if author: # queryset = Fortune.objects.latest_by_author(author) # extra['author'] = author # else: # queryset = Fortune.objects.latest() # # # Ordering # if order_type == 'top': # queryset = queryset.order_by('-votes') # elif order_type == 'worst': # queryset = queryset.order_by('votes') # else: # # latest # queryset = queryset.order_by('-pub_date') # # extra['order_type'] = order_type # # return list_detail.object_list( # request, # queryset = queryset, # paginate_by = getattr(settings, 'FORTUNES_MAX_PER_PAGE', 3), # template_name = template_name, # template_object_name = template_object_name, # extra_context = extra, # **kwargs # ) # # def fortune_detail(request, year, month, day, slug, # template_name='detail.html', template_object_name='fortune', # **kwargs): # ''' # Display one fortune, and provides a comment form wich will # be handled and persisted if request is POST # ''' # return date_based.object_detail( # request, # year = year, # month = month, # day = day, # date_field = 'pub_date', # slug = slug, # queryset = Fortune.objects.published(), # month_format = '%m', # template_object_name = template_object_name, # template_name = template_name, # **kwargs # ) # # def fortune_vote(request, object_pk, direction): # ''' # Votes up or down a fortune # ''' # fortune = get_object_or_404(Fortune, pk=object_pk) # fortune.votes += 1 if direction == 'up' else -1 # fortune.save() # # return redirect(fortune) # # @login_required # def fortune_new(request, template_name='new.html'): # ''' # Provides a Fortune creation form, validates the form if values posted # and saves a new Fortune in the database if everything's okay # ''' # if request.method == 'POST': # form = PublicFortuneForm(request.POST) # if form.is_valid(): # fortune = form.save(commit=False) # fortune.author = request.user # fortune.save() # return redirect(fortune) # else: # form = PublicFortuneForm() # return render_to_response(template_name, # {'form': form, 'section': 'new'}, # context_instance=RequestContext(request)) . Output only the next line.
fortune_detail,
Predict the next line after this snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<page>\d)?$', fortune_list, name='fortune_index_type'), url(r'^new$', fortune_new, name='fortune_new'), url(r'^show/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$', fortune_detail, name='fortune_detail'), url(r'^vote/(?P<object_pk>\d+)/(?P<direction>(up|down))$', <|code_end|> using the current file's imports: from django.conf.urls.defaults import * from django.conf import settings from django_fortunes.feeds import LatestFortunes, LatestFortunesByAuthor from django_fortunes.views import fortune_list, fortune_detail, \ fortune_vote, fortune_new and any relevant context from other files: # Path: django_fortunes/feeds.py # class LatestFortunes(FortuneFeed): # title = "Latest fortunes" # description = "Latest fortunes added." # # def items(self): # return self.manager.latest() # # def link(self, obj): # return reverse('fortune_index_type', kwargs={'order_type': 'latest'}) # # class LatestFortunesByAuthor(FortuneFeed): # def get_object(self, request, username): # ''' Retrieve simple param in url, waiting for authenticated user ''' # return get_object_or_404(User, username=username) # # def title(self, obj): # return "Latest fortunes by %s" % obj # # def link(self, obj): # if not obj: # raise FeedDoesNotExist # return reverse('fortune_index_author', kwargs={'author': obj}) # # def description(self, obj): # return "Latest fortunes added by %s." % obj # # def items(self, obj): # return obj.fortune_set.all()[:getattr(settings, 'FORTUNES_MAX_PER_PAGE', 5)] # # Path: django_fortunes/views.py # def fortune_list(request, order_type='latest', author=None, template_name='index.html', # template_object_name='fortune', **kwargs): # ''' # Lists Fortunes # ''' # # extra = {} # # # Filtering # if author: # queryset = Fortune.objects.latest_by_author(author) # extra['author'] = author # else: # queryset = Fortune.objects.latest() # # # Ordering # if order_type == 'top': # queryset = queryset.order_by('-votes') # elif order_type == 'worst': # queryset = queryset.order_by('votes') # else: # # latest # queryset = queryset.order_by('-pub_date') # # extra['order_type'] = order_type # # return list_detail.object_list( # request, # queryset = queryset, # paginate_by = getattr(settings, 'FORTUNES_MAX_PER_PAGE', 3), # template_name = template_name, # template_object_name = template_object_name, # extra_context = extra, # **kwargs # ) # # def fortune_detail(request, year, month, day, slug, # template_name='detail.html', template_object_name='fortune', # **kwargs): # ''' # Display one fortune, and provides a comment form wich will # be handled and persisted if request is POST # ''' # return date_based.object_detail( # request, # year = year, # month = month, # day = day, # date_field = 'pub_date', # slug = slug, # queryset = Fortune.objects.published(), # month_format = '%m', # template_object_name = template_object_name, # template_name = template_name, # **kwargs # ) # # def fortune_vote(request, object_pk, direction): # ''' # Votes up or down a fortune # ''' # fortune = get_object_or_404(Fortune, pk=object_pk) # fortune.votes += 1 if direction == 'up' else -1 # fortune.save() # # return redirect(fortune) # # @login_required # def fortune_new(request, template_name='new.html'): # ''' # Provides a Fortune creation form, validates the form if values posted # and saves a new Fortune in the database if everything's okay # ''' # if request.method == 'POST': # form = PublicFortuneForm(request.POST) # if form.is_valid(): # fortune = form.save(commit=False) # fortune.author = request.user # fortune.save() # return redirect(fortune) # else: # form = PublicFortuneForm() # return render_to_response(template_name, # {'form': form, 'section': 'new'}, # context_instance=RequestContext(request)) . Output only the next line.
fortune_vote,
Continue the code snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<page>\d)?$', fortune_list, name='fortune_index_type'), url(r'^new$', <|code_end|> . Use current file imports: from django.conf.urls.defaults import * from django.conf import settings from django_fortunes.feeds import LatestFortunes, LatestFortunesByAuthor from django_fortunes.views import fortune_list, fortune_detail, \ fortune_vote, fortune_new and context (classes, functions, or code) from other files: # Path: django_fortunes/feeds.py # class LatestFortunes(FortuneFeed): # title = "Latest fortunes" # description = "Latest fortunes added." # # def items(self): # return self.manager.latest() # # def link(self, obj): # return reverse('fortune_index_type', kwargs={'order_type': 'latest'}) # # class LatestFortunesByAuthor(FortuneFeed): # def get_object(self, request, username): # ''' Retrieve simple param in url, waiting for authenticated user ''' # return get_object_or_404(User, username=username) # # def title(self, obj): # return "Latest fortunes by %s" % obj # # def link(self, obj): # if not obj: # raise FeedDoesNotExist # return reverse('fortune_index_author', kwargs={'author': obj}) # # def description(self, obj): # return "Latest fortunes added by %s." % obj # # def items(self, obj): # return obj.fortune_set.all()[:getattr(settings, 'FORTUNES_MAX_PER_PAGE', 5)] # # Path: django_fortunes/views.py # def fortune_list(request, order_type='latest', author=None, template_name='index.html', # template_object_name='fortune', **kwargs): # ''' # Lists Fortunes # ''' # # extra = {} # # # Filtering # if author: # queryset = Fortune.objects.latest_by_author(author) # extra['author'] = author # else: # queryset = Fortune.objects.latest() # # # Ordering # if order_type == 'top': # queryset = queryset.order_by('-votes') # elif order_type == 'worst': # queryset = queryset.order_by('votes') # else: # # latest # queryset = queryset.order_by('-pub_date') # # extra['order_type'] = order_type # # return list_detail.object_list( # request, # queryset = queryset, # paginate_by = getattr(settings, 'FORTUNES_MAX_PER_PAGE', 3), # template_name = template_name, # template_object_name = template_object_name, # extra_context = extra, # **kwargs # ) # # def fortune_detail(request, year, month, day, slug, # template_name='detail.html', template_object_name='fortune', # **kwargs): # ''' # Display one fortune, and provides a comment form wich will # be handled and persisted if request is POST # ''' # return date_based.object_detail( # request, # year = year, # month = month, # day = day, # date_field = 'pub_date', # slug = slug, # queryset = Fortune.objects.published(), # month_format = '%m', # template_object_name = template_object_name, # template_name = template_name, # **kwargs # ) # # def fortune_vote(request, object_pk, direction): # ''' # Votes up or down a fortune # ''' # fortune = get_object_or_404(Fortune, pk=object_pk) # fortune.votes += 1 if direction == 'up' else -1 # fortune.save() # # return redirect(fortune) # # @login_required # def fortune_new(request, template_name='new.html'): # ''' # Provides a Fortune creation form, validates the form if values posted # and saves a new Fortune in the database if everything's okay # ''' # if request.method == 'POST': # form = PublicFortuneForm(request.POST) # if form.is_valid(): # fortune = form.save(commit=False) # fortune.author = request.user # fortune.save() # return redirect(fortune) # else: # form = PublicFortuneForm() # return render_to_response(template_name, # {'form': form, 'section': 'new'}, # context_instance=RequestContext(request)) . Output only the next line.
fortune_new,
Using the snippet: <|code_start|> # Based on snippets from: https://code.djangoproject.com/ticket/10899 self.client.cookies[settings.SESSION_COOKIE_NAME] = 'fake' session = self.client.session session['deleted_email'] = 'test@domain.net' session.save() self.client.cookies[settings.SESSION_COOKIE_NAME] = session.session_key def test_template_used(self): self._setup_session() resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'feedback/create.html') def test_feedback_creation(self): self._setup_session() data = { 'question_1': 'on', 'question_2': 'on', 'question_3': '', 'question_4': 'on', 'question_5': '', 'comments': 'A nice comment', } next_url = reverse('feedback:create') resp = self.client.post('{}?next={}'.format(self.url, next_url), data) self.assertRedirects(resp, next_url) <|code_end|> , determine the next line of code. You have imports: from django.conf import settings from django.core.urlresolvers import reverse from django.test import TestCase from ..models import Feedback and context (class names, function names, or code) available: # Path: brasilcomvc/feedback/models.py # class Feedback(models.Model): # # email = models.EmailField() # question_1 = models.BooleanField(QUESTIONS[0], default=False) # question_2 = models.BooleanField(QUESTIONS[1], default=False) # question_3 = models.BooleanField(QUESTIONS[2], default=False) # question_4 = models.BooleanField(QUESTIONS[3], default=False) # question_5 = models.BooleanField(QUESTIONS[4], default=False) # comments = models.TextField(default='') # # created = models.DateTimeField(auto_now_add=True) # updated = models.DateTimeField(auto_now=True) # # comments.verbose_name = 'comentários' # # def __str__(self): # return '{} - {}'.format(self.email, self.created) # # def __unicode__(self): # return '{} - {}'.format(self.email, self.created) . Output only the next line.
self.assertEqual(Feedback.objects.count(), 1)
Predict the next line for this snippet: <|code_start|> User = get_user_model() class RequiresLogin(LoginRequiredMixin, View): def get(self, *args, **kwargs): return HttpResponse('OK') <|code_end|> with the help of current file imports: from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from django.http import HttpResponse from django.test import RequestFactory, TestCase from django.views.generic import View from ..views import AnonymousRequiredMixin, LoginRequiredMixin and context from other files: # Path: brasilcomvc/common/views.py # class AnonymousRequiredMixin(object): # # ''' # Make any view be accessible by unauthenticated users only # ''' # # def dispatch(self, request, *args, **kwargs): # if request.user.is_authenticated(): # return redirect(settings.LOGIN_REDIRECT_URL) # return super(AnonymousRequiredMixin, self).dispatch( # request, *args, **kwargs) # # class LoginRequiredMixin(object): # # ''' # Bind login requirement to any view # ''' # # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) , which may contain function names, class names, or code. Output only the next line.
class RequiresAnonymous(AnonymousRequiredMixin, View):
Given the following code snippet before the placeholder: <|code_start|> class UserManagerTestCase(TestCase): _user_data = { 'email': 'test@example.com', 'password': '123', 'full_name': 'Test User', } def test_create_user(self): data = self._user_data.copy() <|code_end|> , predict the next line using imports from the current file: from django.test import TestCase from ..models import User, user_picture_upload_to and context including class names, function names, and sometimes code from other files: # Path: brasilcomvc/accounts/models.py # class User(AbstractBaseUser, PermissionsMixin): # # # Personal Info # email = models.EmailField(unique=True) # full_name = models.CharField('Nome Completo', max_length=255) # username = models.SlugField(max_length=30, null=True, blank=True) # picture = ProcessedImageField( # null=True, blank=True, # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(256, 256)], # upload_to=user_picture_upload_to) # picture_medium = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(128, 128)], # source='picture') # picture_small = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(50, 50)], # source='picture') # # # Professional Info # job_title = models.CharField(max_length=80, null=True, blank=True) # bio = models.TextField(null=True, blank=True) # # # Status # date_joined = models.DateTimeField(auto_now_add=True) # date_updated = models.DateTimeField(auto_now=True) # is_active = models.BooleanField(editable=False, default=True) # is_staff = models.BooleanField(editable=False, default=False) # # # Notifications # email_newsletter = models.BooleanField(default=True) # # # Verbose names # email.verbose_name = 'e-mail' # full_name.verbose_name = 'nome completo' # username.verbose_name = 'nome de usuário' # picture.verbose_name = 'foto do usuário' # job_title.verbose_name = 'profissão' # bio.verbose_name = 'biografia' # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ('full_name',) # # objects = UserManager() # # class Meta: # verbose_name = 'usuário' # # def get_short_name(self): # return self.full_name.split()[0] if self.full_name else '' # # def get_full_name(self): # return self.full_name # # def send_welcome_email(self): # send_template_email( # subject='Bem vindo!', # to=self.email, # template_name='emails/welcome.html', # context={'user': self}) # # def user_picture_upload_to(instance, filename): # return 'users/{}/picture.jpg'.format(instance.pk) . Output only the next line.
self.assertFalse(User.objects.exists())
Predict the next line for this snippet: <|code_start|> User.objects.create_user(**data) raw_pwd = data.pop('password') self.assertTrue(User.objects.filter(**data).exists()) user = User.objects.all()[0] self.assertTrue(user.check_password(raw_pwd)) def test_create_superuser(self): User.objects.create_superuser(**self._user_data) user = User.objects.all()[0] self.assertTrue(user.is_staff) self.assertTrue(user.is_superuser) class UserTestCase(TestCase): def test_short_name_with_long_name(self): user = User(full_name='Homer J. Simpson') self.assertEqual(user.get_short_name(), 'Homer') def test_short_name_with_single_name(self): user = User(full_name='Beavis') self.assertEqual(user.get_short_name(), 'Beavis') def test_short_name_with_no_name(self): user = User(full_name='') self.assertEqual(user.get_short_name(), '') def test_user_picture_upload_to(self): user = User.objects.create(email='user@example.com') expected = 'users/{}/picture.jpg'.format(user.id) <|code_end|> with the help of current file imports: from django.test import TestCase from ..models import User, user_picture_upload_to and context from other files: # Path: brasilcomvc/accounts/models.py # class User(AbstractBaseUser, PermissionsMixin): # # # Personal Info # email = models.EmailField(unique=True) # full_name = models.CharField('Nome Completo', max_length=255) # username = models.SlugField(max_length=30, null=True, blank=True) # picture = ProcessedImageField( # null=True, blank=True, # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(256, 256)], # upload_to=user_picture_upload_to) # picture_medium = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(128, 128)], # source='picture') # picture_small = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(50, 50)], # source='picture') # # # Professional Info # job_title = models.CharField(max_length=80, null=True, blank=True) # bio = models.TextField(null=True, blank=True) # # # Status # date_joined = models.DateTimeField(auto_now_add=True) # date_updated = models.DateTimeField(auto_now=True) # is_active = models.BooleanField(editable=False, default=True) # is_staff = models.BooleanField(editable=False, default=False) # # # Notifications # email_newsletter = models.BooleanField(default=True) # # # Verbose names # email.verbose_name = 'e-mail' # full_name.verbose_name = 'nome completo' # username.verbose_name = 'nome de usuário' # picture.verbose_name = 'foto do usuário' # job_title.verbose_name = 'profissão' # bio.verbose_name = 'biografia' # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ('full_name',) # # objects = UserManager() # # class Meta: # verbose_name = 'usuário' # # def get_short_name(self): # return self.full_name.split()[0] if self.full_name else '' # # def get_full_name(self): # return self.full_name # # def send_welcome_email(self): # send_template_email( # subject='Bem vindo!', # to=self.email, # template_name='emails/welcome.html', # context={'user': self}) # # def user_picture_upload_to(instance, filename): # return 'users/{}/picture.jpg'.format(instance.pk) , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(user_picture_upload_to(user, 'wat.png'), expected)
Continue the code snippet: <|code_start|> urlpatterns = ( # Project Search url(r'^busca/$', ProjectSearch.as_view(), name='project_search'), # Project List url(r'^$', ProjectList.as_view(), name='project_list'), # Project Details url(r'^(?P<slug>[\w-]+)/$', ProjectDetails.as_view(), name='project_details'), # Project Apply url(r'^(?P<slug>[\w-]+)/apply$', <|code_end|> . Use current file imports: from django.conf.urls import url from .views import ( ProjectApply, ProjectDetails, ProjectList, ProjectSearch, ) and context (classes, functions, or code) from other files: # Path: brasilcomvc/projects/views.py # class ProjectApply(LoginRequiredMixin, CreateView): # # form_class = ProjectApplyForm # template_name = 'projects/project_apply.html' # # def get_project(self): # return get_object_or_404(Project, slug=self.kwargs['slug']) # # def get_form_kwargs(self): # return dict( # super(ProjectApply, self).get_form_kwargs(), # volunteer=self.request.user, # project=self.get_project()) # # def get_success_url(self): # return self.get_project().get_absolute_url() # # def form_valid(self, form): # application = form.save(commit=False) # application.project = form.project # application.volunteer = form.volunteer # application.save() # # # Send emails to the involved parts # application.send_owner_email() # application.send_volunteer_email() # # # Display a message # messages.success( # self.request, # 'Inscrição realizada com sucesso! Você agora está participando ' # 'deste projeto.') # # return super(ProjectApply, self).form_valid(form) # # def get_context_data(self, **kwargs): # return dict( # super(ProjectApply, self).get_context_data(**kwargs), # project=self.get_project()) # # class ProjectDetails(DetailView): # # model = Project # template_name = 'projects/project_details.html' # # def get_context_data(self, **kwargs): # user = self.request.user # # return dict( # super(ProjectDetails, self).get_context_data(**kwargs), # user_is_participating=( # user.is_authenticated() and # self.object.applications.filter(volunteer=user).exists())) # # class ProjectList(ListView): # # template_name = 'projects/project_list.html' # # def get_queryset(self): # return Project.objects.order_by('?').annotate( # application_count=Count('applications')) # # def get_context_data(self, **kwargs): # return dict( # super(ProjectList, self).get_context_data(**kwargs), # banner=(HomeBanner.objects.order_by('?')[:1] or (None,))[0]) # # class ProjectSearch(ListView): # # context_object_name = 'projects' # form_class = ProjectSearchForm # template_name = 'projects/project_search.html' # # def get(self, request, *args, **kwargs): # self.form = ProjectSearchForm(request.GET) # return super(ListView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(ProjectSearch, self).get_context_data(**kwargs) # context['form'] = self.form # return context # # def get_queryset(self): # projects = Project.objects.none() # # if self.form.is_valid(): # # Filter by distance # lat = self.form.cleaned_data['lat'] # lng = self.form.cleaned_data['lng'] # radius = self.form.cleaned_data['radius'] or 30 # # user_location = Point(x=lng, y=lat, srid=4326) # projects = Project.objects.filter( # latlng__distance_lte=(user_location, D(km=radius))) # # return projects . Output only the next line.
ProjectApply.as_view(), name='project_apply'),
Predict the next line for this snippet: <|code_start|> urlpatterns = ( # Project Search url(r'^busca/$', ProjectSearch.as_view(), name='project_search'), # Project List url(r'^$', ProjectList.as_view(), name='project_list'), # Project Details url(r'^(?P<slug>[\w-]+)/$', <|code_end|> with the help of current file imports: from django.conf.urls import url from .views import ( ProjectApply, ProjectDetails, ProjectList, ProjectSearch, ) and context from other files: # Path: brasilcomvc/projects/views.py # class ProjectApply(LoginRequiredMixin, CreateView): # # form_class = ProjectApplyForm # template_name = 'projects/project_apply.html' # # def get_project(self): # return get_object_or_404(Project, slug=self.kwargs['slug']) # # def get_form_kwargs(self): # return dict( # super(ProjectApply, self).get_form_kwargs(), # volunteer=self.request.user, # project=self.get_project()) # # def get_success_url(self): # return self.get_project().get_absolute_url() # # def form_valid(self, form): # application = form.save(commit=False) # application.project = form.project # application.volunteer = form.volunteer # application.save() # # # Send emails to the involved parts # application.send_owner_email() # application.send_volunteer_email() # # # Display a message # messages.success( # self.request, # 'Inscrição realizada com sucesso! Você agora está participando ' # 'deste projeto.') # # return super(ProjectApply, self).form_valid(form) # # def get_context_data(self, **kwargs): # return dict( # super(ProjectApply, self).get_context_data(**kwargs), # project=self.get_project()) # # class ProjectDetails(DetailView): # # model = Project # template_name = 'projects/project_details.html' # # def get_context_data(self, **kwargs): # user = self.request.user # # return dict( # super(ProjectDetails, self).get_context_data(**kwargs), # user_is_participating=( # user.is_authenticated() and # self.object.applications.filter(volunteer=user).exists())) # # class ProjectList(ListView): # # template_name = 'projects/project_list.html' # # def get_queryset(self): # return Project.objects.order_by('?').annotate( # application_count=Count('applications')) # # def get_context_data(self, **kwargs): # return dict( # super(ProjectList, self).get_context_data(**kwargs), # banner=(HomeBanner.objects.order_by('?')[:1] or (None,))[0]) # # class ProjectSearch(ListView): # # context_object_name = 'projects' # form_class = ProjectSearchForm # template_name = 'projects/project_search.html' # # def get(self, request, *args, **kwargs): # self.form = ProjectSearchForm(request.GET) # return super(ListView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(ProjectSearch, self).get_context_data(**kwargs) # context['form'] = self.form # return context # # def get_queryset(self): # projects = Project.objects.none() # # if self.form.is_valid(): # # Filter by distance # lat = self.form.cleaned_data['lat'] # lng = self.form.cleaned_data['lng'] # radius = self.form.cleaned_data['radius'] or 30 # # user_location = Point(x=lng, y=lat, srid=4326) # projects = Project.objects.filter( # latlng__distance_lte=(user_location, D(km=radius))) # # return projects , which may contain function names, class names, or code. Output only the next line.
ProjectDetails.as_view(), name='project_details'),
Using the snippet: <|code_start|> urlpatterns = ( # Project Search url(r'^busca/$', ProjectSearch.as_view(), name='project_search'), # Project List url(r'^$', <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import url from .views import ( ProjectApply, ProjectDetails, ProjectList, ProjectSearch, ) and context (class names, function names, or code) available: # Path: brasilcomvc/projects/views.py # class ProjectApply(LoginRequiredMixin, CreateView): # # form_class = ProjectApplyForm # template_name = 'projects/project_apply.html' # # def get_project(self): # return get_object_or_404(Project, slug=self.kwargs['slug']) # # def get_form_kwargs(self): # return dict( # super(ProjectApply, self).get_form_kwargs(), # volunteer=self.request.user, # project=self.get_project()) # # def get_success_url(self): # return self.get_project().get_absolute_url() # # def form_valid(self, form): # application = form.save(commit=False) # application.project = form.project # application.volunteer = form.volunteer # application.save() # # # Send emails to the involved parts # application.send_owner_email() # application.send_volunteer_email() # # # Display a message # messages.success( # self.request, # 'Inscrição realizada com sucesso! Você agora está participando ' # 'deste projeto.') # # return super(ProjectApply, self).form_valid(form) # # def get_context_data(self, **kwargs): # return dict( # super(ProjectApply, self).get_context_data(**kwargs), # project=self.get_project()) # # class ProjectDetails(DetailView): # # model = Project # template_name = 'projects/project_details.html' # # def get_context_data(self, **kwargs): # user = self.request.user # # return dict( # super(ProjectDetails, self).get_context_data(**kwargs), # user_is_participating=( # user.is_authenticated() and # self.object.applications.filter(volunteer=user).exists())) # # class ProjectList(ListView): # # template_name = 'projects/project_list.html' # # def get_queryset(self): # return Project.objects.order_by('?').annotate( # application_count=Count('applications')) # # def get_context_data(self, **kwargs): # return dict( # super(ProjectList, self).get_context_data(**kwargs), # banner=(HomeBanner.objects.order_by('?')[:1] or (None,))[0]) # # class ProjectSearch(ListView): # # context_object_name = 'projects' # form_class = ProjectSearchForm # template_name = 'projects/project_search.html' # # def get(self, request, *args, **kwargs): # self.form = ProjectSearchForm(request.GET) # return super(ListView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(ProjectSearch, self).get_context_data(**kwargs) # context['form'] = self.form # return context # # def get_queryset(self): # projects = Project.objects.none() # # if self.form.is_valid(): # # Filter by distance # lat = self.form.cleaned_data['lat'] # lng = self.form.cleaned_data['lng'] # radius = self.form.cleaned_data['radius'] or 30 # # user_location = Point(x=lng, y=lat, srid=4326) # projects = Project.objects.filter( # latlng__distance_lte=(user_location, D(km=radius))) # # return projects . Output only the next line.
ProjectList.as_view(), name='project_list'),
Continue the code snippet: <|code_start|> url(r'^cadastro/$', Signup.as_view(), name='signup'), # Edit Dashboard url(r'^editar/$', RedirectView.as_view(pattern_name='accounts:edit_personal_info'), name='edit_dashboard'), # Edit Personal Info url(r'^editar/info-pessoal/$', EditPersonalInfo.as_view(), name='edit_personal_info'), # Edit Professional Info url(r'^editar/profissional/$', EditProfessionalInfo.as_view(), name='edit_professional_info'), # Edit Notifications url(r'^editar/notificacoes/$', EditNotifications.as_view(), name='edit_notifications'), # Edit Security Settings url(r'^editar/seguranca/$', EditSecuritySettings.as_view(), name='edit_security_settings'), # Edit User Address url(r'^editar/endereco/$', EditUserAddress.as_view(), name='edit_user_address'), # User Delete url(r'^remover-conta/$', <|code_end|> . Use current file imports: from django.conf.urls import url from django.views.generic import RedirectView from .views import ( DeleteUser, login, logout, password_reset, password_reset_confirm, password_reset_sent, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and context (classes, functions, or code) from other files: # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # def login(request, *args, **kwargs): # if request.user and request.user.is_authenticated(): # return HttpResponseRedirect(reverse('accounts:edit_dashboard')) # return auth_login( # request, # authentication_form=LoginForm, # template_name='accounts/login.html', # ) # # def logout(request): # """ # Logout user and redirect back to login page # """ # logout_user(request) # return HttpResponseRedirect(reverse('accounts:login')) # # def password_reset(request): # return django_password_reset( # request, # template_name='accounts/password_reset.html', # password_reset_form=PasswordResetForm, # post_reset_redirect=reverse('accounts:password_reset_sent')) # # def password_reset_confirm(request, **kwargs): # return django_password_reset_confirm( # request, # template_name='accounts/password_reset_confirm.html', # post_reset_redirect=reverse('accounts:login'), # **kwargs) # # def password_reset_sent(request): # return django_password_reset_done( # request, # template_name='accounts/password_reset_sent.html') # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response . Output only the next line.
DeleteUser.as_view(), name='delete_user'),
Here is a snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url from django.views.generic import RedirectView from .views import ( DeleteUser, login, logout, password_reset, password_reset_confirm, password_reset_sent, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and context from other files: # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # def login(request, *args, **kwargs): # if request.user and request.user.is_authenticated(): # return HttpResponseRedirect(reverse('accounts:edit_dashboard')) # return auth_login( # request, # authentication_form=LoginForm, # template_name='accounts/login.html', # ) # # def logout(request): # """ # Logout user and redirect back to login page # """ # logout_user(request) # return HttpResponseRedirect(reverse('accounts:login')) # # def password_reset(request): # return django_password_reset( # request, # template_name='accounts/password_reset.html', # password_reset_form=PasswordResetForm, # post_reset_redirect=reverse('accounts:password_reset_sent')) # # def password_reset_confirm(request, **kwargs): # return django_password_reset_confirm( # request, # template_name='accounts/password_reset_confirm.html', # post_reset_redirect=reverse('accounts:login'), # **kwargs) # # def password_reset_sent(request): # return django_password_reset_done( # request, # template_name='accounts/password_reset_sent.html') # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response , which may include functions, classes, or code. Output only the next line.
logout, name='logout'),
Predict the next line after this snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', <|code_end|> using the current file's imports: from django.conf.urls import url from django.views.generic import RedirectView from .views import ( DeleteUser, login, logout, password_reset, password_reset_confirm, password_reset_sent, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and any relevant context from other files: # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # def login(request, *args, **kwargs): # if request.user and request.user.is_authenticated(): # return HttpResponseRedirect(reverse('accounts:edit_dashboard')) # return auth_login( # request, # authentication_form=LoginForm, # template_name='accounts/login.html', # ) # # def logout(request): # """ # Logout user and redirect back to login page # """ # logout_user(request) # return HttpResponseRedirect(reverse('accounts:login')) # # def password_reset(request): # return django_password_reset( # request, # template_name='accounts/password_reset.html', # password_reset_form=PasswordResetForm, # post_reset_redirect=reverse('accounts:password_reset_sent')) # # def password_reset_confirm(request, **kwargs): # return django_password_reset_confirm( # request, # template_name='accounts/password_reset_confirm.html', # post_reset_redirect=reverse('accounts:login'), # **kwargs) # # def password_reset_sent(request): # return django_password_reset_done( # request, # template_name='accounts/password_reset_sent.html') # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response . Output only the next line.
password_reset, name='password_reset'),
Predict the next line after this snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), # Password Reset Sent url(r'^esqueci-senha/enviado$', password_reset_sent, name='password_reset_sent'), # Password Reset Confirm url(r'^esqueci-senha/redefinir/(?P<uidb64>[^-]+)-(?P<token>[^$]+)$', <|code_end|> using the current file's imports: from django.conf.urls import url from django.views.generic import RedirectView from .views import ( DeleteUser, login, logout, password_reset, password_reset_confirm, password_reset_sent, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and any relevant context from other files: # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # def login(request, *args, **kwargs): # if request.user and request.user.is_authenticated(): # return HttpResponseRedirect(reverse('accounts:edit_dashboard')) # return auth_login( # request, # authentication_form=LoginForm, # template_name='accounts/login.html', # ) # # def logout(request): # """ # Logout user and redirect back to login page # """ # logout_user(request) # return HttpResponseRedirect(reverse('accounts:login')) # # def password_reset(request): # return django_password_reset( # request, # template_name='accounts/password_reset.html', # password_reset_form=PasswordResetForm, # post_reset_redirect=reverse('accounts:password_reset_sent')) # # def password_reset_confirm(request, **kwargs): # return django_password_reset_confirm( # request, # template_name='accounts/password_reset_confirm.html', # post_reset_redirect=reverse('accounts:login'), # **kwargs) # # def password_reset_sent(request): # return django_password_reset_done( # request, # template_name='accounts/password_reset_sent.html') # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response . Output only the next line.
password_reset_confirm, name='password_reset_confirm'),
Using the snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), # Password Reset Sent url(r'^esqueci-senha/enviado$', <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import url from django.views.generic import RedirectView from .views import ( DeleteUser, login, logout, password_reset, password_reset_confirm, password_reset_sent, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and context (class names, function names, or code) available: # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # def login(request, *args, **kwargs): # if request.user and request.user.is_authenticated(): # return HttpResponseRedirect(reverse('accounts:edit_dashboard')) # return auth_login( # request, # authentication_form=LoginForm, # template_name='accounts/login.html', # ) # # def logout(request): # """ # Logout user and redirect back to login page # """ # logout_user(request) # return HttpResponseRedirect(reverse('accounts:login')) # # def password_reset(request): # return django_password_reset( # request, # template_name='accounts/password_reset.html', # password_reset_form=PasswordResetForm, # post_reset_redirect=reverse('accounts:password_reset_sent')) # # def password_reset_confirm(request, **kwargs): # return django_password_reset_confirm( # request, # template_name='accounts/password_reset_confirm.html', # post_reset_redirect=reverse('accounts:login'), # **kwargs) # # def password_reset_sent(request): # return django_password_reset_done( # request, # template_name='accounts/password_reset_sent.html') # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response . Output only the next line.
password_reset_sent, name='password_reset_sent'),
Using the snippet: <|code_start|> url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), # Password Reset Sent url(r'^esqueci-senha/enviado$', password_reset_sent, name='password_reset_sent'), # Password Reset Confirm url(r'^esqueci-senha/redefinir/(?P<uidb64>[^-]+)-(?P<token>[^$]+)$', password_reset_confirm, name='password_reset_confirm'), # User Signup url(r'^cadastro/$', Signup.as_view(), name='signup'), # Edit Dashboard url(r'^editar/$', RedirectView.as_view(pattern_name='accounts:edit_personal_info'), name='edit_dashboard'), # Edit Personal Info url(r'^editar/info-pessoal/$', <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import url from django.views.generic import RedirectView from .views import ( DeleteUser, login, logout, password_reset, password_reset_confirm, password_reset_sent, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and context (class names, function names, or code) available: # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # def login(request, *args, **kwargs): # if request.user and request.user.is_authenticated(): # return HttpResponseRedirect(reverse('accounts:edit_dashboard')) # return auth_login( # request, # authentication_form=LoginForm, # template_name='accounts/login.html', # ) # # def logout(request): # """ # Logout user and redirect back to login page # """ # logout_user(request) # return HttpResponseRedirect(reverse('accounts:login')) # # def password_reset(request): # return django_password_reset( # request, # template_name='accounts/password_reset.html', # password_reset_form=PasswordResetForm, # post_reset_redirect=reverse('accounts:password_reset_sent')) # # def password_reset_confirm(request, **kwargs): # return django_password_reset_confirm( # request, # template_name='accounts/password_reset_confirm.html', # post_reset_redirect=reverse('accounts:login'), # **kwargs) # # def password_reset_sent(request): # return django_password_reset_done( # request, # template_name='accounts/password_reset_sent.html') # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response . Output only the next line.
EditPersonalInfo.as_view(), name='edit_personal_info'),
Predict the next line for this snippet: <|code_start|> url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), # Password Reset Sent url(r'^esqueci-senha/enviado$', password_reset_sent, name='password_reset_sent'), # Password Reset Confirm url(r'^esqueci-senha/redefinir/(?P<uidb64>[^-]+)-(?P<token>[^$]+)$', password_reset_confirm, name='password_reset_confirm'), # User Signup url(r'^cadastro/$', Signup.as_view(), name='signup'), # Edit Dashboard url(r'^editar/$', RedirectView.as_view(pattern_name='accounts:edit_personal_info'), name='edit_dashboard'), # Edit Personal Info url(r'^editar/info-pessoal/$', EditPersonalInfo.as_view(), name='edit_personal_info'), # Edit Professional Info url(r'^editar/profissional/$', <|code_end|> with the help of current file imports: from django.conf.urls import url from django.views.generic import RedirectView from .views import ( DeleteUser, login, logout, password_reset, password_reset_confirm, password_reset_sent, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and context from other files: # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # def login(request, *args, **kwargs): # if request.user and request.user.is_authenticated(): # return HttpResponseRedirect(reverse('accounts:edit_dashboard')) # return auth_login( # request, # authentication_form=LoginForm, # template_name='accounts/login.html', # ) # # def logout(request): # """ # Logout user and redirect back to login page # """ # logout_user(request) # return HttpResponseRedirect(reverse('accounts:login')) # # def password_reset(request): # return django_password_reset( # request, # template_name='accounts/password_reset.html', # password_reset_form=PasswordResetForm, # post_reset_redirect=reverse('accounts:password_reset_sent')) # # def password_reset_confirm(request, **kwargs): # return django_password_reset_confirm( # request, # template_name='accounts/password_reset_confirm.html', # post_reset_redirect=reverse('accounts:login'), # **kwargs) # # def password_reset_sent(request): # return django_password_reset_done( # request, # template_name='accounts/password_reset_sent.html') # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response , which may contain function names, class names, or code. Output only the next line.
EditProfessionalInfo.as_view(), name='edit_professional_info'),
Predict the next line after this snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), # Password Reset Sent url(r'^esqueci-senha/enviado$', password_reset_sent, name='password_reset_sent'), # Password Reset Confirm url(r'^esqueci-senha/redefinir/(?P<uidb64>[^-]+)-(?P<token>[^$]+)$', password_reset_confirm, name='password_reset_confirm'), # User Signup url(r'^cadastro/$', <|code_end|> using the current file's imports: from django.conf.urls import url from django.views.generic import RedirectView from .views import ( DeleteUser, login, logout, password_reset, password_reset_confirm, password_reset_sent, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and any relevant context from other files: # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # def login(request, *args, **kwargs): # if request.user and request.user.is_authenticated(): # return HttpResponseRedirect(reverse('accounts:edit_dashboard')) # return auth_login( # request, # authentication_form=LoginForm, # template_name='accounts/login.html', # ) # # def logout(request): # """ # Logout user and redirect back to login page # """ # logout_user(request) # return HttpResponseRedirect(reverse('accounts:login')) # # def password_reset(request): # return django_password_reset( # request, # template_name='accounts/password_reset.html', # password_reset_form=PasswordResetForm, # post_reset_redirect=reverse('accounts:password_reset_sent')) # # def password_reset_confirm(request, **kwargs): # return django_password_reset_confirm( # request, # template_name='accounts/password_reset_confirm.html', # post_reset_redirect=reverse('accounts:login'), # **kwargs) # # def password_reset_sent(request): # return django_password_reset_done( # request, # template_name='accounts/password_reset_sent.html') # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response . Output only the next line.
Signup.as_view(), name='signup'),
Given snippet: <|code_start|># coding: utf8 from __future__ import unicode_literals User = get_user_model() class ProjectTestCase(TestCase): def _mock_pygeocoder_request(self, plain_json): responses.add( responses.GET, re.compile(Geocoder.GEOCODE_QUERY_URL), body=json.dumps(plain_json), content_type='application/json', status=200) def test_project_slug_gets_generated_correctly(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import json import re import responses from django.core.exceptions import ValidationError from django.test import TestCase from django.contrib.auth import get_user_model from pygeocoder import Geocoder, GeocoderError from ..models import Project, project_img_upload_to and context: # Path: brasilcomvc/projects/models.py # class Project(models.Model): # # owner = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name='projects_owned') # name = models.CharField(max_length=60) # slug = models.SlugField(editable=False) # relevant_fact = models.TextField(null=True, blank=True) # about = models.TextField() # short_description = models.TextField(null=True, blank=True) # how_to_help = models.TextField() # requirements = models.TextField(blank=True) # tags = models.ManyToManyField('Tag', blank=True) # agenda = models.TextField(default='', blank=True) # address = models.TextField(verbose_name='endereço') # location = models.TextField(verbose_name='local', help_text=( # 'Local ou cidade. E.g. "Teatro Municipal" ou "São Paulo, SP".')) # latlng = models.PointField( # null=True, srid=4326, db_index=True, editable=False) # # img = ProcessedImageField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(854, 480)], # upload_to=project_img_upload_to) # img_thumbnail = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(320, 240)], # source='img') # img_opengraph = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(800, 420)], # source='img') # video = models.URLField(null=True, blank=True) # # name.verbose_name = 'nome' # relevant_fact.verbose_name = 'fato relevante' # about.verbose_name = 'descrição' # short_description.verbose_name = 'descrição curta' # how_to_help.verbose_name = 'como ajudar' # requirements.verbose_name = 'requisitos' # video.verbose_name = 'vídeo' # # class Meta: # verbose_name = 'Projeto' # verbose_name_plural = 'Projetos' # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('projects:project_details', kwargs={'slug': self.slug}) # # def clean(self): # # Use Google Maps API to geocode `address` into `latlng` # try: # addr = Geocoder.geocode(' '.join(self.address.splitlines()))[0] # self.latlng = Point(y=addr.latitude, x=addr.longitude, srid=4326) # # except GeocoderError as err: # if err.status != GeocoderError.G_GEO_ZERO_RESULTS: # raise # raise ValidationError('Endereço não reconhecido no Google Maps.') # # def save(self, **kwargs): # if self.pk is None: # self.slug = slugify(smart_text(self.name)) # super(Project, self).save(**kwargs) # # def project_img_upload_to(instance, filename): # return 'projects/{}/img.jpeg'.format(instance.slug) which might include code, classes, or functions. Output only the next line.
project = Project(
Using the snippet: <|code_start|> User = get_user_model() class ProjectTestCase(TestCase): def _mock_pygeocoder_request(self, plain_json): responses.add( responses.GET, re.compile(Geocoder.GEOCODE_QUERY_URL), body=json.dumps(plain_json), content_type='application/json', status=200) def test_project_slug_gets_generated_correctly(self): project = Project( owner=User.objects.create_user('test@example.com', '123'), name='This is a Test Project') project.save() self.assertEqual(project.slug, 'this-is-a-test-project') old_slug = project.slug project.name = 'Some New Name' project.save() self.assertEqual(project.slug, old_slug) def test_project_img_upload_to(self): project = Project(slug='wat-is-a-slug') filename = 'wat.png' expected = 'projects/wat-is-a-slug/img.jpeg' <|code_end|> , determine the next line of code. You have imports: import json import re import responses from django.core.exceptions import ValidationError from django.test import TestCase from django.contrib.auth import get_user_model from pygeocoder import Geocoder, GeocoderError from ..models import Project, project_img_upload_to and context (class names, function names, or code) available: # Path: brasilcomvc/projects/models.py # class Project(models.Model): # # owner = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name='projects_owned') # name = models.CharField(max_length=60) # slug = models.SlugField(editable=False) # relevant_fact = models.TextField(null=True, blank=True) # about = models.TextField() # short_description = models.TextField(null=True, blank=True) # how_to_help = models.TextField() # requirements = models.TextField(blank=True) # tags = models.ManyToManyField('Tag', blank=True) # agenda = models.TextField(default='', blank=True) # address = models.TextField(verbose_name='endereço') # location = models.TextField(verbose_name='local', help_text=( # 'Local ou cidade. E.g. "Teatro Municipal" ou "São Paulo, SP".')) # latlng = models.PointField( # null=True, srid=4326, db_index=True, editable=False) # # img = ProcessedImageField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(854, 480)], # upload_to=project_img_upload_to) # img_thumbnail = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(320, 240)], # source='img') # img_opengraph = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(800, 420)], # source='img') # video = models.URLField(null=True, blank=True) # # name.verbose_name = 'nome' # relevant_fact.verbose_name = 'fato relevante' # about.verbose_name = 'descrição' # short_description.verbose_name = 'descrição curta' # how_to_help.verbose_name = 'como ajudar' # requirements.verbose_name = 'requisitos' # video.verbose_name = 'vídeo' # # class Meta: # verbose_name = 'Projeto' # verbose_name_plural = 'Projetos' # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('projects:project_details', kwargs={'slug': self.slug}) # # def clean(self): # # Use Google Maps API to geocode `address` into `latlng` # try: # addr = Geocoder.geocode(' '.join(self.address.splitlines()))[0] # self.latlng = Point(y=addr.latitude, x=addr.longitude, srid=4326) # # except GeocoderError as err: # if err.status != GeocoderError.G_GEO_ZERO_RESULTS: # raise # raise ValidationError('Endereço não reconhecido no Google Maps.') # # def save(self, **kwargs): # if self.pk is None: # self.slug = slugify(smart_text(self.name)) # super(Project, self).save(**kwargs) # # def project_img_upload_to(instance, filename): # return 'projects/{}/img.jpeg'.format(instance.slug) . Output only the next line.
self.assertEqual(project_img_upload_to(project, filename), expected)
Given the code snippet: <|code_start|> class ServicesAPIKeysTestCase(SimpleTestCase): factory = RequestFactory() @override_settings( FACEBOOK_API_KEY='fb-key', GOOGLE_ANALYTICS_ID='ga-key', GOOGLE_API_KEY='g-key') def test_api_keys(self): context = RequestContext(self.factory.get('/')) self.assertEqual(context.get('FACEBOOK_API_KEY'), 'fb-key') self.assertEqual(context.get('GOOGLE_ANALYTICS_ID'), 'ga-key') self.assertEqual(context.get('GOOGLE_API_KEY'), 'g-key') class BlogURLTestCase(SimpleTestCase): def test_unit(self): with self.settings(BLOG_URL='http://blog'): <|code_end|> , generate the next line using the imports in this file: from django.template import RequestContext from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory from ..context_processors import blog_url, contact_info and context (functions, classes, or occasionally code) from other files: # Path: brasilcomvc/common/context_processors.py # def blog_url(request): # return {'BLOG_URL': settings.BLOG_URL} # # def contact_info(request): # return { # 'CONTACT_EMAIL': settings.CONTACT_EMAIL, # 'CONTACT_PHONE': settings.CONTACT_PHONE, # } . Output only the next line.
ctx = blog_url(None)
Predict the next line after this snippet: <|code_start|> @override_settings( FACEBOOK_API_KEY='fb-key', GOOGLE_ANALYTICS_ID='ga-key', GOOGLE_API_KEY='g-key') def test_api_keys(self): context = RequestContext(self.factory.get('/')) self.assertEqual(context.get('FACEBOOK_API_KEY'), 'fb-key') self.assertEqual(context.get('GOOGLE_ANALYTICS_ID'), 'ga-key') self.assertEqual(context.get('GOOGLE_API_KEY'), 'g-key') class BlogURLTestCase(SimpleTestCase): def test_unit(self): with self.settings(BLOG_URL='http://blog'): ctx = blog_url(None) self.assertIn('BLOG_URL', ctx) self.assertEquals(ctx['BLOG_URL'], 'http://blog') def test_integration(self): with self.settings(BLOG_URL='http://blog'): ctx = RequestContext(RequestFactory().get('/')) self.assertIn('BLOG_URL', ctx) self.assertEquals(ctx['BLOG_URL'], 'http://blog') class ContactInfoTestCase(SimpleTestCase): def test_unit(self): with self.settings(CONTACT_EMAIL='contato@brasil.com.vc', CONTACT_PHONE='551100000000'): <|code_end|> using the current file's imports: from django.template import RequestContext from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory from ..context_processors import blog_url, contact_info and any relevant context from other files: # Path: brasilcomvc/common/context_processors.py # def blog_url(request): # return {'BLOG_URL': settings.BLOG_URL} # # def contact_info(request): # return { # 'CONTACT_EMAIL': settings.CONTACT_EMAIL, # 'CONTACT_PHONE': settings.CONTACT_PHONE, # } . Output only the next line.
ctx = contact_info(None)
Continue the code snippet: <|code_start|>@python_2_unicode_compatible class ProjectApply(models.Model): volunteer = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='applications', editable=False) project = models.ForeignKey( 'Project', related_name='applications', editable=False) message = models.TextField() created = models.DateTimeField(auto_now_add=True) volunteer.verbose_name = 'voluntário' project.verbose_name = 'projeto' message.verbose_name = 'mensagem ao organizador' message.help_text = 'Conte-nos brevemente como você pode ajudar.' created.verbose_name = 'hora do registro' class Meta: unique_together = ('project', 'volunteer',) verbose_name = 'inscrição em projeto' verbose_name_plural = 'inscrições em projetos' def __str__(self): return '{}: {}'.format(self.project.name, self.volunteer.full_name) def _get_email_context(self): return { attr: getattr(self, attr) for attr in ('message', 'project', 'volunteer',)} def send_owner_email(self): <|code_end|> . Use current file imports: from django.conf import settings from django.contrib.gis.db import models from django.contrib.gis.geos import Point from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.utils.encoding import smart_text, python_2_unicode_compatible from django.utils.text import slugify from imagekit.models import ImageSpecField, ProcessedImageField from imagekit.processors import ResizeToFill from pygeocoder import Geocoder, GeocoderError from brasilcomvc.common.email import send_template_email and context (classes, functions, or code) from other files: # Path: brasilcomvc/common/email.py # def send_template_email(subject, to, template_name, context=None): # ''' # Render a template into an email body and send it through Django's send_mail # # - The `to` parameter must be a single email address. # - This function omits `from_email` because it expects it to exist from an # environment variable. # - Other parameters are omitted as well because there are no # use for them in the current use case. # ''' # body = render_to_string(template_name, context or {}, Context({ # 'mailing_address': settings.MAILING_ADDRESS, # 'site_url': settings.BASE_URL, # 'sns_facebook': settings.SNS_FACEBOOK, # 'sns_googleplus': settings.SNS_GOOGLEPLUS, # 'sns_twitter': settings.SNS_TWITTER, # 'subject': subject, # })) # plain_body = strip_tags(body) # # email = EmailMultiAlternatives( # subject=subject, # body=plain_body, # to=(to,)) # email.attach_alternative(body, 'text/html') # email.send() . Output only the next line.
send_template_email(
Given the following code snippet before the placeholder: <|code_start|> self.assertTrue(isinstance(f.fields['username'], EmailField)) class UserAddressFormTestCase(TestCase): fixtures = ['test_cities'] def test_form_should_have_all_fields(self): self.assertEqual(UserAddressForm.Meta.fields, '__all__') def test_form_state_field_should_have_used_regions_only(self): region = Region.objects.order_by('?')[0] City.objects.filter(region=region).delete() self.assertEqual( set(UserAddressForm().fields['state'].queryset), set(Region.objects.exclude(id=region.id))) def test_form_group_cities(self): expected_choices = [ (region.name, list( region.city_set.order_by('name').values_list('pk', 'name')),) for region in Region.objects.order_by('name') ] self.assertEqual(UserAddressForm()._group_cities(), expected_choices) class DeleteUserFormTestCase(TestCase): def test_clean_password_with_valid_password(self): u = User.objects.create_user('wat@wat.net', 'test') <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm from django.forms import EmailField from django.test import TestCase from cities_light.models import City, Region from ..forms import DeleteUserForm, LoginForm, UserAddressForm and context including class names, function names, and sometimes code from other files: # Path: brasilcomvc/accounts/forms.py # class DeleteUserForm(forms.Form): # # password = forms.CharField(label='Senha', widget=forms.PasswordInput) # # def __init__(self, user, *args, **kwargs): # super(DeleteUserForm, self).__init__(*args, **kwargs) # self.user = user # # def clean_password(self): # password = self.cleaned_data['password'] # if not self.user.check_password(password): # self.add_error('password', 'Senha inválida') # return password # # class LoginForm(AuthenticationForm): # # # this is named username so we can use Django's login view # username = forms.EmailField(required=True) # # class UserAddressForm(forms.ModelForm): # # class Meta: # model = UserAddress # fields = '__all__' # # def __init__(self, *args, **kwargs): # super(UserAddressForm, self).__init__(*args, **kwargs) # # # Limit regions to available cities # states = Region.objects.filter( # id__in=set(City.objects.values_list('region_id', flat=True))) # self.fields['state'].queryset = states # self.fields['state'].choices = states.values_list('id', 'name') # # # Group cities by region (state) # self.fields['city'].choices = self._group_cities() # # def _group_cities(self): # ''' # Build a choices-like list with all cities grouped by state (region) # ''' # return [ # (state, [(city.pk, city.name) for city in cities],) # for state, cities in groupby( # self.fields['city'].queryset.order_by('region__name', 'name'), # lambda city: city.region.name)] . Output only the next line.
f = DeleteUserForm(user=u, data={'password': 'test'})
Continue the code snippet: <|code_start|># encoding: utf8 from __future__ import unicode_literals User = get_user_model() class LoginFormTestCase(TestCase): def test_username_authenticationform_subclass(self): <|code_end|> . Use current file imports: from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm from django.forms import EmailField from django.test import TestCase from cities_light.models import City, Region from ..forms import DeleteUserForm, LoginForm, UserAddressForm and context (classes, functions, or code) from other files: # Path: brasilcomvc/accounts/forms.py # class DeleteUserForm(forms.Form): # # password = forms.CharField(label='Senha', widget=forms.PasswordInput) # # def __init__(self, user, *args, **kwargs): # super(DeleteUserForm, self).__init__(*args, **kwargs) # self.user = user # # def clean_password(self): # password = self.cleaned_data['password'] # if not self.user.check_password(password): # self.add_error('password', 'Senha inválida') # return password # # class LoginForm(AuthenticationForm): # # # this is named username so we can use Django's login view # username = forms.EmailField(required=True) # # class UserAddressForm(forms.ModelForm): # # class Meta: # model = UserAddress # fields = '__all__' # # def __init__(self, *args, **kwargs): # super(UserAddressForm, self).__init__(*args, **kwargs) # # # Limit regions to available cities # states = Region.objects.filter( # id__in=set(City.objects.values_list('region_id', flat=True))) # self.fields['state'].queryset = states # self.fields['state'].choices = states.values_list('id', 'name') # # # Group cities by region (state) # self.fields['city'].choices = self._group_cities() # # def _group_cities(self): # ''' # Build a choices-like list with all cities grouped by state (region) # ''' # return [ # (state, [(city.pk, city.name) for city in cities],) # for state, cities in groupby( # self.fields['city'].queryset.order_by('region__name', 'name'), # lambda city: city.region.name)] . Output only the next line.
self.assertTrue(issubclass(LoginForm, AuthenticationForm))
Based on the snippet: <|code_start|># encoding: utf8 from __future__ import unicode_literals User = get_user_model() class LoginFormTestCase(TestCase): def test_username_authenticationform_subclass(self): self.assertTrue(issubclass(LoginForm, AuthenticationForm)) def test_username_field_is_emailfield_instance(self): f = LoginForm() self.assertTrue(isinstance(f.fields['username'], EmailField)) class UserAddressFormTestCase(TestCase): fixtures = ['test_cities'] def test_form_should_have_all_fields(self): <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm from django.forms import EmailField from django.test import TestCase from cities_light.models import City, Region from ..forms import DeleteUserForm, LoginForm, UserAddressForm and context (classes, functions, sometimes code) from other files: # Path: brasilcomvc/accounts/forms.py # class DeleteUserForm(forms.Form): # # password = forms.CharField(label='Senha', widget=forms.PasswordInput) # # def __init__(self, user, *args, **kwargs): # super(DeleteUserForm, self).__init__(*args, **kwargs) # self.user = user # # def clean_password(self): # password = self.cleaned_data['password'] # if not self.user.check_password(password): # self.add_error('password', 'Senha inválida') # return password # # class LoginForm(AuthenticationForm): # # # this is named username so we can use Django's login view # username = forms.EmailField(required=True) # # class UserAddressForm(forms.ModelForm): # # class Meta: # model = UserAddress # fields = '__all__' # # def __init__(self, *args, **kwargs): # super(UserAddressForm, self).__init__(*args, **kwargs) # # # Limit regions to available cities # states = Region.objects.filter( # id__in=set(City.objects.values_list('region_id', flat=True))) # self.fields['state'].queryset = states # self.fields['state'].choices = states.values_list('id', 'name') # # # Group cities by region (state) # self.fields['city'].choices = self._group_cities() # # def _group_cities(self): # ''' # Build a choices-like list with all cities grouped by state (region) # ''' # return [ # (state, [(city.pk, city.name) for city in cities],) # for state, cities in groupby( # self.fields['city'].queryset.order_by('region__name', 'name'), # lambda city: city.region.name)] . Output only the next line.
self.assertEqual(UserAddressForm.Meta.fields, '__all__')
Given the code snippet: <|code_start|> @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): formfield_overrides = { models.PointField: {'widget': forms.TextInput}, } <|code_end|> , generate the next line using the imports in this file: from django import forms from django.contrib import admin from django.contrib.gis.db import models from .models import ( Project, ProjectApply, Tag, ) and context (functions, classes, or occasionally code) from other files: # Path: brasilcomvc/projects/models.py # class Project(models.Model): # # owner = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name='projects_owned') # name = models.CharField(max_length=60) # slug = models.SlugField(editable=False) # relevant_fact = models.TextField(null=True, blank=True) # about = models.TextField() # short_description = models.TextField(null=True, blank=True) # how_to_help = models.TextField() # requirements = models.TextField(blank=True) # tags = models.ManyToManyField('Tag', blank=True) # agenda = models.TextField(default='', blank=True) # address = models.TextField(verbose_name='endereço') # location = models.TextField(verbose_name='local', help_text=( # 'Local ou cidade. E.g. "Teatro Municipal" ou "São Paulo, SP".')) # latlng = models.PointField( # null=True, srid=4326, db_index=True, editable=False) # # img = ProcessedImageField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(854, 480)], # upload_to=project_img_upload_to) # img_thumbnail = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(320, 240)], # source='img') # img_opengraph = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(800, 420)], # source='img') # video = models.URLField(null=True, blank=True) # # name.verbose_name = 'nome' # relevant_fact.verbose_name = 'fato relevante' # about.verbose_name = 'descrição' # short_description.verbose_name = 'descrição curta' # how_to_help.verbose_name = 'como ajudar' # requirements.verbose_name = 'requisitos' # video.verbose_name = 'vídeo' # # class Meta: # verbose_name = 'Projeto' # verbose_name_plural = 'Projetos' # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('projects:project_details', kwargs={'slug': self.slug}) # # def clean(self): # # Use Google Maps API to geocode `address` into `latlng` # try: # addr = Geocoder.geocode(' '.join(self.address.splitlines()))[0] # self.latlng = Point(y=addr.latitude, x=addr.longitude, srid=4326) # # except GeocoderError as err: # if err.status != GeocoderError.G_GEO_ZERO_RESULTS: # raise # raise ValidationError('Endereço não reconhecido no Google Maps.') # # def save(self, **kwargs): # if self.pk is None: # self.slug = slugify(smart_text(self.name)) # super(Project, self).save(**kwargs) # # class ProjectApply(models.Model): # # volunteer = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name='applications', editable=False) # project = models.ForeignKey( # 'Project', related_name='applications', editable=False) # message = models.TextField() # created = models.DateTimeField(auto_now_add=True) # # volunteer.verbose_name = 'voluntário' # project.verbose_name = 'projeto' # message.verbose_name = 'mensagem ao organizador' # message.help_text = 'Conte-nos brevemente como você pode ajudar.' # created.verbose_name = 'hora do registro' # # class Meta: # unique_together = ('project', 'volunteer',) # verbose_name = 'inscrição em projeto' # verbose_name_plural = 'inscrições em projetos' # # def __str__(self): # return '{}: {}'.format(self.project.name, self.volunteer.full_name) # # def _get_email_context(self): # return { # attr: getattr(self, attr) # for attr in ('message', 'project', 'volunteer',)} # # def send_owner_email(self): # send_template_email( # subject='Alguém se inscreveu no seu projeto!', # to=self.project.owner.email, # template_name='emails/project_apply_owner.html', # context=self._get_email_context()) # # def send_volunteer_email(self): # send_template_email( # subject='Você se inscreveu num projeto!', # to=self.volunteer.email, # template_name='emails/project_apply_volunteer.html', # context=self._get_email_context()) # # class Tag(models.Model): # # name = models.CharField(max_length=24) # # def __str__(self): # return self.name . Output only the next line.
@admin.register(ProjectApply)
Using the snippet: <|code_start|> @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): formfield_overrides = { models.PointField: {'widget': forms.TextInput}, } @admin.register(ProjectApply) class ProjectApplyAdmin(admin.ModelAdmin): actions = None date_hierarchy = 'created' list_display = ('project', 'volunteer', 'created', 'message',) list_display_links = None list_filter = ('created',) search_fields = ('project__name', 'volunteer__full_name', 'message',) def has_delete_permission(self, request, obj=None): return False <|code_end|> , determine the next line of code. You have imports: from django import forms from django.contrib import admin from django.contrib.gis.db import models from .models import ( Project, ProjectApply, Tag, ) and context (class names, function names, or code) available: # Path: brasilcomvc/projects/models.py # class Project(models.Model): # # owner = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name='projects_owned') # name = models.CharField(max_length=60) # slug = models.SlugField(editable=False) # relevant_fact = models.TextField(null=True, blank=True) # about = models.TextField() # short_description = models.TextField(null=True, blank=True) # how_to_help = models.TextField() # requirements = models.TextField(blank=True) # tags = models.ManyToManyField('Tag', blank=True) # agenda = models.TextField(default='', blank=True) # address = models.TextField(verbose_name='endereço') # location = models.TextField(verbose_name='local', help_text=( # 'Local ou cidade. E.g. "Teatro Municipal" ou "São Paulo, SP".')) # latlng = models.PointField( # null=True, srid=4326, db_index=True, editable=False) # # img = ProcessedImageField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(854, 480)], # upload_to=project_img_upload_to) # img_thumbnail = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(320, 240)], # source='img') # img_opengraph = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(800, 420)], # source='img') # video = models.URLField(null=True, blank=True) # # name.verbose_name = 'nome' # relevant_fact.verbose_name = 'fato relevante' # about.verbose_name = 'descrição' # short_description.verbose_name = 'descrição curta' # how_to_help.verbose_name = 'como ajudar' # requirements.verbose_name = 'requisitos' # video.verbose_name = 'vídeo' # # class Meta: # verbose_name = 'Projeto' # verbose_name_plural = 'Projetos' # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('projects:project_details', kwargs={'slug': self.slug}) # # def clean(self): # # Use Google Maps API to geocode `address` into `latlng` # try: # addr = Geocoder.geocode(' '.join(self.address.splitlines()))[0] # self.latlng = Point(y=addr.latitude, x=addr.longitude, srid=4326) # # except GeocoderError as err: # if err.status != GeocoderError.G_GEO_ZERO_RESULTS: # raise # raise ValidationError('Endereço não reconhecido no Google Maps.') # # def save(self, **kwargs): # if self.pk is None: # self.slug = slugify(smart_text(self.name)) # super(Project, self).save(**kwargs) # # class ProjectApply(models.Model): # # volunteer = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name='applications', editable=False) # project = models.ForeignKey( # 'Project', related_name='applications', editable=False) # message = models.TextField() # created = models.DateTimeField(auto_now_add=True) # # volunteer.verbose_name = 'voluntário' # project.verbose_name = 'projeto' # message.verbose_name = 'mensagem ao organizador' # message.help_text = 'Conte-nos brevemente como você pode ajudar.' # created.verbose_name = 'hora do registro' # # class Meta: # unique_together = ('project', 'volunteer',) # verbose_name = 'inscrição em projeto' # verbose_name_plural = 'inscrições em projetos' # # def __str__(self): # return '{}: {}'.format(self.project.name, self.volunteer.full_name) # # def _get_email_context(self): # return { # attr: getattr(self, attr) # for attr in ('message', 'project', 'volunteer',)} # # def send_owner_email(self): # send_template_email( # subject='Alguém se inscreveu no seu projeto!', # to=self.project.owner.email, # template_name='emails/project_apply_owner.html', # context=self._get_email_context()) # # def send_volunteer_email(self): # send_template_email( # subject='Você se inscreveu num projeto!', # to=self.volunteer.email, # template_name='emails/project_apply_volunteer.html', # context=self._get_email_context()) # # class Tag(models.Model): # # name = models.CharField(max_length=24) # # def __str__(self): # return self.name . Output only the next line.
admin.site.register(Tag)
Next line prediction: <|code_start|># coding: utf8 from __future__ import unicode_literals class Signup(AnonymousRequiredMixin, CreateView): ''' User Signup ''' <|code_end|> . Use current file imports: (from django.core.urlresolvers import reverse, reverse_lazy from django.contrib.auth import ( authenticate, login as login_user, logout as logout_user) from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.views import ( login as auth_login, password_reset as django_password_reset, password_reset_confirm as django_password_reset_confirm, password_reset_done as django_password_reset_done) from django.contrib import messages from django.http import HttpResponseRedirect from django.views.generic import ( CreateView, FormView, UpdateView) from brasilcomvc.common.views import AnonymousRequiredMixin, LoginRequiredMixin from .forms import ( EditNotificationsForm, DeleteUserForm, LoginForm, PasswordResetForm, SignupForm, UserAddressForm)) and context including class names, function names, or small code snippets from other files: # Path: brasilcomvc/common/views.py # class AnonymousRequiredMixin(object): # # ''' # Make any view be accessible by unauthenticated users only # ''' # # def dispatch(self, request, *args, **kwargs): # if request.user.is_authenticated(): # return redirect(settings.LOGIN_REDIRECT_URL) # return super(AnonymousRequiredMixin, self).dispatch( # request, *args, **kwargs) # # class LoginRequiredMixin(object): # # ''' # Bind login requirement to any view # ''' # # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) # # Path: brasilcomvc/accounts/forms.py # class EditNotificationsForm(forms.ModelForm): # # class Meta: # model = User # fields = ('email_newsletter',) # labels = { # 'email_newsletter': 'Receber novidades sobre o Brasil.com.vc', # } # # class DeleteUserForm(forms.Form): # # password = forms.CharField(label='Senha', widget=forms.PasswordInput) # # def __init__(self, user, *args, **kwargs): # super(DeleteUserForm, self).__init__(*args, **kwargs) # self.user = user # # def clean_password(self): # password = self.cleaned_data['password'] # if not self.user.check_password(password): # self.add_error('password', 'Senha inválida') # return password # # class LoginForm(AuthenticationForm): # # # this is named username so we can use Django's login view # username = forms.EmailField(required=True) # # class PasswordResetForm(djangoPasswordResetForm): # ''' # Override the built-in form to customize email sending # ''' # # def save( # self, use_https=False, token_generator=default_token_generator, # from_email=None, domain_override=None, request=None, **kwargs): # try: # user = User.objects.get(email=self.cleaned_data['email']) # except User.DoesNotExist: # return # # if not user.has_usable_password(): # return # # if domain_override: # site_name = domain = domain_override # else: # current_site = get_current_site(request) # site_name = current_site.name # domain = current_site.domain # # context = { # 'email': user.email, # 'domain': domain, # 'site_name': site_name, # 'uid': urlsafe_base64_encode(force_bytes(user.pk)), # 'user': user, # 'token': token_generator.make_token(user), # 'protocol': 'https' if use_https else 'http', # } # context['reset_link'] = '{protocol}://{domain}{url}'.format( # url=reverse('accounts:password_reset_confirm', kwargs={ # 'uidb64': context['uid'], 'token': context['token']}), # **context) # # send_template_email( # subject='Redefinição de senha', # to=self.cleaned_data['email'], # template_name='emails/password_reset.html', # context=context) # # class SignupForm(forms.ModelForm): # # password = forms.CharField(label='Senha', widget=forms.PasswordInput) # # class Meta: # model = User # fields = ('full_name', 'email',) # # def save(self, **kwargs): # # Set password from user input # self.instance.set_password(self.cleaned_data['password']) # return super(SignupForm, self).save(**kwargs) # # class UserAddressForm(forms.ModelForm): # # class Meta: # model = UserAddress # fields = '__all__' # # def __init__(self, *args, **kwargs): # super(UserAddressForm, self).__init__(*args, **kwargs) # # # Limit regions to available cities # states = Region.objects.filter( # id__in=set(City.objects.values_list('region_id', flat=True))) # self.fields['state'].queryset = states # self.fields['state'].choices = states.values_list('id', 'name') # # # Group cities by region (state) # self.fields['city'].choices = self._group_cities() # # def _group_cities(self): # ''' # Build a choices-like list with all cities grouped by state (region) # ''' # return [ # (state, [(city.pk, city.name) for city in cities],) # for state, cities in groupby( # self.fields['city'].queryset.order_by('region__name', 'name'), # lambda city: city.region.name)] . Output only the next line.
form_class = SignupForm
Given snippet: <|code_start|># coding: utf8 from __future__ import unicode_literals class UserAdmin(admin.ModelAdmin): class UserAddressInline(admin.StackedInline): model = UserAddress list_display = ('email', 'full_name', 'username', 'date_joined') list_filter = ('date_joined',) fieldsets = ( ('Informações Pessoais', { 'fields': ('full_name', 'username', 'email',), }), ('Informações Profissionais', { 'fields': ('job_title', 'bio',), }), ('Notificações', { 'fields': ('email_newsletter',), }), ) inlines = (UserAddressInline,) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from .models import User, UserAddress and context: # Path: brasilcomvc/accounts/models.py # class User(AbstractBaseUser, PermissionsMixin): # # # Personal Info # email = models.EmailField(unique=True) # full_name = models.CharField('Nome Completo', max_length=255) # username = models.SlugField(max_length=30, null=True, blank=True) # picture = ProcessedImageField( # null=True, blank=True, # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(256, 256)], # upload_to=user_picture_upload_to) # picture_medium = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(128, 128)], # source='picture') # picture_small = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(50, 50)], # source='picture') # # # Professional Info # job_title = models.CharField(max_length=80, null=True, blank=True) # bio = models.TextField(null=True, blank=True) # # # Status # date_joined = models.DateTimeField(auto_now_add=True) # date_updated = models.DateTimeField(auto_now=True) # is_active = models.BooleanField(editable=False, default=True) # is_staff = models.BooleanField(editable=False, default=False) # # # Notifications # email_newsletter = models.BooleanField(default=True) # # # Verbose names # email.verbose_name = 'e-mail' # full_name.verbose_name = 'nome completo' # username.verbose_name = 'nome de usuário' # picture.verbose_name = 'foto do usuário' # job_title.verbose_name = 'profissão' # bio.verbose_name = 'biografia' # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ('full_name',) # # objects = UserManager() # # class Meta: # verbose_name = 'usuário' # # def get_short_name(self): # return self.full_name.split()[0] if self.full_name else '' # # def get_full_name(self): # return self.full_name # # def send_welcome_email(self): # send_template_email( # subject='Bem vindo!', # to=self.email, # template_name='emails/welcome.html', # context={'user': self}) # # class UserAddress(models.Model): # # user = models.OneToOneField('User', related_name='address', editable=False) # zipcode = models.CharField(max_length=90) # address_line1 = models.CharField(max_length=120) # address_line2 = models.CharField(max_length=80, blank=True) # state = models.ForeignKey('cities_light.Region') # city = models.ForeignKey('cities_light.City') # # # Verbose names # zipcode.verbose_name = 'CEP' # address_line1.verbose_name = 'endereço' # address_line2.verbose_name = 'complemento' # state.verbose_name = 'estado' # city.verbose_name = 'cidade' which might include code, classes, or functions. Output only the next line.
admin.site.register(User, UserAdmin)
Given snippet: <|code_start|># coding: utf8 from __future__ import unicode_literals class UserAdmin(admin.ModelAdmin): class UserAddressInline(admin.StackedInline): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from .models import User, UserAddress and context: # Path: brasilcomvc/accounts/models.py # class User(AbstractBaseUser, PermissionsMixin): # # # Personal Info # email = models.EmailField(unique=True) # full_name = models.CharField('Nome Completo', max_length=255) # username = models.SlugField(max_length=30, null=True, blank=True) # picture = ProcessedImageField( # null=True, blank=True, # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(256, 256)], # upload_to=user_picture_upload_to) # picture_medium = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(128, 128)], # source='picture') # picture_small = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(50, 50)], # source='picture') # # # Professional Info # job_title = models.CharField(max_length=80, null=True, blank=True) # bio = models.TextField(null=True, blank=True) # # # Status # date_joined = models.DateTimeField(auto_now_add=True) # date_updated = models.DateTimeField(auto_now=True) # is_active = models.BooleanField(editable=False, default=True) # is_staff = models.BooleanField(editable=False, default=False) # # # Notifications # email_newsletter = models.BooleanField(default=True) # # # Verbose names # email.verbose_name = 'e-mail' # full_name.verbose_name = 'nome completo' # username.verbose_name = 'nome de usuário' # picture.verbose_name = 'foto do usuário' # job_title.verbose_name = 'profissão' # bio.verbose_name = 'biografia' # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ('full_name',) # # objects = UserManager() # # class Meta: # verbose_name = 'usuário' # # def get_short_name(self): # return self.full_name.split()[0] if self.full_name else '' # # def get_full_name(self): # return self.full_name # # def send_welcome_email(self): # send_template_email( # subject='Bem vindo!', # to=self.email, # template_name='emails/welcome.html', # context={'user': self}) # # class UserAddress(models.Model): # # user = models.OneToOneField('User', related_name='address', editable=False) # zipcode = models.CharField(max_length=90) # address_line1 = models.CharField(max_length=120) # address_line2 = models.CharField(max_length=80, blank=True) # state = models.ForeignKey('cities_light.Region') # city = models.ForeignKey('cities_light.City') # # # Verbose names # zipcode.verbose_name = 'CEP' # address_line1.verbose_name = 'endereço' # address_line2.verbose_name = 'complemento' # state.verbose_name = 'estado' # city.verbose_name = 'cidade' which might include code, classes, or functions. Output only the next line.
model = UserAddress
Predict the next line after this snippet: <|code_start|> class BlogRedirectTestCase(TestCase): def test_blog_redirect_with_empty_setting(self): req = RequestFactory().get('/blog') with self.assertRaises(Http404): with self.settings(BLOG_URL=''): <|code_end|> using the current file's imports: from django.core.urlresolvers import reverse from django.http import Http404 from django.test import RequestFactory, TestCase from ..views import blog_redirect and any relevant context from other files: # Path: brasilcomvc/portal/views.py # def blog_redirect(request): # """Simple redirect to blog URL. # """ # if not settings.BLOG_URL: # raise Http404() # return HttpResponsePermanentRedirect(settings.BLOG_URL) . Output only the next line.
resp = blog_redirect(req)
Based on the snippet: <|code_start|> class SetUserInfoFromAuthProviderTestCase(TestCase): def test_should_return_none_if_user_not_found(self): self.assertIsNone(set_user_info_from_auth_provider(None, None, None)) def test_should_register_full_name_and_email_on_user_instance(self): backend = mock.Mock() details = { 'email': 'cool@mailinator.com', 'fullname': 'My Name Yo', } <|code_end|> , predict the immediate next line with the help of imports: from django.test import TestCase from ..models import User from ..pipelines import set_user_info_from_auth_provider import mock and context (classes, functions, sometimes code) from other files: # Path: brasilcomvc/accounts/models.py # class User(AbstractBaseUser, PermissionsMixin): # # # Personal Info # email = models.EmailField(unique=True) # full_name = models.CharField('Nome Completo', max_length=255) # username = models.SlugField(max_length=30, null=True, blank=True) # picture = ProcessedImageField( # null=True, blank=True, # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(256, 256)], # upload_to=user_picture_upload_to) # picture_medium = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(128, 128)], # source='picture') # picture_small = ImageSpecField( # format='JPEG', # options={'quality': 80}, # processors=[ResizeToFill(50, 50)], # source='picture') # # # Professional Info # job_title = models.CharField(max_length=80, null=True, blank=True) # bio = models.TextField(null=True, blank=True) # # # Status # date_joined = models.DateTimeField(auto_now_add=True) # date_updated = models.DateTimeField(auto_now=True) # is_active = models.BooleanField(editable=False, default=True) # is_staff = models.BooleanField(editable=False, default=False) # # # Notifications # email_newsletter = models.BooleanField(default=True) # # # Verbose names # email.verbose_name = 'e-mail' # full_name.verbose_name = 'nome completo' # username.verbose_name = 'nome de usuário' # picture.verbose_name = 'foto do usuário' # job_title.verbose_name = 'profissão' # bio.verbose_name = 'biografia' # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ('full_name',) # # objects = UserManager() # # class Meta: # verbose_name = 'usuário' # # def get_short_name(self): # return self.full_name.split()[0] if self.full_name else '' # # def get_full_name(self): # return self.full_name # # def send_welcome_email(self): # send_template_email( # subject='Bem vindo!', # to=self.email, # template_name='emails/welcome.html', # context={'user': self}) # # Path: brasilcomvc/accounts/pipelines.py # def set_user_info_from_auth_provider(backend, user, details, *args, **kwargs): # """Social auth pipeline to set user info returned from auth provider # """ # if not user: # return # # user.email = details['email'] # user.full_name = details['fullname'] # # backend.strategy.storage.user.changed(user) . Output only the next line.
user = User()
Predict the next line after this snippet: <|code_start|> class UIGuidelineView(TemplateView): template_name = 'guideline/ui.html' def get_context_data(self, **kwargs): return dict( super(UIGuidelineView, self).get_context_data(**kwargs), <|code_end|> using the current file's imports: from django.views.generic import TemplateView from .forms import ExampleForm and any relevant context from other files: # Path: brasilcomvc/guideline/forms.py # class ExampleForm(forms.Form): # ''' # A dummy form to represent every possible kind of form widget to be used # in this project. # ''' # # _choices = [(1, 'One'), (2, 'Two'), (3, 'Three')] # # email = forms.EmailField( # widget=forms.EmailInput()) # text = forms.CharField( # widget=forms.TextInput(), min_length=3, max_length=10) # text_disabled = forms.CharField( # widget=forms.TextInput(attrs={'disabled': ''}), # help_text='Disabled just because.', # initial='Immutable') # textarea = forms.CharField( # widget=forms.Textarea( # attrs={'placeholder': 'Type something here'})) # password = forms.CharField( # widget=forms.PasswordInput) # search = forms.CharField( # widget=forms.TextInput(attrs={'type': 'search'})) # one_choice_select = forms.IntegerField( # widget=forms.Select(choices=_choices)) # one_choice_radio = forms.IntegerField( # widget=forms.RadioSelect(choices=_choices)) # multi_choice_select = forms.IntegerField( # widget=forms.SelectMultiple(choices=_choices)) # multi_choice_checkboxes = forms.IntegerField( # widget=forms.CheckboxSelectMultiple(choices=_choices), # help_text='Pick multiple options.') # option_toggle = forms.BooleanField( # widget=forms.CheckboxInput()) # option_toggle_disabled = forms.BooleanField( # widget=forms.CheckboxInput(attrs={'disabled': ''})) # spin_number = forms.IntegerField( # widget=forms.NumberInput(), initial=0) # range_number = forms.IntegerField( # widget=forms.NumberInput( # attrs={'type': 'range', 'min': 0, 'max': 10, 'step': 1}), # initial=0) # date = forms.DateField( # widget=forms.DateInput(attrs={'type': 'date'})) . Output only the next line.
empty_form=ExampleForm(),
Given snippet: <|code_start|> class FilterCityImportTestCase(TestCase): def test_filter_city_import_should_raise_invalid_items_when_not_br(self): items = [None, None, None, None, None, None, None, None, 'NOBR'] <|code_end|> , continue by predicting the next line. Consider current file imports: from django.test import TestCase from cities_light import InvalidItems from ..signals import filter_city_import and context: # Path: brasilcomvc/accounts/signals.py # def filter_city_import(sender, items, **kwargs): # if items[8] != 'BR': # raise InvalidItems() which might include code, classes, or functions. Output only the next line.
self.assertRaises(InvalidItems, filter_city_import, None, items)
Based on the snippet: <|code_start|> urlpatterns = [ # About url(r'^sobre/$', TemplateView.as_view(template_name='portal/about.html'), name='about'), # How It Works url(r'^como-funciona/$', TemplateView.as_view(template_name='portal/how_it_works.html'), name='how_it_works'), # Blog redirect <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import url from django.views.generic import TemplateView from .views import blog_redirect and context (classes, functions, sometimes code) from other files: # Path: brasilcomvc/portal/views.py # def blog_redirect(request): # """Simple redirect to blog URL. # """ # if not settings.BLOG_URL: # raise Http404() # return HttpResponsePermanentRedirect(settings.BLOG_URL) . Output only the next line.
url(r'^blog/$', blog_redirect, name='blog_redirect'),
Next line prediction: <|code_start|># encoding: utf8 from __future__ import unicode_literals User = get_user_model() class SignupTestCase(TestCase): url = reverse('accounts:signup') def test_signup_page_is_accessible(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_inherits_anonymous_required_mixin(self): <|code_end|> . Use current file imports: (from django.contrib.auth import get_user_model from django.core import mail from django.core.urlresolvers import reverse from django.test import TestCase from brasilcomvc.common.views import AnonymousRequiredMixin, LoginRequiredMixin from cities_light.models import City from ..models import UserAddress from ..views import ( DeleteUser, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, )) and context including class names, function names, or small code snippets from other files: # Path: brasilcomvc/common/views.py # class AnonymousRequiredMixin(object): # # ''' # Make any view be accessible by unauthenticated users only # ''' # # def dispatch(self, request, *args, **kwargs): # if request.user.is_authenticated(): # return redirect(settings.LOGIN_REDIRECT_URL) # return super(AnonymousRequiredMixin, self).dispatch( # request, *args, **kwargs) # # class LoginRequiredMixin(object): # # ''' # Bind login requirement to any view # ''' # # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) # # Path: brasilcomvc/accounts/models.py # class UserAddress(models.Model): # # user = models.OneToOneField('User', related_name='address', editable=False) # zipcode = models.CharField(max_length=90) # address_line1 = models.CharField(max_length=120) # address_line2 = models.CharField(max_length=80, blank=True) # state = models.ForeignKey('cities_light.Region') # city = models.ForeignKey('cities_light.City') # # # Verbose names # zipcode.verbose_name = 'CEP' # address_line1.verbose_name = 'endereço' # address_line2.verbose_name = 'complemento' # state.verbose_name = 'estado' # city.verbose_name = 'cidade' # # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response . Output only the next line.
self.assertTrue(issubclass(Signup, AnonymousRequiredMixin))
Given the code snippet: <|code_start|># encoding: utf8 from __future__ import unicode_literals User = get_user_model() class SignupTestCase(TestCase): url = reverse('accounts:signup') def test_signup_page_is_accessible(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_inherits_anonymous_required_mixin(self): <|code_end|> , generate the next line using the imports in this file: from django.contrib.auth import get_user_model from django.core import mail from django.core.urlresolvers import reverse from django.test import TestCase from brasilcomvc.common.views import AnonymousRequiredMixin, LoginRequiredMixin from cities_light.models import City from ..models import UserAddress from ..views import ( DeleteUser, EditNotifications, EditPersonalInfo, EditProfessionalInfo, EditSecuritySettings, EditUserAddress, Signup, ) and context (functions, classes, or occasionally code) from other files: # Path: brasilcomvc/common/views.py # class AnonymousRequiredMixin(object): # # ''' # Make any view be accessible by unauthenticated users only # ''' # # def dispatch(self, request, *args, **kwargs): # if request.user.is_authenticated(): # return redirect(settings.LOGIN_REDIRECT_URL) # return super(AnonymousRequiredMixin, self).dispatch( # request, *args, **kwargs) # # class LoginRequiredMixin(object): # # ''' # Bind login requirement to any view # ''' # # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) # # Path: brasilcomvc/accounts/models.py # class UserAddress(models.Model): # # user = models.OneToOneField('User', related_name='address', editable=False) # zipcode = models.CharField(max_length=90) # address_line1 = models.CharField(max_length=120) # address_line2 = models.CharField(max_length=80, blank=True) # state = models.ForeignKey('cities_light.Region') # city = models.ForeignKey('cities_light.City') # # # Verbose names # zipcode.verbose_name = 'CEP' # address_line1.verbose_name = 'endereço' # address_line2.verbose_name = 'complemento' # state.verbose_name = 'estado' # city.verbose_name = 'cidade' # # Path: brasilcomvc/accounts/views.py # class DeleteUser(LoginRequiredMixin, FormView): # # form_class = DeleteUserForm # template_name = 'accounts/delete-user.html' # # def get_form_kwargs(self): # kwargs = super(DeleteUser, self).get_form_kwargs() # kwargs['user'] = self.request.user # return kwargs # # def form_valid(self, form): # email = self.request.user.email # # # Delete user and logout (clean session) # self.request.user.delete() # logout_user(self.request) # # # Put deleted_email into session for feedback form consumption # self.request.session['deleted_email'] = email # self.request.session['feedback_success_message'] = ( # 'Sua conta foi excluída. Até logo! :(') # return HttpResponseRedirect('{}?next={}'.format( # reverse('feedback:create'), reverse('accounts:login'))) # # class EditNotifications(BaseEditUser, UpdateView): # # form_class = EditNotificationsForm # title = 'Notificações' # url_pattern = 'accounts:edit_notifications' # # class EditPersonalInfo(BaseEditUser, UpdateView): # # fields = ('full_name', 'username', 'email', 'picture',) # title = 'Informações Pessoais' # url_pattern = 'accounts:edit_personal_info' # # class EditProfessionalInfo(BaseEditUser, UpdateView): # # fields = ('job_title', 'bio',) # title = 'Informações Profissionais' # url_pattern = 'accounts:edit_professional_info' # # class EditSecuritySettings(BaseEditUser, UpdateView): # # form_class = PasswordChangeForm # success_message = 'Configurações de segurança atualizadas com sucesso!' # template_name = 'accounts/edit_security_settings.html' # title = 'Segurança' # url_pattern = 'accounts:edit_security_settings' # # def get_form_kwargs(self): # kwargs = super(EditSecuritySettings, self).get_form_kwargs() # kwargs['user'] = kwargs.pop('instance') # return kwargs # # class EditUserAddress(BaseEditUser, UpdateView): # # form_class = UserAddressForm # title = 'Editar Endereço' # url_pattern = 'accounts:edit_user_address' # # def get_object(self): # # If the user already has an address, make it the edition target # return getattr(self.request.user, 'address', None) # # def form_valid(self, form): # address = form.save(commit=False) # address.user = self.request.user # address.save() # return super(EditUserAddress, self).form_valid(form) # # class Signup(AnonymousRequiredMixin, CreateView): # ''' # User Signup # ''' # # form_class = SignupForm # success_url = reverse_lazy('accounts:edit_dashboard') # template_name = 'accounts/signup.html' # # def form_valid(self, form): # response = super(Signup, self).form_valid(form) # # # log user in # user = authenticate(email=form.cleaned_data['email'], # password=form.cleaned_data['password']) # login_user(self.request, user) # # # Send welcome email upon signup # user.send_welcome_email() # # # Display a welcome message # messages.info( # self.request, # 'Parabéns! Você agora está cadastrado e já pode buscar projetos ' # 'para participar. Bem vindo e mãos à obra!') # # return response . Output only the next line.
self.assertTrue(issubclass(Signup, AnonymousRequiredMixin))
Predict the next line for this snippet: <|code_start|> class FeedbackForm(forms.ModelForm): class Meta: fields = [ 'email', 'question_1', 'question_2', 'question_3', 'question_4', 'question_5', 'comments', ] <|code_end|> with the help of current file imports: from django import forms from .models import Feedback and context from other files: # Path: brasilcomvc/feedback/models.py # class Feedback(models.Model): # # email = models.EmailField() # question_1 = models.BooleanField(QUESTIONS[0], default=False) # question_2 = models.BooleanField(QUESTIONS[1], default=False) # question_3 = models.BooleanField(QUESTIONS[2], default=False) # question_4 = models.BooleanField(QUESTIONS[3], default=False) # question_5 = models.BooleanField(QUESTIONS[4], default=False) # comments = models.TextField(default='') # # created = models.DateTimeField(auto_now_add=True) # updated = models.DateTimeField(auto_now=True) # # comments.verbose_name = 'comentários' # # def __str__(self): # return '{} - {}'.format(self.email, self.created) # # def __unicode__(self): # return '{} - {}'.format(self.email, self.created) , which may contain function names, class names, or code. Output only the next line.
model = Feedback
Using the snippet: <|code_start|> class TestForm(forms.Form): test_field = forms.CharField(max_length=40) class TypeTestCase(TestCase): def test_type_filter_should_return_correct_class_name(self): self.assertEqual(type_([]), 'list') form = TestForm() self.assertEqual(type_(form['test_field'].field.widget), 'TextInput') class FormFieldTestCase(TestCase): def test_generate_an_id_from_a_form_with_prefix(self): form = TestForm(prefix='foo') self.assertEqual( <|code_end|> , determine the next line of code. You have imports: from django import forms from django.test import TestCase from ...templatetags.form_utils import ( form_field, form_fieldset, type_, ) and context (class names, function names, or code) available: # Path: brasilcomvc/common/templatetags/form_utils.py # @register.inclusion_tag('widgets/form_field.html') # def form_field(field): # ''' # Render a single field # ''' # form = field.form # # # Prepare field HTML classes # classes = tuple(filter(None, [ # 'required' if field.field.required else None, # 'error' if field.errors else None, # ])) # # return { # 'classes': classes, # 'field': field, # 'form_id': form.prefix or type(form).__name__.lower(), # } # # @register.inclusion_tag('widgets/form_fieldset.html') # def form_fieldset(form, legend=None, fields=None): # ''' # Render a <fieldset> from `form` with provided space-separated fields # ''' # return { # 'fields': list(map(lambda field: form[field], fields.split())), # 'legend': legend, # } # # @register.filter('type') # def type_(obj): # ''' # Retrieve the class name of an object # ''' # return str(type(obj).__name__) . Output only the next line.
form_field(form['test_field'])['form_id'], form.prefix)
Given snippet: <|code_start|> def test_generate_an_id_from_a_form_without_prefix(self): form = TestForm() self.assertEqual(form_field(form['test_field'])['form_id'], 'testform') def test_render_html_classes_correctly_for_required_field(self): form = TestForm() form.fields['test_field'].required = True self.assertEqual( form_field(form['test_field'])['classes'], ('required',)) def test_render_html_classes_correctly_for_empty_required_field(self): form = TestForm(data={}) form.fields['test_field'].required = True self.assertEqual( set(form_field(form['test_field'])['classes']), set(['required', 'error'])) def test_render_html_classes_correctly_for_non_required_field(self): form = TestForm() form.fields['test_field'].required = False self.assertEqual( form_field(form['test_field'])['classes'], ()) class FormFieldsetTestCase(TestCase): def test_generate_list_of_bound_fields_correctly(self): form = TestForm() self.assertEqual( [bound_field.field for bound_field in <|code_end|> , continue by predicting the next line. Consider current file imports: from django import forms from django.test import TestCase from ...templatetags.form_utils import ( form_field, form_fieldset, type_, ) and context: # Path: brasilcomvc/common/templatetags/form_utils.py # @register.inclusion_tag('widgets/form_field.html') # def form_field(field): # ''' # Render a single field # ''' # form = field.form # # # Prepare field HTML classes # classes = tuple(filter(None, [ # 'required' if field.field.required else None, # 'error' if field.errors else None, # ])) # # return { # 'classes': classes, # 'field': field, # 'form_id': form.prefix or type(form).__name__.lower(), # } # # @register.inclusion_tag('widgets/form_fieldset.html') # def form_fieldset(form, legend=None, fields=None): # ''' # Render a <fieldset> from `form` with provided space-separated fields # ''' # return { # 'fields': list(map(lambda field: form[field], fields.split())), # 'legend': legend, # } # # @register.filter('type') # def type_(obj): # ''' # Retrieve the class name of an object # ''' # return str(type(obj).__name__) which might include code, classes, or functions. Output only the next line.
form_fieldset(form, fields='test_field')['fields']],
Given the code snippet: <|code_start|> class TestForm(forms.Form): test_field = forms.CharField(max_length=40) class TypeTestCase(TestCase): def test_type_filter_should_return_correct_class_name(self): <|code_end|> , generate the next line using the imports in this file: from django import forms from django.test import TestCase from ...templatetags.form_utils import ( form_field, form_fieldset, type_, ) and context (functions, classes, or occasionally code) from other files: # Path: brasilcomvc/common/templatetags/form_utils.py # @register.inclusion_tag('widgets/form_field.html') # def form_field(field): # ''' # Render a single field # ''' # form = field.form # # # Prepare field HTML classes # classes = tuple(filter(None, [ # 'required' if field.field.required else None, # 'error' if field.errors else None, # ])) # # return { # 'classes': classes, # 'field': field, # 'form_id': form.prefix or type(form).__name__.lower(), # } # # @register.inclusion_tag('widgets/form_fieldset.html') # def form_fieldset(form, legend=None, fields=None): # ''' # Render a <fieldset> from `form` with provided space-separated fields # ''' # return { # 'fields': list(map(lambda field: form[field], fields.split())), # 'legend': legend, # } # # @register.filter('type') # def type_(obj): # ''' # Retrieve the class name of an object # ''' # return str(type(obj).__name__) . Output only the next line.
self.assertEqual(type_([]), 'list')
Using the snippet: <|code_start|> from_email=None, domain_override=None, request=None, **kwargs): try: user = User.objects.get(email=self.cleaned_data['email']) except User.DoesNotExist: return if not user.has_usable_password(): return if domain_override: site_name = domain = domain_override else: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain context = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', } context['reset_link'] = '{protocol}://{domain}{url}'.format( url=reverse('accounts:password_reset_confirm', kwargs={ 'uidb64': context['uid'], 'token': context['token']}), **context) <|code_end|> , determine the next line of code. You have imports: from itertools import groupby from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import ( AuthenticationForm, PasswordResetForm as djangoPasswordResetForm, ) from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.urlresolvers import reverse from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from brasilcomvc.common.email import send_template_email from cities_light.models import City, Region from .models import UserAddress and context (class names, function names, or code) available: # Path: brasilcomvc/common/email.py # def send_template_email(subject, to, template_name, context=None): # ''' # Render a template into an email body and send it through Django's send_mail # # - The `to` parameter must be a single email address. # - This function omits `from_email` because it expects it to exist from an # environment variable. # - Other parameters are omitted as well because there are no # use for them in the current use case. # ''' # body = render_to_string(template_name, context or {}, Context({ # 'mailing_address': settings.MAILING_ADDRESS, # 'site_url': settings.BASE_URL, # 'sns_facebook': settings.SNS_FACEBOOK, # 'sns_googleplus': settings.SNS_GOOGLEPLUS, # 'sns_twitter': settings.SNS_TWITTER, # 'subject': subject, # })) # plain_body = strip_tags(body) # # email = EmailMultiAlternatives( # subject=subject, # body=plain_body, # to=(to,)) # email.attach_alternative(body, 'text/html') # email.send() # # Path: brasilcomvc/accounts/models.py # class UserAddress(models.Model): # # user = models.OneToOneField('User', related_name='address', editable=False) # zipcode = models.CharField(max_length=90) # address_line1 = models.CharField(max_length=120) # address_line2 = models.CharField(max_length=80, blank=True) # state = models.ForeignKey('cities_light.Region') # city = models.ForeignKey('cities_light.City') # # # Verbose names # zipcode.verbose_name = 'CEP' # address_line1.verbose_name = 'endereço' # address_line2.verbose_name = 'complemento' # state.verbose_name = 'estado' # city.verbose_name = 'cidade' . Output only the next line.
send_template_email(
Continue the code snippet: <|code_start|> context=context) class SignupForm(forms.ModelForm): password = forms.CharField(label='Senha', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name', 'email',) def save(self, **kwargs): # Set password from user input self.instance.set_password(self.cleaned_data['password']) return super(SignupForm, self).save(**kwargs) class EditNotificationsForm(forms.ModelForm): class Meta: model = User fields = ('email_newsletter',) labels = { 'email_newsletter': 'Receber novidades sobre o Brasil.com.vc', } class UserAddressForm(forms.ModelForm): class Meta: <|code_end|> . Use current file imports: from itertools import groupby from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import ( AuthenticationForm, PasswordResetForm as djangoPasswordResetForm, ) from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.urlresolvers import reverse from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from brasilcomvc.common.email import send_template_email from cities_light.models import City, Region from .models import UserAddress and context (classes, functions, or code) from other files: # Path: brasilcomvc/common/email.py # def send_template_email(subject, to, template_name, context=None): # ''' # Render a template into an email body and send it through Django's send_mail # # - The `to` parameter must be a single email address. # - This function omits `from_email` because it expects it to exist from an # environment variable. # - Other parameters are omitted as well because there are no # use for them in the current use case. # ''' # body = render_to_string(template_name, context or {}, Context({ # 'mailing_address': settings.MAILING_ADDRESS, # 'site_url': settings.BASE_URL, # 'sns_facebook': settings.SNS_FACEBOOK, # 'sns_googleplus': settings.SNS_GOOGLEPLUS, # 'sns_twitter': settings.SNS_TWITTER, # 'subject': subject, # })) # plain_body = strip_tags(body) # # email = EmailMultiAlternatives( # subject=subject, # body=plain_body, # to=(to,)) # email.attach_alternative(body, 'text/html') # email.send() # # Path: brasilcomvc/accounts/models.py # class UserAddress(models.Model): # # user = models.OneToOneField('User', related_name='address', editable=False) # zipcode = models.CharField(max_length=90) # address_line1 = models.CharField(max_length=120) # address_line2 = models.CharField(max_length=80, blank=True) # state = models.ForeignKey('cities_light.Region') # city = models.ForeignKey('cities_light.City') # # # Verbose names # zipcode.verbose_name = 'CEP' # address_line1.verbose_name = 'endereço' # address_line2.verbose_name = 'complemento' # state.verbose_name = 'estado' # city.verbose_name = 'cidade' . Output only the next line.
model = UserAddress
Based on the snippet: <|code_start|> class HomeBannerTestCase(TestCase): def test_image_upload_to(self): banner = HomeBanner.objects.create() self.assertEqual( <|code_end|> , predict the immediate next line with the help of imports: from django.test import TestCase from ..models import ( HomeBanner, homebanner_image_upload_to, homebanner_video_upload_to,) and context (classes, functions, sometimes code) from other files: # Path: brasilcomvc/portal/models.py # class HomeBanner(models.Model): # # image = ProcessedImageField( # format='JPEG', # options={'quality': 90}, # processors=[ResizeToFill(2000, 550)], # upload_to=homebanner_image_upload_to) # video = models.FileField( # null=True, blank=True, upload_to=homebanner_video_upload_to) # content = models.TextField() # created = models.DateTimeField(default=now, editable=False) # # image.verbose_name = 'imagem' # image.help_text = 'Imagem de alta resolução; será cortada para 1400x550.' # video.verbose_name = 'vídeo' # video.help_text = 'Vídeo curto e leve; ficará em loop.' # content.verbose_name = 'conteúdo' # content.help_text = 'Conteúdo (HTML) para sobrepor a imagem no banner.' # # class Meta: # verbose_name = 'Banner da Home' # verbose_name_plural = 'Banners da Home' # # def __str__(self): # return truncatechars(striptags(self.content), 40) # # def homebanner_image_upload_to(instance, filename): # return 'homebanners/{:%Y-%m-%d}/image.jpeg'.format(instance.created) # # def homebanner_video_upload_to(instance, filename): # return 'homebanners/{created:%Y-%m-%d}/video{extension}'.format( # created=instance.created, # extension=filename[filename.rfind('.'):]) . Output only the next line.
homebanner_image_upload_to(banner, 'whatever.png'),
Given the code snippet: <|code_start|> class HomeBannerTestCase(TestCase): def test_image_upload_to(self): banner = HomeBanner.objects.create() self.assertEqual( homebanner_image_upload_to(banner, 'whatever.png'), 'homebanners/{:%Y-%m-%d}/image.jpeg'.format(banner.created)) def test_video_upload_to(self): banner = HomeBanner.objects.create() self.assertEqual( <|code_end|> , generate the next line using the imports in this file: from django.test import TestCase from ..models import ( HomeBanner, homebanner_image_upload_to, homebanner_video_upload_to,) and context (functions, classes, or occasionally code) from other files: # Path: brasilcomvc/portal/models.py # class HomeBanner(models.Model): # # image = ProcessedImageField( # format='JPEG', # options={'quality': 90}, # processors=[ResizeToFill(2000, 550)], # upload_to=homebanner_image_upload_to) # video = models.FileField( # null=True, blank=True, upload_to=homebanner_video_upload_to) # content = models.TextField() # created = models.DateTimeField(default=now, editable=False) # # image.verbose_name = 'imagem' # image.help_text = 'Imagem de alta resolução; será cortada para 1400x550.' # video.verbose_name = 'vídeo' # video.help_text = 'Vídeo curto e leve; ficará em loop.' # content.verbose_name = 'conteúdo' # content.help_text = 'Conteúdo (HTML) para sobrepor a imagem no banner.' # # class Meta: # verbose_name = 'Banner da Home' # verbose_name_plural = 'Banners da Home' # # def __str__(self): # return truncatechars(striptags(self.content), 40) # # def homebanner_image_upload_to(instance, filename): # return 'homebanners/{:%Y-%m-%d}/image.jpeg'.format(instance.created) # # def homebanner_video_upload_to(instance, filename): # return 'homebanners/{created:%Y-%m-%d}/video{extension}'.format( # created=instance.created, # extension=filename[filename.rfind('.'):]) . Output only the next line.
homebanner_video_upload_to(banner, 'whatever.webm'),