Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|> if session_language in accept_languages: return session_language # language can be forced in config user_language = current_app.config.get('CHANJO_LANGUAGE') if user_language: return user_language # try to guess the language from the user accept header that # the browser transmits. We support de/fr/en in this example. # The best match wins. return request.accept_languages.best_match(accept_languages) def configure_blueprints(app): """Configure blueprints in views.""" for blueprint in app.config.get('BLUEPRINTS', []): app.register_blueprint(blueprint) def configure_template_filters(app): """Configure custom Jinja2 template filters.""" @app.context_processor def inject_levels(): return dict(levels=LEVELS) @app.template_filter() def human_date(value): """Prettify dates for humans.""" <|code_end|> using the current file's imports: from flask import current_app, Flask, request from flask_babel import Babel from .config import DefaultConfig from .extensions import api from .utils import pretty_date from .constants import LEVELS and any relevant context from other files: # Path: chanjo_report/server/config.py # class DefaultConfig(BaseConfig): # # """Default config values during development.""" # # DEBUG = True # ACCEPT_LANGUAGES = {'en': 'English', 'sv': 'Svenska'} # # Path: chanjo_report/server/extensions.py # # Path: chanjo_report/server/utils.py # def pretty_date(date, default=None): # """Return string representing "time since": 3 days ago, 5 hours ago. # # Ref: https://bitbucket.org/danjac/newsmeme/src/a281babb9ca3/newsmeme/ # """ # if default is None: # default = 'just now' # # now = datetime.utcnow() # diff = now - date # # periods = ((diff.days / 365, 'year', 'years'), # (diff.days / 30, 'month', 'months'), # (diff.days / 7, 'week', 'weeks'), # (diff.days, 'day', 'days'), # (diff.seconds / 3600, 'hour', 'hours'), # (diff.seconds / 60, 'minute', 'minutes'), # (diff.seconds, 'second', 'seconds')) # # for period, singular, plural in periods: # if not period: # continue # if period == 1: # return "%d %s ago" % (period, singular) # else: # return "%d %s ago" % (period, plural) # return default # # Path: chanjo_report/server/constants.py # LEVELS = OrderedDict([ # (10, 'completeness_10'), # (15, 'completeness_15'), # (20, 'completeness_20'), # (50, 'completeness_50'), # (100, 'completeness_100'), # ]) . Output only the next line.
return pretty_date(value)
Using the snippet: <|code_start|> """Determine locale to use for translations.""" accept_languages = current_app.config.get('ACCEPT_LANGUAGES') # first check request args session_language = request.args.get('lang') if session_language in accept_languages: return session_language # language can be forced in config user_language = current_app.config.get('CHANJO_LANGUAGE') if user_language: return user_language # try to guess the language from the user accept header that # the browser transmits. We support de/fr/en in this example. # The best match wins. return request.accept_languages.best_match(accept_languages) def configure_blueprints(app): """Configure blueprints in views.""" for blueprint in app.config.get('BLUEPRINTS', []): app.register_blueprint(blueprint) def configure_template_filters(app): """Configure custom Jinja2 template filters.""" @app.context_processor def inject_levels(): <|code_end|> , determine the next line of code. You have imports: from flask import current_app, Flask, request from flask_babel import Babel from .config import DefaultConfig from .extensions import api from .utils import pretty_date from .constants import LEVELS and context (class names, function names, or code) available: # Path: chanjo_report/server/config.py # class DefaultConfig(BaseConfig): # # """Default config values during development.""" # # DEBUG = True # ACCEPT_LANGUAGES = {'en': 'English', 'sv': 'Svenska'} # # Path: chanjo_report/server/extensions.py # # Path: chanjo_report/server/utils.py # def pretty_date(date, default=None): # """Return string representing "time since": 3 days ago, 5 hours ago. # # Ref: https://bitbucket.org/danjac/newsmeme/src/a281babb9ca3/newsmeme/ # """ # if default is None: # default = 'just now' # # now = datetime.utcnow() # diff = now - date # # periods = ((diff.days / 365, 'year', 'years'), # (diff.days / 30, 'month', 'months'), # (diff.days / 7, 'week', 'weeks'), # (diff.days, 'day', 'days'), # (diff.seconds / 3600, 'hour', 'hours'), # (diff.seconds / 60, 'minute', 'minutes'), # (diff.seconds, 'second', 'seconds')) # # for period, singular, plural in periods: # if not period: # continue # if period == 1: # return "%d %s ago" % (period, singular) # else: # return "%d %s ago" % (period, plural) # return default # # Path: chanjo_report/server/constants.py # LEVELS = OrderedDict([ # (10, 'completeness_10'), # (15, 'completeness_15'), # (20, 'completeness_20'), # (50, 'completeness_50'), # (100, 'completeness_100'), # ]) . Output only the next line.
return dict(levels=LEVELS)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class Config: SQLALCHEMY_DATABASE_URI = os.environ['SQLALCHEMY_DATABASE_URI'] SQLALCHEMY_TRACK_MODIFICATIONS = False <|code_end|> , generate the next line using the imports in this file: import os from chanjo_report.server.app import create_app and context (functions, classes, or occasionally code) from other files: # Path: chanjo_report/server/app.py # def create_app(config=None): # """Create a Flask app (Flask Application Factory).""" # app = Flask(__name__, instance_relative_config=True) # configure_app(app, config=config) # configure_extensions(app) # configure_blueprints(app) # configure_template_filters(app) # # return app . Output only the next line.
application = create_app(config=Config)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- logger = logging.getLogger(__name__) index_bp = Blueprint('index', __name__, template_folder='templates', static_folder='static', static_url_path='/static/index') @index_bp.route('/') def index(): <|code_end|> , generate the next line using the imports in this file: import logging from chanjo.store.models import Sample, Transcript from flask import Blueprint, render_template from chanjo_report.server.extensions import api and context (functions, classes, or occasionally code) from other files: # Path: chanjo_report/server/extensions.py . Output only the next line.
sample_objs = api.query(Sample).limit(20)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- def render_html(options): """Start a Flask server to generate HTML report on request.""" # spin up the Flask server config = ProdConfig config.SQLALCHEMY_DATABASE_URI = options['database'] report_options = options['report'] config.CHANJO_PANEL_NAME = report_options.get('panel_name') config.CHANJO_LANGUAGE = report_options.get('language') config.CHANJO_PANEL = report_options.get('panel') config.DEBUG = report_options.get('debug') <|code_end|> . Use current file imports: import click from chanjo_report.server.app import create_app from chanjo_report.server.config import ProdConfig and context (classes, functions, or code) from other files: # Path: chanjo_report/server/app.py # def create_app(config=None): # """Create a Flask app (Flask Application Factory).""" # app = Flask(__name__, instance_relative_config=True) # configure_app(app, config=config) # configure_extensions(app) # configure_blueprints(app) # configure_template_filters(app) # # return app # # Path: chanjo_report/server/config.py # class ProdConfig(DefaultConfig): # SQLALCHEMY_TRACK_MODIFICATIONS = False # DEBUG = False . Output only the next line.
app = create_app(config=config)
Continue the code snippet: <|code_start|> """Generate key metrics rows.""" query = ( api.query( TranscriptStat, func.avg(TranscriptStat.mean_coverage).label('mean_coverage'), func.avg(TranscriptStat.completeness_10).label('completeness_10'), func.avg(TranscriptStat.completeness_15).label('completeness_15'), func.avg(TranscriptStat.completeness_20).label('completeness_20'), func.avg(TranscriptStat.completeness_50).label('completeness_50'), func.avg(TranscriptStat.completeness_100).label('completeness_100'), ) .filter(TranscriptStat.sample_id.in_(samples_ids)) .group_by(TranscriptStat.sample_id) ) if genes: query = (query.join(TranscriptStat.transcript) .filter(Transcript.gene_id.in_(genes))) return query def transcripts_rows(sample_ids, genes=None, level=10): """Generate metrics rows for transcripts.""" for sample_id in sample_ids: sample_obj = Sample.query.get(sample_id) all_tx = TranscriptStat.query.filter_by(sample_id=sample_id) if genes: all_tx = (all_tx.join(TranscriptStat.transcript) .filter(Transcript.gene_id.in_(genes))) tx_count = all_tx.count() <|code_end|> . Use current file imports: import itertools import logging from flask import abort, flash from sqlalchemy.exc import OperationalError from sqlalchemy import func from chanjo.store.models import Transcript, TranscriptStat, Sample from chanjo.sex import predict_sex from chanjo_report.server.constants import LEVELS from chanjo_report.server.extensions import api and context (classes, functions, or code) from other files: # Path: chanjo_report/server/constants.py # LEVELS = OrderedDict([ # (10, 'completeness_10'), # (15, 'completeness_15'), # (20, 'completeness_20'), # (50, 'completeness_50'), # (100, 'completeness_100'), # ]) # # Path: chanjo_report/server/extensions.py . Output only the next line.
stat_field = getattr(TranscriptStat, LEVELS[level])
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- def render_pdf(options): """Generate a PDF report for a given group of samples.""" group_id = options['report']['group'] url = "/groups/{}".format(group_id) # spin up the Flask server config = DefaultConfig report_options = options['report'] config.CHANJO_URI = options.get('database') panel_name = report_options.get('panel_name') config.CHANJO_LANGUAGE = report_options.get('language') config.CHANJO_PANEL = report_options.get('panel') <|code_end|> , predict the next line using imports from the current file: from flask import url_for from flask_weasyprint import HTML from chanjo_report.server.app import create_app from chanjo_report.server.config import DefaultConfig and context including class names, function names, and sometimes code from other files: # Path: chanjo_report/server/app.py # def create_app(config=None): # """Create a Flask app (Flask Application Factory).""" # app = Flask(__name__, instance_relative_config=True) # configure_app(app, config=config) # configure_extensions(app) # configure_blueprints(app) # configure_template_filters(app) # # return app # # Path: chanjo_report/server/config.py # class DefaultConfig(BaseConfig): # # """Default config values during development.""" # # DEBUG = True # ACCEPT_LANGUAGES = {'en': 'English', 'sv': 'Svenska'} . Output only the next line.
app = create_app(config=config)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- def render_pdf(options): """Generate a PDF report for a given group of samples.""" group_id = options['report']['group'] url = "/groups/{}".format(group_id) # spin up the Flask server <|code_end|> , predict the next line using imports from the current file: from flask import url_for from flask_weasyprint import HTML from chanjo_report.server.app import create_app from chanjo_report.server.config import DefaultConfig and context including class names, function names, and sometimes code from other files: # Path: chanjo_report/server/app.py # def create_app(config=None): # """Create a Flask app (Flask Application Factory).""" # app = Flask(__name__, instance_relative_config=True) # configure_app(app, config=config) # configure_extensions(app) # configure_blueprints(app) # configure_template_filters(app) # # return app # # Path: chanjo_report/server/config.py # class DefaultConfig(BaseConfig): # # """Default config values during development.""" # # DEBUG = True # ACCEPT_LANGUAGES = {'en': 'English', 'sv': 'Svenska'} . Output only the next line.
config = DefaultConfig
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @click.command() @click.option('-r', '--render', type=click.Choice(['html', 'pdf']), default='html') @click.option('-l', '--language', type=click.Choice(['en', 'sv'])) @click.option('-d', '--debug', is_flag=True) @click.pass_context def report(context, render, language, debug): """Generate a coverage report from Chanjo SQL output.""" # get uri + dialect of Chanjo database if context.obj['database'] is None: click.echo('database URI not found') context.abort() # set the custom option context.obj['report'] = dict(language=language, debug=debug) if render == 'html': <|code_end|> . Write the next line using the current file imports: import click from chanjo_report.interfaces import html, pdf and context from other files: # Path: chanjo_report/interfaces/html.py # def render_html(options): # # Path: chanjo_report/interfaces/pdf.py # def render_pdf(options): , which may include functions, classes, or code. Output only the next line.
html.render_html(context.obj)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @click.command() @click.option('-r', '--render', type=click.Choice(['html', 'pdf']), default='html') @click.option('-l', '--language', type=click.Choice(['en', 'sv'])) @click.option('-d', '--debug', is_flag=True) @click.pass_context def report(context, render, language, debug): """Generate a coverage report from Chanjo SQL output.""" # get uri + dialect of Chanjo database if context.obj['database'] is None: click.echo('database URI not found') context.abort() # set the custom option context.obj['report'] = dict(language=language, debug=debug) if render == 'html': html.render_html(context.obj) else: <|code_end|> . Write the next line using the current file imports: import click from chanjo_report.interfaces import html, pdf and context from other files: # Path: chanjo_report/interfaces/html.py # def render_html(options): # # Path: chanjo_report/interfaces/pdf.py # def render_pdf(options): , which may include functions, classes, or code. Output only the next line.
pdf.render_pdf(context.obj)
Here is a snippet: <|code_start|> # Goes to homepage res = testapp.get('/') # Fills out login form, password incorrect form = res.forms['loginForm'] form['email'] = user.email form['password'] = 'wrong' # Submits res = form.submit() # sees error assert 'Invalid password' in res def test_sees_error_message_if_email_doesnt_exist(self, user, testapp): """Show error if email doesn't exist.""" # Goes to homepage res = testapp.get('/') # Fills out login form, password incorrect form = res.forms['loginForm'] form['email'] = 'unknown@unknown.com' form['password'] = 'myprecious' # Submits res = form.submit() # sees error assert 'Specified user does not exist' in res class TestRegistering: """Register a user.""" def test_can_register(self, user, testapp): """Register a new user.""" <|code_end|> . Write the next line using the current file imports: from flask import url_for from recruit_app.user.models import User from .factories import UserFactory and context from other files: # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: tests/factories.py # class UserFactory(BaseFactory): # """User factory.""" # # email = Sequence(lambda n: 'user{0}@example.com'.format(n)) # password = PostGenerationMethodCall('set_password', 'example') # active = True # # class Meta: # """Factory configuration.""" # # model = User , which may include functions, classes, or code. Output only the next line.
old_count = len(User.query.all())
Given the following code snippet before the placeholder: <|code_start|> # Clicks Create Account button res = res.click('Create account') # Fills out the form form = res.forms['registerForm'] form['email'] = 'foo@bar.com' form['password'] = 'secret' form['password_confirm'] = 'secret' # Submits # res = form.submit().follow() res = form.submit().follow() assert res.status_code == 200 # A new user was created assert len(User.query.all()) == old_count + 1 def test_sees_error_message_if_passwords_dont_match(self, user, testapp): """Show error if passwords don't match.""" # Goes to registration page res = testapp.get(url_for('security.register')) # Fills out form, but passwords don't match form = res.forms['registerForm'] form['email'] = 'foo@bar.com' form['password'] = 'secret' form['password_confirm'] = 'secrets' # Submits res = form.submit() # sees error message assert 'Passwords do not match' in res def test_sees_error_message_if_user_already_registered(self, user, testapp): """Show error if user already registered.""" <|code_end|> , predict the next line using imports from the current file: from flask import url_for from recruit_app.user.models import User from .factories import UserFactory and context including class names, function names, and sometimes code from other files: # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: tests/factories.py # class UserFactory(BaseFactory): # """User factory.""" # # email = Sequence(lambda n: 'user{0}@example.com'.format(n)) # password = PostGenerationMethodCall('set_password', 'example') # active = True # # class Meta: # """Factory configuration.""" # # model = User . Output only the next line.
user = UserFactory(active=True) # A registered user
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # from recruit_app.wsgi import app if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) # app.debug = True def _make_context(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys import subprocess import pytest from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from recruit_app.app import create_app from recruit_app.user.models import User, Role from recruit_app.settings import DevConfig, ProdConfig from recruit_app.database import db and context: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): which might include code, classes, or functions. Output only the next line.
return {'app': app, 'db': db, 'User': User, 'Role': Role}
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # from recruit_app.wsgi import app if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) # app.debug = True def _make_context(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ <|code_end|> . Use current file imports: (import os import sys import subprocess import pytest from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from recruit_app.app import create_app from recruit_app.user.models import User, Role from recruit_app.settings import DevConfig, ProdConfig from recruit_app.database import db) and context including class names, function names, or small code snippets from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
return {'app': app, 'db': db, 'User': User, 'Role': Role}
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # from recruit_app.wsgi import app if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: <|code_end|> . Use current file imports: import os import sys import subprocess import pytest from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from recruit_app.app import create_app from recruit_app.user.models import User, Role from recruit_app.settings import DevConfig, ProdConfig from recruit_app.database import db and context (classes, functions, or code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
app = create_app(DevConfig)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # from recruit_app.wsgi import app if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) # app.debug = True def _make_context(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ <|code_end|> , predict the next line using imports from the current file: import os import sys import subprocess import pytest from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from recruit_app.app import create_app from recruit_app.user.models import User, Role from recruit_app.settings import DevConfig, ProdConfig from recruit_app.database import db and context including class names, function names, and sometimes code from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
return {'app': app, 'db': db, 'User': User, 'Role': Role}
Next line prediction: <|code_start|> user = User(email='foo@bar.com') user.save() assert bool(user.created_at) assert isinstance(user.created_at, dt.datetime) def test_password_is_nullable(self): """Test null password.""" user = User(email='foo@bar.com') user.save() assert user.password is None def test_factory(self, db): """Test user factory.""" user = UserFactory(password='myprecious') db.session.commit() assert bool(user.email) assert bool(user.created_at) assert user.is_admin is False assert user.active is True assert user.check_password('myprecious') def test_check_password(self): """Check password.""" user = User.create(email='foo@bar.com', password='foobarbaz123') assert user.check_password('foobarbaz123') is True assert user.check_password('barfoobaz') is False def test_roles(self): """Add a role to a user.""" <|code_end|> . Use current file imports: (import datetime as dt import pytest from recruit_app.user.models import Role, User from .factories import UserFactory) and context including class names, function names, or small code snippets from other files: # Path: recruit_app/user/models.py # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) # # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: tests/factories.py # class UserFactory(BaseFactory): # """User factory.""" # # email = Sequence(lambda n: 'user{0}@example.com'.format(n)) # password = PostGenerationMethodCall('set_password', 'example') # active = True # # class Meta: # """Factory configuration.""" # # model = User . Output only the next line.
role = Role(name='admin')
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """Model unit tests.""" @pytest.mark.usefixtures('db') class TestUser: """User tests.""" def test_get_by_id(self): """Get user by ID.""" <|code_end|> with the help of current file imports: import datetime as dt import pytest from recruit_app.user.models import Role, User from .factories import UserFactory and context from other files: # Path: recruit_app/user/models.py # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) # # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: tests/factories.py # class UserFactory(BaseFactory): # """User factory.""" # # email = Sequence(lambda n: 'user{0}@example.com'.format(n)) # password = PostGenerationMethodCall('set_password', 'example') # active = True # # class Meta: # """Factory configuration.""" # # model = User , which may contain function names, class names, or code. Output only the next line.
user = User(email='foo@bar.com')
Continue the code snippet: <|code_start|> @pytest.mark.usefixtures('db') class TestUser: """User tests.""" def test_get_by_id(self): """Get user by ID.""" user = User(email='foo@bar.com') user.save() retrieved = User.get_by_id(user.id) assert retrieved == user def test_created_at_defaults_to_datetime(self): """Test creation date.""" user = User(email='foo@bar.com') user.save() assert bool(user.created_at) assert isinstance(user.created_at, dt.datetime) def test_password_is_nullable(self): """Test null password.""" user = User(email='foo@bar.com') user.save() assert user.password is None def test_factory(self, db): """Test user factory.""" <|code_end|> . Use current file imports: import datetime as dt import pytest from recruit_app.user.models import Role, User from .factories import UserFactory and context (classes, functions, or code) from other files: # Path: recruit_app/user/models.py # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) # # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: tests/factories.py # class UserFactory(BaseFactory): # """User factory.""" # # email = Sequence(lambda n: 'user{0}@example.com'.format(n)) # password = PostGenerationMethodCall('set_password', 'example') # active = True # # class Meta: # """Factory configuration.""" # # model = User . Output only the next line.
user = UserFactory(password='myprecious')
Based on the snippet: <|code_start|> def register_admin_views(admin, db): admin.add_view(HrApplicationAdmin(HrApplication, db.session, category='Recruitment')) admin.add_view(HrApplicationCommentAdmin(HrApplicationComment, db.session, category='Recruitment')) <|code_end|> , predict the immediate next line with the help of imports: from recruit_app.recruit.models import HrApplication, HrApplicationComment, HrApplicationCommentHistory from recruit_app.user.models import EveCharacter from recruit_app.admin import AuthenticatedModelView and context (classes, functions, sometimes code) from other files: # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # class HrApplicationCommentHistory(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comment_history' # # old_comment = Column(db.Text, nullable=True) # comment_id = ReferenceCol('hr_comments') # editor = ReferenceCol('users') # comment = relationship('HrApplicationComment', foreign_keys=[comment_id], backref=backref('hr_comment_history', cascade="delete")) # user = relationship('User', backref='hr_comment_history', foreign_keys=[editor]) # # def __repr__(self): # return str(self.editor) + " - Edited comment" # # Path: recruit_app/user/models.py # class EveCharacter(Model, TimeMixin): # __tablename__ = 'characters' # # character_id = Column(db.String(254), primary_key=True) # character_name = Column(db.String(254)) # corporation_id = ReferenceCol('corporations', pk_name='corporation_id', nullable=True) # corporation = relationship('EveCorporationInfo', backref='characters', foreign_keys=[corporation_id]) # # api_id = ReferenceCol('api_key_pairs', pk_name='api_id', nullable=True) # api = relationship('EveApiKeyPair', backref='characters', foreign_keys=[api_id]) # # user_id = ReferenceCol('users', nullable=True) # user = relationship('User', backref='characters', foreign_keys=[user_id]) # # skillpoints = Column(db.Integer, nullable=True) # previous_users = db.relationship('User', secondary=previous_chars, backref=db.backref('previous_chars', lazy='dynamic'), lazy='dynamic') # # def __str__(self): # return self.character_name # # Path: recruit_app/admin.py # class AuthenticatedModelView(ModelView): # column_display_pk = True # # def is_accessible(self): # if current_user.has_role("admin"): # return True # return False # # def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # abort(401) . Output only the next line.
admin.add_view(HrApplicationCommentHistoryAdmin(HrApplicationCommentHistory, db.session, category='Recruitment'))
Continue the code snippet: <|code_start|> def register_admin_views(admin, db): admin.add_view(HrApplicationAdmin(HrApplication, db.session, category='Recruitment')) admin.add_view(HrApplicationCommentAdmin(HrApplicationComment, db.session, category='Recruitment')) admin.add_view(HrApplicationCommentHistoryAdmin(HrApplicationCommentHistory, db.session, category='Recruitment')) # Useful things: column_list, column_labels, column_searchable_list, column_filters, form_columns, form_ajax_refs <|code_end|> . Use current file imports: from recruit_app.recruit.models import HrApplication, HrApplicationComment, HrApplicationCommentHistory from recruit_app.user.models import EveCharacter from recruit_app.admin import AuthenticatedModelView and context (classes, functions, or code) from other files: # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # class HrApplicationCommentHistory(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comment_history' # # old_comment = Column(db.Text, nullable=True) # comment_id = ReferenceCol('hr_comments') # editor = ReferenceCol('users') # comment = relationship('HrApplicationComment', foreign_keys=[comment_id], backref=backref('hr_comment_history', cascade="delete")) # user = relationship('User', backref='hr_comment_history', foreign_keys=[editor]) # # def __repr__(self): # return str(self.editor) + " - Edited comment" # # Path: recruit_app/user/models.py # class EveCharacter(Model, TimeMixin): # __tablename__ = 'characters' # # character_id = Column(db.String(254), primary_key=True) # character_name = Column(db.String(254)) # corporation_id = ReferenceCol('corporations', pk_name='corporation_id', nullable=True) # corporation = relationship('EveCorporationInfo', backref='characters', foreign_keys=[corporation_id]) # # api_id = ReferenceCol('api_key_pairs', pk_name='api_id', nullable=True) # api = relationship('EveApiKeyPair', backref='characters', foreign_keys=[api_id]) # # user_id = ReferenceCol('users', nullable=True) # user = relationship('User', backref='characters', foreign_keys=[user_id]) # # skillpoints = Column(db.Integer, nullable=True) # previous_users = db.relationship('User', secondary=previous_chars, backref=db.backref('previous_chars', lazy='dynamic'), lazy='dynamic') # # def __str__(self): # return self.character_name # # Path: recruit_app/admin.py # class AuthenticatedModelView(ModelView): # column_display_pk = True # # def is_accessible(self): # if current_user.has_role("admin"): # return True # return False # # def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # abort(401) . Output only the next line.
class HrApplicationAdmin(AuthenticatedModelView):
Given the code snippet: <|code_start|> class TestRegisterForm: """Register form.""" def test_validate_email_already_registered(self, user): """Enter email that is already registered.""" form = ConfirmRegisterForm(email=user.email, password='example', password_confirm='example') assert form.validate() is False assert '{0} is already associated with an account.'\ .format(user.email) in form.email.errors def test_validate_success(self, db): """Register with success.""" form = ConfirmRegisterForm(email='new@test.test', password='example', password_confirm='example') assert form.validate() is True class TestLoginForm: """Login form.""" def test_validate_success(self, user): """Login successful.""" user.set_password('example') user.save() <|code_end|> , generate the next line using the imports in this file: from recruit_app.public.forms import LoginForm from flask_security.forms import ConfirmRegisterForm and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/public/forms.py # class LoginForm(Form): # email = TextField('Email', validators=[DataRequired()]) # password = PasswordField('Password', validators=[DataRequired()]) # submit = SubmitField(label='Log In') # # def __init__(self, *args, **kwargs): # super(LoginForm, self).__init__(*args, **kwargs) # self.user = None # # def validate(self): # initial_validation = super(LoginForm, self).validate() # if not initial_validation: # return False # # self.user = user_datastore.get_user(self.email.data) # if not self.user: # self.email.errors.append('Unknown email address') # return False # # if not self.user.check_password(self.password.data): # self.password.errors.append('Invalid password') # return False # # if not self.user.active: # self.email.errors.append('User not activated') # return False # return True . Output only the next line.
form = LoginForm(email=user.email, password='example')
Given the following code snippet before the placeholder: <|code_start|> blueprint = Blueprint("hr", __name__, url_prefix='/hr', static_folder="../static") @blueprint.route("/compliance/<int:corp_id>", methods=['GET']) @login_required @roles_accepted('admin', 'compliance') def compliance(corp_id): <|code_end|> , predict the next line using imports from the current file: from flask import Blueprint, render_template from flask_security.decorators import login_required from flask_security import current_user, roles_accepted from recruit_app.hr.managers import HrManager and context including class names, function names, and sometimes code from other files: # Path: recruit_app/hr/managers.py # class HrManager: # def __init__(self): # pass # # @staticmethod # @cache_extension.memoize(timeout=3600) # def get_compliance(corp_id): # url = 'https://goonfleet.com' # # s = requests.session() # r = s.get(url, verify=True) # # soup = BeautifulSoup(r.text, 'html.parser') # token = soup.find('input', {'name':'auth_key'})['value'] # # payload = { # 'ips_username' : current_app.config['GSF_USERNAME'], # 'ips_password' : current_app.config['GSF_PASSWORD'], # 'auth_key' : token, # 'referer' : 'https://goonfleet.com/', # 'rememberMe' : 1, # } # # url = 'https://goonfleet.com/index.php?app=core&module=global&section=login&do=process' # r = s.post(url, data=payload, verify=True) # # url = 'https://goonfleet.com/corps/checkMembers.php' # r = s.get(url, verify=True) # # payload = { # 'corpID' : str(corp_id) # } # r = s.post(url, data=payload, verify=True) # # soup = BeautifulSoup(r.text, 'html.parser') # # output = "<table id='compliance' class='table tablesorter'><thead><th>Character Name</th><th>Forum Name/Main</th><th>Primary Group</th><th>Status</th></thead><tbody>\n" # # for row in soup.findAll('tr'): # alert = None # if row.get('class'): # alert = row.get('class')[1] # cols = row.findAll('td') # charname = cols[1].get_text() # forumname = cols[2].get_text() # group = cols[3].get_text() # # # Look for an API for character # if not alert and not EveCharacter.query.filter_by(character_name=charname).first(): # alert = 'alert-warning' # # # Set status # if alert == 'alert-warning': # status = 'No KF API' # elif alert == 'alert-success': # status = 'Director' # elif alert == 'alert-error': # status = 'No Goon Auth' # else: # status = 'OK' # # if alert: # output = output + '<tr class="alert {0}"><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>\n'.format(alert, charname, forumname, group, status) # else: # output = output + '<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>\n'.format(charname, forumname, group, status) # # output = output + '</tbody></table>' # return output . Output only the next line.
return render_template('hr/compliance.html', data=HrManager.get_compliance(corp_id))
Continue the code snippet: <|code_start|> 'auth_key' : token, 'referer' : 'https://goonfleet.com/', 'rememberMe' : 1, } url = 'https://goonfleet.com/index.php?app=core&module=global&section=login&do=process' r = s.post(url, data=payload, verify=True) url = 'https://goonfleet.com/corps/checkMembers.php' r = s.get(url, verify=True) payload = { 'corpID' : str(corp_id) } r = s.post(url, data=payload, verify=True) soup = BeautifulSoup(r.text, 'html.parser') output = "<table id='compliance' class='table tablesorter'><thead><th>Character Name</th><th>Forum Name/Main</th><th>Primary Group</th><th>Status</th></thead><tbody>\n" for row in soup.findAll('tr'): alert = None if row.get('class'): alert = row.get('class')[1] cols = row.findAll('td') charname = cols[1].get_text() forumname = cols[2].get_text() group = cols[3].get_text() # Look for an API for character <|code_end|> . Use current file imports: from recruit_app.user.models import EveCharacter from recruit_app.extensions import cache_extension from flask import current_app from bs4 import BeautifulSoup import requests and context (classes, functions, or code) from other files: # Path: recruit_app/user/models.py # class EveCharacter(Model, TimeMixin): # __tablename__ = 'characters' # # character_id = Column(db.String(254), primary_key=True) # character_name = Column(db.String(254)) # corporation_id = ReferenceCol('corporations', pk_name='corporation_id', nullable=True) # corporation = relationship('EveCorporationInfo', backref='characters', foreign_keys=[corporation_id]) # # api_id = ReferenceCol('api_key_pairs', pk_name='api_id', nullable=True) # api = relationship('EveApiKeyPair', backref='characters', foreign_keys=[api_id]) # # user_id = ReferenceCol('users', nullable=True) # user = relationship('User', backref='characters', foreign_keys=[user_id]) # # skillpoints = Column(db.Integer, nullable=True) # previous_users = db.relationship('User', secondary=previous_chars, backref=db.backref('previous_chars', lazy='dynamic'), lazy='dynamic') # # def __str__(self): # return self.character_name # # Path: recruit_app/extensions.py . Output only the next line.
if not alert and not EveCharacter.query.filter_by(character_name=charname).first():
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class HrManager: def __init__(self): pass @staticmethod <|code_end|> , generate the next line using the imports in this file: from recruit_app.user.models import EveCharacter from recruit_app.extensions import cache_extension from flask import current_app from bs4 import BeautifulSoup import requests and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/user/models.py # class EveCharacter(Model, TimeMixin): # __tablename__ = 'characters' # # character_id = Column(db.String(254), primary_key=True) # character_name = Column(db.String(254)) # corporation_id = ReferenceCol('corporations', pk_name='corporation_id', nullable=True) # corporation = relationship('EveCorporationInfo', backref='characters', foreign_keys=[corporation_id]) # # api_id = ReferenceCol('api_key_pairs', pk_name='api_id', nullable=True) # api = relationship('EveApiKeyPair', backref='characters', foreign_keys=[api_id]) # # user_id = ReferenceCol('users', nullable=True) # user = relationship('User', backref='characters', foreign_keys=[user_id]) # # skillpoints = Column(db.Integer, nullable=True) # previous_users = db.relationship('User', secondary=previous_chars, backref=db.backref('previous_chars', lazy='dynamic'), lazy='dynamic') # # def __str__(self): # return self.character_name # # Path: recruit_app/extensions.py . Output only the next line.
@cache_extension.memoize(timeout=3600)
Given the code snippet: <|code_start|> if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: <|code_end|> , generate the next line using the imports in this file: import os, sys from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig from recruit_app.user.tasks import run_alliance_corp_update, run_api_key_update and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') . Output only the next line.
app = create_app(DevConfig)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """Extensions module. Each extension is initialized in the app factory located in app.py """ bcrypt = Bcrypt() # from flask_login import LoginManager # login_manager = LoginManager() cache_extension = Cache() db = SQLAlchemy() security = Security() <|code_end|> , generate the next line using the imports in this file: from flask_bcrypt import Bcrypt from flask_cache import Cache from flask_sqlalchemy import SQLAlchemy from flask_security import Security, SQLAlchemyUserDatastore from recruit_app.user.models import User, Role from flask_migrate import Migrate from raven.contrib.flask import Sentry from flask_debugtoolbar import DebugToolbarExtension from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_rq import RQ from flask_misaka import Misaka and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) . Output only the next line.
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """Extensions module. Each extension is initialized in the app factory located in app.py """ bcrypt = Bcrypt() # from flask_login import LoginManager # login_manager = LoginManager() cache_extension = Cache() db = SQLAlchemy() security = Security() <|code_end|> , predict the next line using imports from the current file: from flask_bcrypt import Bcrypt from flask_cache import Cache from flask_sqlalchemy import SQLAlchemy from flask_security import Security, SQLAlchemyUserDatastore from recruit_app.user.models import User, Role from flask_migrate import Migrate from raven.contrib.flask import Sentry from flask_debugtoolbar import DebugToolbarExtension from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_rq import RQ from flask_misaka import Misaka and context including class names, function names, and sometimes code from other files: # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # class Role(SurrogatePK, Model, RoleMixin): # __tablename__ = 'roles' # name = Column(db.String(80), unique=True) # description = db.Column(db.String(255)) # # def __repr__(self): # return '<Role({name})>'.format(name=self.name) . Output only the next line.
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # import flask_whooshalchemy as whooshalchemy # from sqlalchemy_searchable import make_searchable # from sqlalchemy_utils.types import TSVectorType, ScalarListType # # from sqlalchemy_searchable import SearchQueryMixin # from sqlalchemy.dialects import postgresql # make_searchable() character_apps = db.Table('app_characters', db.Column('app_id', db.Integer(), db.ForeignKey('hr_applications.id')), db.Column('character_id', db.String(), db.ForeignKey('characters.character_id'))) <|code_end|> with the help of current file imports: from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from sqlalchemy.orm import backref from flask_sqlalchemy import BaseQuery import datetime and context from other files: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): , which may contain function names, class names, or code. Output only the next line.
class HrApplication(SurrogatePK, TimeMixin, Model):
Based on the snippet: <|code_start|> 'why_interested', 'find_out', 'favorite_role', 'main_character_name'] main_character_name = Column(db.Unicode, nullable=True) alt_application = Column(db.Boolean, default=False) characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') thesis = Column(db.UnicodeText, nullable=True) how_long = Column(db.Text, nullable=True) notable_accomplishments = Column(db.Text, nullable=True) corporation_history = Column(db.Text, nullable=True) why_leaving = Column(db.Text, nullable=True) what_know = Column(db.Text, nullable=True) what_expect = Column(db.Text, nullable=True) bought_characters = Column(db.Text, nullable=True) why_interested = Column(db.Text, nullable=True) goon_interaction = Column(db.Text, nullable=True) friends = Column(db.Text, nullable=True) scale = Column(db.Text, nullable=True) find_out = Column(db.Text, nullable=True) favorite_role = Column(db.Text, nullable=True) <|code_end|> , predict the immediate next line with the help of imports: from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from sqlalchemy.orm import backref from flask_sqlalchemy import BaseQuery import datetime and context (classes, functions, sometimes code) from other files: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
user_id = ReferenceCol('users', nullable=True)
Given the following code snippet before the placeholder: <|code_start|> # make_searchable() character_apps = db.Table('app_characters', db.Column('app_id', db.Integer(), db.ForeignKey('hr_applications.id')), db.Column('character_id', db.String(), db.ForeignKey('characters.character_id'))) class HrApplication(SurrogatePK, TimeMixin, Model): # query_class = HrApplicationQuery __tablename__ = 'hr_applications' __searchable__ = ['thesis', 'how_long', 'notable_accomplishments', 'corporation_history', 'why_leaving', 'what_know', 'what_expect', 'bought_characters', 'why_interested', 'find_out', 'favorite_role', 'main_character_name'] main_character_name = Column(db.Unicode, nullable=True) alt_application = Column(db.Boolean, default=False) <|code_end|> , predict the next line using imports from the current file: from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from sqlalchemy.orm import backref from flask_sqlalchemy import BaseQuery import datetime and context including class names, function names, and sometimes code from other files: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic')
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # import flask_whooshalchemy as whooshalchemy # from sqlalchemy_searchable import make_searchable # from sqlalchemy_utils.types import TSVectorType, ScalarListType # # from sqlalchemy_searchable import SearchQueryMixin # from sqlalchemy.dialects import postgresql # make_searchable() character_apps = db.Table('app_characters', db.Column('app_id', db.Integer(), db.ForeignKey('hr_applications.id')), db.Column('character_id', db.String(), db.ForeignKey('characters.character_id'))) <|code_end|> with the help of current file imports: from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from sqlalchemy.orm import backref from flask_sqlalchemy import BaseQuery import datetime and context from other files: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): , which may contain function names, class names, or code. Output only the next line.
class HrApplication(SurrogatePK, TimeMixin, Model):
Given snippet: <|code_start|># -*- coding: utf-8 -*- # import flask_whooshalchemy as whooshalchemy # from sqlalchemy_searchable import make_searchable # from sqlalchemy_utils.types import TSVectorType, ScalarListType # # from sqlalchemy_searchable import SearchQueryMixin # from sqlalchemy.dialects import postgresql # make_searchable() character_apps = db.Table('app_characters', db.Column('app_id', db.Integer(), db.ForeignKey('hr_applications.id')), db.Column('character_id', db.String(), db.ForeignKey('characters.character_id'))) <|code_end|> , continue by predicting the next line. Consider current file imports: from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from sqlalchemy.orm import backref from flask_sqlalchemy import BaseQuery import datetime and context: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): which might include code, classes, or functions. Output only the next line.
class HrApplication(SurrogatePK, TimeMixin, Model):
Using the snippet: <|code_start|> comment.save() RecruitManager.comment_notify(comment) @staticmethod def create_application(form, user): application = HrApplication() application.alt_application = form.alt_application.data application.how_long = form.how_long.data application.notable_accomplishments = form.notable_accomplishments.data application.corporation_history = form.corporation_history.data application.why_leaving = form.why_leaving.data application.what_know = form.what_know.data application.what_expect = form.what_expect.data application.bought_characters = form.bought_characters.data application.why_interested = form.why_interested.data application.goon_interaction = form.goon_interaction.data application.friends = form.friends.data application.find_out = form.find_out.data application.favorite_role = form.favorite_role.data application.thesis = form.thesis.data application.scale = form.scale.data application.hidden = False application.user_id = user.id for character in form.characters.data: # The form data for characters selected is the character id <|code_end|> , determine the next line of code. You have imports: from recruit_app.user.models import EveCharacter from recruit_app.recruit.models import HrApplication, HrApplicationComment, HrApplicationCommentHistory from flask import current_app, url_for import datetime as dt import requests import re and context (class names, function names, or code) available: # Path: recruit_app/user/models.py # class EveCharacter(Model, TimeMixin): # __tablename__ = 'characters' # # character_id = Column(db.String(254), primary_key=True) # character_name = Column(db.String(254)) # corporation_id = ReferenceCol('corporations', pk_name='corporation_id', nullable=True) # corporation = relationship('EveCorporationInfo', backref='characters', foreign_keys=[corporation_id]) # # api_id = ReferenceCol('api_key_pairs', pk_name='api_id', nullable=True) # api = relationship('EveApiKeyPair', backref='characters', foreign_keys=[api_id]) # # user_id = ReferenceCol('users', nullable=True) # user = relationship('User', backref='characters', foreign_keys=[user_id]) # # skillpoints = Column(db.Integer, nullable=True) # previous_users = db.relationship('User', secondary=previous_chars, backref=db.backref('previous_chars', lazy='dynamic'), lazy='dynamic') # # def __str__(self): # return self.character_name # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # class HrApplicationCommentHistory(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comment_history' # # old_comment = Column(db.Text, nullable=True) # comment_id = ReferenceCol('hr_comments') # editor = ReferenceCol('users') # comment = relationship('HrApplicationComment', foreign_keys=[comment_id], backref=backref('hr_comment_history', cascade="delete")) # user = relationship('User', backref='hr_comment_history', foreign_keys=[editor]) # # def __repr__(self): # return str(self.editor) + " - Edited comment" . Output only the next line.
eve_character = EveCharacter.query.filter_by(character_id=character).first()
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class RecruitManager: def __init__(self): pass @staticmethod def check_if_application_owned_by_user(application_id, user): <|code_end|> , generate the next line using the imports in this file: from recruit_app.user.models import EveCharacter from recruit_app.recruit.models import HrApplication, HrApplicationComment, HrApplicationCommentHistory from flask import current_app, url_for import datetime as dt import requests import re and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/user/models.py # class EveCharacter(Model, TimeMixin): # __tablename__ = 'characters' # # character_id = Column(db.String(254), primary_key=True) # character_name = Column(db.String(254)) # corporation_id = ReferenceCol('corporations', pk_name='corporation_id', nullable=True) # corporation = relationship('EveCorporationInfo', backref='characters', foreign_keys=[corporation_id]) # # api_id = ReferenceCol('api_key_pairs', pk_name='api_id', nullable=True) # api = relationship('EveApiKeyPair', backref='characters', foreign_keys=[api_id]) # # user_id = ReferenceCol('users', nullable=True) # user = relationship('User', backref='characters', foreign_keys=[user_id]) # # skillpoints = Column(db.Integer, nullable=True) # previous_users = db.relationship('User', secondary=previous_chars, backref=db.backref('previous_chars', lazy='dynamic'), lazy='dynamic') # # def __str__(self): # return self.character_name # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # class HrApplicationCommentHistory(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comment_history' # # old_comment = Column(db.Text, nullable=True) # comment_id = ReferenceCol('hr_comments') # editor = ReferenceCol('users') # comment = relationship('HrApplicationComment', foreign_keys=[comment_id], backref=backref('hr_comment_history', cascade="delete")) # user = relationship('User', backref='hr_comment_history', foreign_keys=[editor]) # # def __repr__(self): # return str(self.editor) + " - Edited comment" . Output only the next line.
application = HrApplication.query.filter_by(id=application_id).first()
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- class RecruitManager: def __init__(self): pass @staticmethod def check_if_application_owned_by_user(application_id, user): application = HrApplication.query.filter_by(id=application_id).first() if application: if application.user_id == user.id: return True return False @staticmethod def create_comment(application, comment_data, user): <|code_end|> . Use current file imports: from recruit_app.user.models import EveCharacter from recruit_app.recruit.models import HrApplication, HrApplicationComment, HrApplicationCommentHistory from flask import current_app, url_for import datetime as dt import requests import re and context (classes, functions, or code) from other files: # Path: recruit_app/user/models.py # class EveCharacter(Model, TimeMixin): # __tablename__ = 'characters' # # character_id = Column(db.String(254), primary_key=True) # character_name = Column(db.String(254)) # corporation_id = ReferenceCol('corporations', pk_name='corporation_id', nullable=True) # corporation = relationship('EveCorporationInfo', backref='characters', foreign_keys=[corporation_id]) # # api_id = ReferenceCol('api_key_pairs', pk_name='api_id', nullable=True) # api = relationship('EveApiKeyPair', backref='characters', foreign_keys=[api_id]) # # user_id = ReferenceCol('users', nullable=True) # user = relationship('User', backref='characters', foreign_keys=[user_id]) # # skillpoints = Column(db.Integer, nullable=True) # previous_users = db.relationship('User', secondary=previous_chars, backref=db.backref('previous_chars', lazy='dynamic'), lazy='dynamic') # # def __str__(self): # return self.character_name # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # class HrApplicationCommentHistory(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comment_history' # # old_comment = Column(db.Text, nullable=True) # comment_id = ReferenceCol('hr_comments') # editor = ReferenceCol('users') # comment = relationship('HrApplicationComment', foreign_keys=[comment_id], backref=backref('hr_comment_history', cascade="delete")) # user = relationship('User', backref='hr_comment_history', foreign_keys=[editor]) # # def __repr__(self): # return str(self.editor) + " - Edited comment" . Output only the next line.
comment = HrApplicationComment()
Using the snippet: <|code_start|> class RecruitManager: def __init__(self): pass @staticmethod def check_if_application_owned_by_user(application_id, user): application = HrApplication.query.filter_by(id=application_id).first() if application: if application.user_id == user.id: return True return False @staticmethod def create_comment(application, comment_data, user): comment = HrApplicationComment() comment.application_id = application.id comment.comment = comment_data if user: comment.user_id = user.id comment.save() application.last_update_time = dt.datetime.utcnow() application.save() RecruitManager.comment_notify(comment) @staticmethod def edit_comment(comment, comment_data, user): # Save the previous version of the comment for possible future use / auditing <|code_end|> , determine the next line of code. You have imports: from recruit_app.user.models import EveCharacter from recruit_app.recruit.models import HrApplication, HrApplicationComment, HrApplicationCommentHistory from flask import current_app, url_for import datetime as dt import requests import re and context (class names, function names, or code) available: # Path: recruit_app/user/models.py # class EveCharacter(Model, TimeMixin): # __tablename__ = 'characters' # # character_id = Column(db.String(254), primary_key=True) # character_name = Column(db.String(254)) # corporation_id = ReferenceCol('corporations', pk_name='corporation_id', nullable=True) # corporation = relationship('EveCorporationInfo', backref='characters', foreign_keys=[corporation_id]) # # api_id = ReferenceCol('api_key_pairs', pk_name='api_id', nullable=True) # api = relationship('EveApiKeyPair', backref='characters', foreign_keys=[api_id]) # # user_id = ReferenceCol('users', nullable=True) # user = relationship('User', backref='characters', foreign_keys=[user_id]) # # skillpoints = Column(db.Integer, nullable=True) # previous_users = db.relationship('User', secondary=previous_chars, backref=db.backref('previous_chars', lazy='dynamic'), lazy='dynamic') # # def __str__(self): # return self.character_name # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # class HrApplicationCommentHistory(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comment_history' # # old_comment = Column(db.Text, nullable=True) # comment_id = ReferenceCol('hr_comments') # editor = ReferenceCol('users') # comment = relationship('HrApplicationComment', foreign_keys=[comment_id], backref=backref('hr_comment_history', cascade="delete")) # user = relationship('User', backref='hr_comment_history', foreign_keys=[editor]) # # def __repr__(self): # return str(self.editor) + " - Edited comment" . Output only the next line.
comment_history = HrApplicationCommentHistory()
Given the code snippet: <|code_start|> # some DBs lock after things have been dropped in # a transaction. metadata = MetaData() tbs = [] all_fks = [] for table_name in inspector.get_table_names(): fks = [] for fk in inspector.get_foreign_keys(table_name): if not fk['name']: continue fks.append( ForeignKeyConstraint((), (), name=fk['name']) ) t = Table(table_name, metadata, *fks) tbs.append(t) all_fks.extend(fks) for fkc in all_fks: db.engine.execute(DropConstraint(fkc)) for table in tbs: db.engine.execute(DropTable(table)) @pytest.yield_fixture(scope='function') def db(app): """A database for the tests.""" <|code_end|> , generate the next line using the imports in this file: import pytest from webtest import TestApp from sqlalchemy.engine import reflection from sqlalchemy.schema import ( MetaData, Table, DropTable, ForeignKeyConstraint, DropConstraint, ) from recruit_app.app import create_app from recruit_app.database import db as _db from recruit_app.settings import TestConfig from .factories import UserFactory and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): # # Path: recruit_app/settings.py # class TestConfig(Config): # ENV = 'test' # TESTING = True # DEBUG = True # BCRYPT_LOG_ROUNDS = 1 # For faster tests # WTF_CSRF_ENABLED = False # Allows form testing # ASSETS_DEBUG = True # CACHE_TYPE = 'redis' # SQLALCHEMY_DATABASE_URI = os_env.get('TEST_DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # # Path: tests/factories.py # class UserFactory(BaseFactory): # """User factory.""" # # email = Sequence(lambda n: 'user{0}@example.com'.format(n)) # password = PostGenerationMethodCall('set_password', 'example') # active = True # # class Meta: # """Factory configuration.""" # # model = User . Output only the next line.
_db.app = app
Based on the snippet: <|code_start|> t = Table(table_name, metadata, *fks) tbs.append(t) all_fks.extend(fks) for fkc in all_fks: db.engine.execute(DropConstraint(fkc)) for table in tbs: db.engine.execute(DropTable(table)) @pytest.yield_fixture(scope='function') def db(app): """A database for the tests.""" _db.app = app with app.app_context(): _db.create_all() yield _db # Explicitly close DB connection _db.session.close() drop_db(_db) _db.drop_all() @pytest.fixture def user(db): """A user for the tests.""" <|code_end|> , predict the immediate next line with the help of imports: import pytest from webtest import TestApp from sqlalchemy.engine import reflection from sqlalchemy.schema import ( MetaData, Table, DropTable, ForeignKeyConstraint, DropConstraint, ) from recruit_app.app import create_app from recruit_app.database import db as _db from recruit_app.settings import TestConfig from .factories import UserFactory and context (classes, functions, sometimes code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): # # Path: recruit_app/settings.py # class TestConfig(Config): # ENV = 'test' # TESTING = True # DEBUG = True # BCRYPT_LOG_ROUNDS = 1 # For faster tests # WTF_CSRF_ENABLED = False # Allows form testing # ASSETS_DEBUG = True # CACHE_TYPE = 'redis' # SQLALCHEMY_DATABASE_URI = os_env.get('TEST_DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # # Path: tests/factories.py # class UserFactory(BaseFactory): # """User factory.""" # # email = Sequence(lambda n: 'user{0}@example.com'.format(n)) # password = PostGenerationMethodCall('set_password', 'example') # active = True # # class Meta: # """Factory configuration.""" # # model = User . Output only the next line.
user = UserFactory(password='myprecious')
Using the snippet: <|code_start|> listen = ['high', 'medium', 'low'] redis_url = os.getenv('REDISTOGO_URL') # if not redis_url: # raise RuntimeError('Set up Redis To Go first.') if redis_url: urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password) else: conn = Redis() if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': <|code_end|> , determine the next line of code. You have imports: import os import urlparse from redis import Redis from rq import Worker, Queue, Connection from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig and context (class names, function names, or code) available: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') . Output only the next line.
app = create_app(ProdConfig)
Given the code snippet: <|code_start|> listen = ['high', 'medium', 'low'] redis_url = os.getenv('REDISTOGO_URL') # if not redis_url: # raise RuntimeError('Set up Redis To Go first.') if redis_url: urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password) else: conn = Redis() if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: <|code_end|> , generate the next line using the imports in this file: import os import urlparse from redis import Redis from rq import Worker, Queue, Connection from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') . Output only the next line.
app = create_app(DevConfig)
Using the snippet: <|code_start|> listen = ['high', 'medium', 'low'] redis_url = os.getenv('REDISTOGO_URL') # if not redis_url: # raise RuntimeError('Set up Redis To Go first.') if redis_url: urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password) else: conn = Redis() if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': <|code_end|> , determine the next line of code. You have imports: import os import urlparse from redis import Redis from rq import Worker, Queue, Connection from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig and context (class names, function names, or code) available: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') . Output only the next line.
app = create_app(ProdConfig)
Next line prediction: <|code_start|> class LoginForm(Form): email = TextField('Email', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField(label='Log In') def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.user = None def validate(self): initial_validation = super(LoginForm, self).validate() if not initial_validation: return False <|code_end|> . Use current file imports: (from flask_wtf import Form, RecaptchaField from wtforms import TextField, PasswordField, SubmitField from wtforms.validators import DataRequired from recruit_app.user.models import User from recruit_app.extensions import user_datastore from flask_security.forms import ConfirmRegisterForm, PasswordConfirmFormMixin) and context including class names, function names, or small code snippets from other files: # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: recruit_app/extensions.py . Output only the next line.
self.user = user_datastore.get_user(self.email.data)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- class BaseFactory(SQLAlchemyModelFactory): """Base factory.""" class Meta: """Factory configuration.""" abstract = True sqlalchemy_session = db.session class UserFactory(BaseFactory): """User factory.""" email = Sequence(lambda n: 'user{0}@example.com'.format(n)) password = PostGenerationMethodCall('set_password', 'example') active = True class Meta: """Factory configuration.""" <|code_end|> . Use current file imports: (from factory import Sequence, PostGenerationMethodCall from factory.alchemy import SQLAlchemyModelFactory from recruit_app.user.models import User from recruit_app.database import db) and context including class names, function names, or small code snippets from other files: # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
model = User
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class BaseFactory(SQLAlchemyModelFactory): """Base factory.""" class Meta: """Factory configuration.""" abstract = True <|code_end|> , determine the next line of code. You have imports: from factory import Sequence, PostGenerationMethodCall from factory.alchemy import SQLAlchemyModelFactory from recruit_app.user.models import User from recruit_app.database import db and context (class names, function names, or code) available: # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
sqlalchemy_session = db.session
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- class BlacklistCharacter(SurrogatePK, TimeMixin, Model): __tablename__ = 'blacklist_character' # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] name = Column(db.Unicode, nullable=True) main_name = Column(db.Unicode, nullable=True) corporation = Column(db.Unicode) alliance = Column(db.Unicode) notes = Column(db.Unicode) ip_address = Column(db.Unicode) <|code_end|> , predict the immediate next line with the help of imports: from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from flask import current_app from sqlalchemy.orm import backref import requests import datetime as dt and context (classes, functions, sometimes code) from other files: # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
creator_id = ReferenceCol('users', nullable=True)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- class BlacklistCharacter(SurrogatePK, TimeMixin, Model): __tablename__ = 'blacklist_character' # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] name = Column(db.Unicode, nullable=True) main_name = Column(db.Unicode, nullable=True) corporation = Column(db.Unicode) alliance = Column(db.Unicode) notes = Column(db.Unicode) ip_address = Column(db.Unicode) creator_id = ReferenceCol('users', nullable=True) <|code_end|> . Use current file imports: (from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from flask import current_app from sqlalchemy.orm import backref import requests import datetime as dt) and context including class names, function names, or small code snippets from other files: # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries')
Based on the snippet: <|code_start|> scheduler = Scheduler(connection=Redis()) # Get a scheduler for the "default" queue def schedule_tasks(): scheduler.schedule( scheduled_time=dt.datetime.now(), <|code_end|> , predict the immediate next line with the help of imports: from flask import current_app from redis import Redis from rq_scheduler import Scheduler from recruit_app.user.tasks import run_alliance_corp_update, run_api_key_update import datetime as dt and context (classes, functions, sometimes code) from other files: # Path: recruit_app/user/tasks.py # @job('low') # def run_alliance_corp_update(): # with current_app.app_context(): # if EveApiManager.check_if_api_server_online(): # corporations = EveCorporationInfo.query.all() # for corp in corporations: # corp_info = EveApiManager.get_corporation_information(corp.corporation_id) # if corp_info: # # Set alliance info first to set foreign key # if corp_info['alliance']['id']: # alliance_info = EveApiManager.get_alliance_information(corp_info['alliance']['id']) # if alliance_info: # if not EveAllianceInfo.query.filter_by(alliance_id=str(alliance_info['id'])).first(): # EveManager.create_alliance_info(alliance_id=alliance_info['id'], # alliance_name=alliance_info['name'], # alliance_ticker=alliance_info['ticker'], # alliance_executor_corp_id=alliance_info['executor_id'], # alliance_member_count=alliance_info['member_count']) # else: # EveManager.update_alliance_info(alliance_id=alliance_info['id'], # alliance_executor_corp_id=alliance_info['executor_id'], # alliance_member_count=alliance_info['member_count']) # EveManager.update_corporation_info(corporation_id=corp_info['id'], # corp_member_count=corp_info['members']['current'], # alliance_id=corp_info['alliance']['id']) # # @job('low') # def run_api_key_update(): # with current_app.app_context(): # # I am not proud of this block of code # if EveApiManager.check_if_api_server_online(): # api_keys = EveApiKeyPair.query.order_by(EveApiKeyPair.api_id).all() # for api_key in api_keys: # if EveApiManager.check_api_is_not_expire(api_key.api_id, api_key.api_key): # EveManager.update_api_keypair( # api_key.api_id, api_key.api_key) # current_app.logger.debug("Updating {0}".format(api_key.api_id)) # else: # current_app.logger.debug("Removing expired api_key {0} {1}".format(api_key.api_id, api_key.api_key)) # EveManager.delete_api_key_pair(api_key.api_id, None) . Output only the next line.
func=run_alliance_corp_update,
Given snippet: <|code_start|> scheduler = Scheduler(connection=Redis()) # Get a scheduler for the "default" queue def schedule_tasks(): scheduler.schedule( scheduled_time=dt.datetime.now(), func=run_alliance_corp_update, interval=21600, queue_name='low', ) scheduler.schedule( scheduled_time=dt.datetime.now(), <|code_end|> , continue by predicting the next line. Consider current file imports: from flask import current_app from redis import Redis from rq_scheduler import Scheduler from recruit_app.user.tasks import run_alliance_corp_update, run_api_key_update import datetime as dt and context: # Path: recruit_app/user/tasks.py # @job('low') # def run_alliance_corp_update(): # with current_app.app_context(): # if EveApiManager.check_if_api_server_online(): # corporations = EveCorporationInfo.query.all() # for corp in corporations: # corp_info = EveApiManager.get_corporation_information(corp.corporation_id) # if corp_info: # # Set alliance info first to set foreign key # if corp_info['alliance']['id']: # alliance_info = EveApiManager.get_alliance_information(corp_info['alliance']['id']) # if alliance_info: # if not EveAllianceInfo.query.filter_by(alliance_id=str(alliance_info['id'])).first(): # EveManager.create_alliance_info(alliance_id=alliance_info['id'], # alliance_name=alliance_info['name'], # alliance_ticker=alliance_info['ticker'], # alliance_executor_corp_id=alliance_info['executor_id'], # alliance_member_count=alliance_info['member_count']) # else: # EveManager.update_alliance_info(alliance_id=alliance_info['id'], # alliance_executor_corp_id=alliance_info['executor_id'], # alliance_member_count=alliance_info['member_count']) # EveManager.update_corporation_info(corporation_id=corp_info['id'], # corp_member_count=corp_info['members']['current'], # alliance_id=corp_info['alliance']['id']) # # @job('low') # def run_api_key_update(): # with current_app.app_context(): # # I am not proud of this block of code # if EveApiManager.check_if_api_server_online(): # api_keys = EveApiKeyPair.query.order_by(EveApiKeyPair.api_id).all() # for api_key in api_keys: # if EveApiManager.check_api_is_not_expire(api_key.api_id, api_key.api_key): # EveManager.update_api_keypair( # api_key.api_id, api_key.api_key) # current_app.logger.debug("Updating {0}".format(api_key.api_id)) # else: # current_app.logger.debug("Removing expired api_key {0} {1}".format(api_key.api_id, api_key.api_key)) # EveManager.delete_api_key_pair(api_key.api_id, None) which might include code, classes, or functions. Output only the next line.
func=run_api_key_update,
Given the code snippet: <|code_start|> except evelink.api.APIError as error: current_app.logger.error(error) return chars @staticmethod def get_corporation_ticker_from_id(corp_id): ticker = "" try: api = EveApiManager.evelink_api() corp = evelink.corp.Corp(api) response = corp.corporation_sheet(corp_id) ticker = response[0]['ticker'] except evelink.api.APIError as error: current_app.logger.error(error) return ticker @staticmethod def get_alliance_information(alliance_id): results = {} try: alliances = EveApiManager.get_alliance_info() results = alliances[0][int(alliance_id)] except evelink.api.APIError as error: current_app.logger.error(error) return results @staticmethod <|code_end|> , generate the next line using the imports in this file: import evelink.api import evelink.char import evelink.eve from flask import current_app from recruit_app.extensions import cache_extension and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/extensions.py . Output only the next line.
@cache_extension.cached(timeout=3600, key_prefix='get_alliance_info')
Next line prediction: <|code_start|> def register_admin_views(admin, db): admin.add_link(MenuLink(name='Go Back', url='/', category='')) admin.add_view(EveCharacterAdmin(EveCharacter, db.session, category='EvE')) admin.add_view(EveCorporationInfoAdmin(EveCorporationInfo, db.session, category='EvE')) <|code_end|> . Use current file imports: (from .models import EveCharacter, EveAllianceInfo, EveApiKeyPair, EveCorporationInfo, User, Role, roles_users from flask_security import current_user from recruit_app.admin import AuthenticatedModelView from wtforms import PasswordField from recruit_app.recruit.models import HrApplication, HrApplicationComment from recruit_app.blacklist.models import BlacklistCharacter from flask import url_for from flask.ext.admin.menu import MenuLink) and context including class names, function names, or small code snippets from other files: # Path: recruit_app/user/models.py # class Role(SurrogatePK, Model, RoleMixin): # class User(SurrogatePK, Model, UserMixin): # class EveCharacter(Model, TimeMixin): # class EveApiKeyPair(Model): # class EveAllianceInfo(Model): # class EveCorporationInfo(Model): # def __repr__(self): # def set_password(self, password): # def check_password(self, value): # def create(self, **kwargs): # def get_ips(self): # def __repr__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # # Path: recruit_app/admin.py # class AuthenticatedModelView(ModelView): # column_display_pk = True # # def is_accessible(self): # if current_user.has_role("admin"): # return True # return False # # def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # abort(401) # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
admin.add_view(EveAllianceInfoAdmin(EveAllianceInfo, db.session, category='EvE'))
Based on the snippet: <|code_start|> def register_admin_views(admin, db): admin.add_link(MenuLink(name='Go Back', url='/', category='')) admin.add_view(EveCharacterAdmin(EveCharacter, db.session, category='EvE')) admin.add_view(EveCorporationInfoAdmin(EveCorporationInfo, db.session, category='EvE')) admin.add_view(EveAllianceInfoAdmin(EveAllianceInfo, db.session, category='EvE')) <|code_end|> , predict the immediate next line with the help of imports: from .models import EveCharacter, EveAllianceInfo, EveApiKeyPair, EveCorporationInfo, User, Role, roles_users from flask_security import current_user from recruit_app.admin import AuthenticatedModelView from wtforms import PasswordField from recruit_app.recruit.models import HrApplication, HrApplicationComment from recruit_app.blacklist.models import BlacklistCharacter from flask import url_for from flask.ext.admin.menu import MenuLink and context (classes, functions, sometimes code) from other files: # Path: recruit_app/user/models.py # class Role(SurrogatePK, Model, RoleMixin): # class User(SurrogatePK, Model, UserMixin): # class EveCharacter(Model, TimeMixin): # class EveApiKeyPair(Model): # class EveAllianceInfo(Model): # class EveCorporationInfo(Model): # def __repr__(self): # def set_password(self, password): # def check_password(self, value): # def create(self, **kwargs): # def get_ips(self): # def __repr__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # # Path: recruit_app/admin.py # class AuthenticatedModelView(ModelView): # column_display_pk = True # # def is_accessible(self): # if current_user.has_role("admin"): # return True # return False # # def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # abort(401) # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
admin.add_view(EveApiKeyPairAdmin(EveApiKeyPair, db.session, category='EvE'))
Predict the next line for this snippet: <|code_start|> def register_admin_views(admin, db): admin.add_link(MenuLink(name='Go Back', url='/', category='')) admin.add_view(EveCharacterAdmin(EveCharacter, db.session, category='EvE')) <|code_end|> with the help of current file imports: from .models import EveCharacter, EveAllianceInfo, EveApiKeyPair, EveCorporationInfo, User, Role, roles_users from flask_security import current_user from recruit_app.admin import AuthenticatedModelView from wtforms import PasswordField from recruit_app.recruit.models import HrApplication, HrApplicationComment from recruit_app.blacklist.models import BlacklistCharacter from flask import url_for from flask.ext.admin.menu import MenuLink and context from other files: # Path: recruit_app/user/models.py # class Role(SurrogatePK, Model, RoleMixin): # class User(SurrogatePK, Model, UserMixin): # class EveCharacter(Model, TimeMixin): # class EveApiKeyPair(Model): # class EveAllianceInfo(Model): # class EveCorporationInfo(Model): # def __repr__(self): # def set_password(self, password): # def check_password(self, value): # def create(self, **kwargs): # def get_ips(self): # def __repr__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # # Path: recruit_app/admin.py # class AuthenticatedModelView(ModelView): # column_display_pk = True # # def is_accessible(self): # if current_user.has_role("admin"): # return True # return False # # def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # abort(401) # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' , which may contain function names, class names, or code. Output only the next line.
admin.add_view(EveCorporationInfoAdmin(EveCorporationInfo, db.session, category='EvE'))
Continue the code snippet: <|code_start|> def register_admin_views(admin, db): admin.add_link(MenuLink(name='Go Back', url='/', category='')) admin.add_view(EveCharacterAdmin(EveCharacter, db.session, category='EvE')) admin.add_view(EveCorporationInfoAdmin(EveCorporationInfo, db.session, category='EvE')) admin.add_view(EveAllianceInfoAdmin(EveAllianceInfo, db.session, category='EvE')) admin.add_view(EveApiKeyPairAdmin(EveApiKeyPair, db.session, category='EvE')) <|code_end|> . Use current file imports: from .models import EveCharacter, EveAllianceInfo, EveApiKeyPair, EveCorporationInfo, User, Role, roles_users from flask_security import current_user from recruit_app.admin import AuthenticatedModelView from wtforms import PasswordField from recruit_app.recruit.models import HrApplication, HrApplicationComment from recruit_app.blacklist.models import BlacklistCharacter from flask import url_for from flask.ext.admin.menu import MenuLink and context (classes, functions, or code) from other files: # Path: recruit_app/user/models.py # class Role(SurrogatePK, Model, RoleMixin): # class User(SurrogatePK, Model, UserMixin): # class EveCharacter(Model, TimeMixin): # class EveApiKeyPair(Model): # class EveAllianceInfo(Model): # class EveCorporationInfo(Model): # def __repr__(self): # def set_password(self, password): # def check_password(self, value): # def create(self, **kwargs): # def get_ips(self): # def __repr__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # # Path: recruit_app/admin.py # class AuthenticatedModelView(ModelView): # column_display_pk = True # # def is_accessible(self): # if current_user.has_role("admin"): # return True # return False # # def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # abort(401) # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
admin.add_view(UserAdmin(User, db.session, endpoint="users", category='Users'))
Continue the code snippet: <|code_start|> def register_admin_views(admin, db): admin.add_link(MenuLink(name='Go Back', url='/', category='')) admin.add_view(EveCharacterAdmin(EveCharacter, db.session, category='EvE')) admin.add_view(EveCorporationInfoAdmin(EveCorporationInfo, db.session, category='EvE')) admin.add_view(EveAllianceInfoAdmin(EveAllianceInfo, db.session, category='EvE')) admin.add_view(EveApiKeyPairAdmin(EveApiKeyPair, db.session, category='EvE')) admin.add_view(UserAdmin(User, db.session, endpoint="users", category='Users')) <|code_end|> . Use current file imports: from .models import EveCharacter, EveAllianceInfo, EveApiKeyPair, EveCorporationInfo, User, Role, roles_users from flask_security import current_user from recruit_app.admin import AuthenticatedModelView from wtforms import PasswordField from recruit_app.recruit.models import HrApplication, HrApplicationComment from recruit_app.blacklist.models import BlacklistCharacter from flask import url_for from flask.ext.admin.menu import MenuLink and context (classes, functions, or code) from other files: # Path: recruit_app/user/models.py # class Role(SurrogatePK, Model, RoleMixin): # class User(SurrogatePK, Model, UserMixin): # class EveCharacter(Model, TimeMixin): # class EveApiKeyPair(Model): # class EveAllianceInfo(Model): # class EveCorporationInfo(Model): # def __repr__(self): # def set_password(self, password): # def check_password(self, value): # def create(self, **kwargs): # def get_ips(self): # def __repr__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # # Path: recruit_app/admin.py # class AuthenticatedModelView(ModelView): # column_display_pk = True # # def is_accessible(self): # if current_user.has_role("admin"): # return True # return False # # def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # abort(401) # # Path: recruit_app/recruit/models.py # class HrApplication(SurrogatePK, TimeMixin, Model): # # query_class = HrApplicationQuery # __tablename__ = 'hr_applications' # # __searchable__ = ['thesis', # 'how_long', # 'notable_accomplishments', # 'corporation_history', # 'why_leaving', # 'what_know', # 'what_expect', # 'bought_characters', # 'why_interested', # 'find_out', # 'favorite_role', # 'main_character_name'] # # main_character_name = Column(db.Unicode, nullable=True) # # alt_application = Column(db.Boolean, default=False) # # characters = relationship('EveCharacter', secondary=character_apps, backref=db.backref('hr_applications', lazy='dynamic'), lazy='dynamic') # # thesis = Column(db.UnicodeText, nullable=True) # how_long = Column(db.Text, nullable=True) # notable_accomplishments = Column(db.Text, nullable=True) # corporation_history = Column(db.Text, nullable=True) # why_leaving = Column(db.Text, nullable=True) # what_know = Column(db.Text, nullable=True) # what_expect = Column(db.Text, nullable=True) # bought_characters = Column(db.Text, nullable=True) # why_interested = Column(db.Text, nullable=True) # # goon_interaction = Column(db.Text, nullable=True) # friends = Column(db.Text, nullable=True) # # scale = Column(db.Text, nullable=True) # # find_out = Column(db.Text, nullable=True) # # favorite_role = Column(db.Text, nullable=True) # # user_id = ReferenceCol('users', nullable=True) # reviewer_user_id = ReferenceCol('users', nullable=True) # last_user_id = ReferenceCol('users', nullable=True) # # approved_denied = Column(db.Text, default="New") # # hidden = Column(db.Boolean, nullable=True, default=False) # # # search_vector = Column(TSVectorType('main_character_name', 'thesis')) # # user = relationship('User', foreign_keys=[user_id], backref='hr_applications') # reviewer_user = relationship('User', foreign_keys=[reviewer_user_id], backref='hr_applications_reviewed') # last_action_user = relationship('User', foreign_keys=[last_user_id], backref='hr_applications_touched') # # training = Column(db.Boolean, default=False) # # def __str__(self): # return '<Application %r>' % str(self.main_character_name) # # class HrApplicationComment(SurrogatePK, TimeMixin, Model): # __tablename__ = 'hr_comments' # # comment = Column(db.Text, nullable=True) # # application_id = ReferenceCol('hr_applications') # user_id = ReferenceCol('users') # application = relationship('HrApplication', foreign_keys=[application_id], backref=backref('hr_comments', cascade="delete")) # user = relationship('User', backref='hr_comments', foreign_keys=[user_id]) # # def __repr__(self): # return str(self.user) + " - Comment" # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
admin.add_view(RoleAdmin(Role, db.session, category='Users'))
Given the code snippet: <|code_start|>#!/usr/bin/env python sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) atatime = 512 if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': <|code_end|> , generate the next line using the imports in this file: import os import sys from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig from recruit_app.blacklist.models import BlacklistCharacter as Model from flask.ext.whooshalchemy import whoosh_index and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
app = create_app(ProdConfig)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) atatime = 512 if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: <|code_end|> , predict the next line using imports from the current file: import os import sys from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig from recruit_app.blacklist.models import BlacklistCharacter as Model from flask.ext.whooshalchemy import whoosh_index and context including class names, function names, and sometimes code from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
app = create_app(DevConfig)
Continue the code snippet: <|code_start|>#!/usr/bin/env python sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) atatime = 512 if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': <|code_end|> . Use current file imports: import os import sys from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig from recruit_app.blacklist.models import BlacklistCharacter as Model from flask.ext.whooshalchemy import whoosh_index and context (classes, functions, or code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
app = create_app(ProdConfig)
Given the code snippet: <|code_start|>#!/usr/bin/env python sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) atatime = 512 if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) with app.app_context(): <|code_end|> , generate the next line using the imports in this file: import os import sys from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig from recruit_app.blacklist.models import BlacklistCharacter as Model from flask.ext.whooshalchemy import whoosh_index and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
index = whoosh_index(app, Model)
Given the code snippet: <|code_start|> with open(filename, 'w') as f: f.write(pid) if args.url is not None: connection = Redis.from_url(args.url) elif os.getenv('REDISTOGO_URL'): redis_url = os.getenv('REDISTOGO_URL') if not redis_url: raise RuntimeError('Set up Redis To Go first.') urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) connection = Redis(host=url.hostname, port=url.port, db=0, password=url.password) elif args.host is not None: connection = Redis(args.host, args.port, args.db, args.password) else: connection = Redis() if args.verbose: level = 'DEBUG' else: level = 'INFO' setup_loghandlers(level) scheduler = Scheduler(connection=connection, interval=args.interval) scheduler.run() if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': <|code_end|> , generate the next line using the imports in this file: import argparse import urlparse import sys import os from redis import Redis from rq_scheduler.scheduler import Scheduler from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig from rq.logutils import setup_loghandlers and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') . Output only the next line.
app = create_app(ProdConfig)
Based on the snippet: <|code_start|> if args.url is not None: connection = Redis.from_url(args.url) elif os.getenv('REDISTOGO_URL'): redis_url = os.getenv('REDISTOGO_URL') if not redis_url: raise RuntimeError('Set up Redis To Go first.') urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) connection = Redis(host=url.hostname, port=url.port, db=0, password=url.password) elif args.host is not None: connection = Redis(args.host, args.port, args.db, args.password) else: connection = Redis() if args.verbose: level = 'DEBUG' else: level = 'INFO' setup_loghandlers(level) scheduler = Scheduler(connection=connection, interval=args.interval) scheduler.run() if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': app = create_app(ProdConfig) else: <|code_end|> , predict the immediate next line with the help of imports: import argparse import urlparse import sys import os from redis import Redis from rq_scheduler.scheduler import Scheduler from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig from rq.logutils import setup_loghandlers and context (classes, functions, sometimes code) from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') . Output only the next line.
app = create_app(DevConfig)
Predict the next line for this snippet: <|code_start|> with open(filename, 'w') as f: f.write(pid) if args.url is not None: connection = Redis.from_url(args.url) elif os.getenv('REDISTOGO_URL'): redis_url = os.getenv('REDISTOGO_URL') if not redis_url: raise RuntimeError('Set up Redis To Go first.') urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) connection = Redis(host=url.hostname, port=url.port, db=0, password=url.password) elif args.host is not None: connection = Redis(args.host, args.port, args.db, args.password) else: connection = Redis() if args.verbose: level = 'DEBUG' else: level = 'INFO' setup_loghandlers(level) scheduler = Scheduler(connection=connection, interval=args.interval) scheduler.run() if __name__ == '__main__': if os.environ.get("RECRUIT_APP_ENV") == 'prod': <|code_end|> with the help of current file imports: import argparse import urlparse import sys import os from redis import Redis from rq_scheduler.scheduler import Scheduler from recruit_app.app import create_app from recruit_app.settings import DevConfig, ProdConfig from rq.logutils import setup_loghandlers and context from other files: # Path: recruit_app/app.py # def create_app(config_object=ProdConfig): # '''An application factory, as explained here: # http://flask.pocoo.org/docs/patterns/appfactories/ # # :param config_object: The configuration object to use. # ''' # app = Flask(__name__) # app.config.from_object(config_object) # register_extensions(app) # register_blueprints(app) # register_errorhandlers(app) # admin = Admin() # register_admin(admin, db) # # register_search(app) # admin.init_app(app) # # admin needs to be initialized oddly for tests to work. # register_tasks() # # return app # # Path: recruit_app/settings.py # class DevConfig(Config): # """Development configuration.""" # ENV = 'dev' # DEBUG = True # #DB_NAME = 'dev.db' # # Put the db file in project root # #DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) # WHOOSH_BASE = os.path.join(basedir, 'search.db') # #DEBUG_TB_ENABLED = True # ASSETS_DEBUG = True # Don't bundle/minify static assets # CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. # # class ProdConfig(Config): # """Production configuration.""" # ENV = 'prod' # DEBUG = False # SQLALCHEMY_DATABASE_URI = os_env.get('DATABASE_URL', 'postgresql://recruit@localhost:5432/recruit') # DEBUG_TB_ENABLED = False # Disable Debug toolbar # WHOOSH_BASE = os.path.join(basedir, 'search.db') , which may contain function names, class names, or code. Output only the next line.
app = create_app(ProdConfig)
Here is a snippet: <|code_start|> blueprint = Blueprint("blacklist", __name__, url_prefix='/blacklist', static_folder="../static") @blueprint.route("/", methods=['GET', 'POST']) @blueprint.route("/<int:page>/", methods=['GET', 'POST']) @login_required @roles_accepted('admin', 'recruiter', 'reviewer', 'compliance', 'blacklist') def blacklist_view(page=1): <|code_end|> . Write the next line using the current file imports: from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app from flask_security.decorators import login_required from flask_security import current_user, roles_accepted from .forms import SearchForm, BlacklistCharacterForm from .models import BlacklistCharacter from .managers import BlacklistManager and context from other files: # Path: recruit_app/blacklist/forms.py # class SearchForm(Form): # search = StringField('Search') # submit = SubmitField(label='Submit') # # class BlacklistCharacterForm(Form): # character_name = TextAreaField("Character Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # main_name = TextAreaField("Main Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # corporation = TextAreaField("Corporation", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # alliance = TextAreaField("Alliance", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # ip_address = TextAreaField("IP Address", validators=[IPAddress(), Optional()]) # notes = TextAreaField("Notes", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # # submit = SubmitField(label='Submit Entry') # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' # # Path: recruit_app/blacklist/managers.py # class BlacklistManager: # def __init__(self): # pass # # @staticmethod # def create_entry(entry_data, user): # try: # entry = BlacklistCharacter() # entry.name = entry_data.character_name.data # entry.main_name = entry_data.main_name.data # entry.corporation = entry_data.corporation.data # entry.alliance = entry_data.alliance.data # entry.ip_address = entry_data.ip_address.data # entry.notes = entry_data.notes.data # entry.creator = user # entry.save() # # return True # except: # return False , which may include functions, classes, or code. Output only the next line.
search_form = SearchForm()
Next line prediction: <|code_start|> blueprint = Blueprint("blacklist", __name__, url_prefix='/blacklist', static_folder="../static") @blueprint.route("/", methods=['GET', 'POST']) @blueprint.route("/<int:page>/", methods=['GET', 'POST']) @login_required @roles_accepted('admin', 'recruiter', 'reviewer', 'compliance', 'blacklist') def blacklist_view(page=1): search_form = SearchForm() <|code_end|> . Use current file imports: (from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app from flask_security.decorators import login_required from flask_security import current_user, roles_accepted from .forms import SearchForm, BlacklistCharacterForm from .models import BlacklistCharacter from .managers import BlacklistManager) and context including class names, function names, or small code snippets from other files: # Path: recruit_app/blacklist/forms.py # class SearchForm(Form): # search = StringField('Search') # submit = SubmitField(label='Submit') # # class BlacklistCharacterForm(Form): # character_name = TextAreaField("Character Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # main_name = TextAreaField("Main Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # corporation = TextAreaField("Corporation", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # alliance = TextAreaField("Alliance", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # ip_address = TextAreaField("IP Address", validators=[IPAddress(), Optional()]) # notes = TextAreaField("Notes", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # # submit = SubmitField(label='Submit Entry') # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' # # Path: recruit_app/blacklist/managers.py # class BlacklistManager: # def __init__(self): # pass # # @staticmethod # def create_entry(entry_data, user): # try: # entry = BlacklistCharacter() # entry.name = entry_data.character_name.data # entry.main_name = entry_data.main_name.data # entry.corporation = entry_data.corporation.data # entry.alliance = entry_data.alliance.data # entry.ip_address = entry_data.ip_address.data # entry.notes = entry_data.notes.data # entry.creator = user # entry.save() # # return True # except: # return False . Output only the next line.
blacklist_form = BlacklistCharacterForm()
Given snippet: <|code_start|> blueprint = Blueprint("blacklist", __name__, url_prefix='/blacklist', static_folder="../static") @blueprint.route("/", methods=['GET', 'POST']) @blueprint.route("/<int:page>/", methods=['GET', 'POST']) @login_required @roles_accepted('admin', 'recruiter', 'reviewer', 'compliance', 'blacklist') def blacklist_view(page=1): search_form = SearchForm() blacklist_form = BlacklistCharacterForm() blacklist = None if request.method == 'POST': if request.form['submit'] == 'Submit Entry': if current_user.has_role('admin') or current_user.has_role('compliance') or current_user.has_role('blacklist'): if blacklist_form.validate_on_submit(): if BlacklistManager.create_entry(blacklist_form, current_user): flash('Entry Added') else: flash("You don't have the proper permissions.") elif search_form.validate_on_submit() and search_form.search.data: <|code_end|> , continue by predicting the next line. Consider current file imports: from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app from flask_security.decorators import login_required from flask_security import current_user, roles_accepted from .forms import SearchForm, BlacklistCharacterForm from .models import BlacklistCharacter from .managers import BlacklistManager and context: # Path: recruit_app/blacklist/forms.py # class SearchForm(Form): # search = StringField('Search') # submit = SubmitField(label='Submit') # # class BlacklistCharacterForm(Form): # character_name = TextAreaField("Character Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # main_name = TextAreaField("Main Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # corporation = TextAreaField("Corporation", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # alliance = TextAreaField("Alliance", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # ip_address = TextAreaField("IP Address", validators=[IPAddress(), Optional()]) # notes = TextAreaField("Notes", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # # submit = SubmitField(label='Submit Entry') # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' # # Path: recruit_app/blacklist/managers.py # class BlacklistManager: # def __init__(self): # pass # # @staticmethod # def create_entry(entry_data, user): # try: # entry = BlacklistCharacter() # entry.name = entry_data.character_name.data # entry.main_name = entry_data.main_name.data # entry.corporation = entry_data.corporation.data # entry.alliance = entry_data.alliance.data # entry.ip_address = entry_data.ip_address.data # entry.notes = entry_data.notes.data # entry.creator = user # entry.save() # # return True # except: # return False which might include code, classes, or functions. Output only the next line.
blacklist = BlacklistCharacter.query.filter(
Given the code snippet: <|code_start|> blueprint = Blueprint("blacklist", __name__, url_prefix='/blacklist', static_folder="../static") @blueprint.route("/", methods=['GET', 'POST']) @blueprint.route("/<int:page>/", methods=['GET', 'POST']) @login_required @roles_accepted('admin', 'recruiter', 'reviewer', 'compliance', 'blacklist') def blacklist_view(page=1): search_form = SearchForm() blacklist_form = BlacklistCharacterForm() blacklist = None if request.method == 'POST': if request.form['submit'] == 'Submit Entry': if current_user.has_role('admin') or current_user.has_role('compliance') or current_user.has_role('blacklist'): if blacklist_form.validate_on_submit(): <|code_end|> , generate the next line using the imports in this file: from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app from flask_security.decorators import login_required from flask_security import current_user, roles_accepted from .forms import SearchForm, BlacklistCharacterForm from .models import BlacklistCharacter from .managers import BlacklistManager and context (functions, classes, or occasionally code) from other files: # Path: recruit_app/blacklist/forms.py # class SearchForm(Form): # search = StringField('Search') # submit = SubmitField(label='Submit') # # class BlacklistCharacterForm(Form): # character_name = TextAreaField("Character Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # main_name = TextAreaField("Main Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # corporation = TextAreaField("Corporation", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # alliance = TextAreaField("Alliance", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # ip_address = TextAreaField("IP Address", validators=[IPAddress(), Optional()]) # notes = TextAreaField("Notes", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) # # submit = SubmitField(label='Submit Entry') # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' # # Path: recruit_app/blacklist/managers.py # class BlacklistManager: # def __init__(self): # pass # # @staticmethod # def create_entry(entry_data, user): # try: # entry = BlacklistCharacter() # entry.name = entry_data.character_name.data # entry.main_name = entry_data.main_name.data # entry.corporation = entry_data.corporation.data # entry.alliance = entry_data.alliance.data # entry.ip_address = entry_data.ip_address.data # entry.notes = entry_data.notes.data # entry.creator = user # entry.save() # # return True # except: # return False . Output only the next line.
if BlacklistManager.create_entry(blacklist_form, current_user):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- '''Public section, including homepage and signup.''' blueprint = Blueprint('public', __name__, static_folder="../static") # @login_manager.user_loader # def load_user(id): # return User.get_by_id(int(id)) @blueprint.route("/", methods=["GET", "POST"]) def home(): <|code_end|> , determine the next line of code. You have imports: from flask import (Blueprint, request, render_template, flash, url_for, redirect, session) from flask_security.utils import login_user, logout_user from flask_security.decorators import login_required from flask_security import current_user from recruit_app.extensions import security, user_datastore from recruit_app.user.models import User from recruit_app.public.forms import LoginForm from recruit_app.utils import flash_errors from recruit_app.database import db from recruit_app.blacklist.models import BlacklistCharacter and context (class names, function names, or code) available: # Path: recruit_app/extensions.py # # Path: recruit_app/user/models.py # class User(SurrogatePK, Model, UserMixin): # __tablename__ = 'users' # # email = Column(db.String(80), unique=True, nullable=False) # #: The hashed password # password = Column(db.String(128), nullable=True) # created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # active = Column(db.Boolean(), default=False) # is_admin = Column(db.Boolean(), default=False) # # confirmed_at = Column(db.DateTime, nullable=True) # # last_login_at = Column(db.DateTime()) # current_login_at = Column(db.DateTime()) # last_login_ip = Column(db.String(100)) # current_login_ip = Column(db.String(100)) # login_count = Column(db.Integer) # # roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # # main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True) # main_character = relationship('EveCharacter', backref='user_main_character', foreign_keys=[main_character_id]) # # def set_password(self, password): # self.password = encrypt_password(password) # self.save() # # def check_password(self, value): # return verify_and_update_password(value, self) # # @classmethod # def create(self, **kwargs): # """Create a new record and save it the database.""" # instance = self(**kwargs) # if kwargs['password']: # instance.password = encrypt_password(kwargs['password']) # return instance.save() # # @property # def get_ips(self): # return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') # # def __repr__(self): # return '<User({name})>'.format(name=self.email) # # def __str__(self): # return self.email # # Path: recruit_app/public/forms.py # class LoginForm(Form): # email = TextField('Email', validators=[DataRequired()]) # password = PasswordField('Password', validators=[DataRequired()]) # submit = SubmitField(label='Log In') # # def __init__(self, *args, **kwargs): # super(LoginForm, self).__init__(*args, **kwargs) # self.user = None # # def validate(self): # initial_validation = super(LoginForm, self).validate() # if not initial_validation: # return False # # self.user = user_datastore.get_user(self.email.data) # if not self.user: # self.email.errors.append('Unknown email address') # return False # # if not self.user.check_password(self.password.data): # self.password.errors.append('Invalid password') # return False # # if not self.user.active: # self.email.errors.append('User not activated') # return False # return True # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
form = LoginForm(request.form)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('users.id')), db.Column('role_id', db.Integer(), db.ForeignKey('roles.id'))) <|code_end|> . Use current file imports: import datetime as dt from flask_security import UserMixin, RoleMixin from flask_security.utils import verify_and_update_password, encrypt_password from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin and context (classes, functions, or code) from other files: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
class Role(SurrogatePK, Model, RoleMixin):
Using the snippet: <|code_start|> class Role(SurrogatePK, Model, RoleMixin): __tablename__ = 'roles' name = Column(db.String(80), unique=True) description = db.Column(db.String(255)) def __repr__(self): return '<Role({name})>'.format(name=self.name) class User(SurrogatePK, Model, UserMixin): __tablename__ = 'users' email = Column(db.String(80), unique=True, nullable=False) #: The hashed password password = Column(db.String(128), nullable=True) created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) active = Column(db.Boolean(), default=False) is_admin = Column(db.Boolean(), default=False) confirmed_at = Column(db.DateTime, nullable=True) last_login_at = Column(db.DateTime()) current_login_at = Column(db.DateTime()) last_login_ip = Column(db.String(100)) current_login_ip = Column(db.String(100)) login_count = Column(db.Integer) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic') <|code_end|> , determine the next line of code. You have imports: import datetime as dt from flask_security import UserMixin, RoleMixin from flask_security.utils import verify_and_update_password, encrypt_password from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin and context (class names, function names, or code) available: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
main_character_id = ReferenceCol('characters', pk_name='character_id', nullable=True)
Using the snippet: <|code_start|> db.Column('role_id', db.Integer(), db.ForeignKey('roles.id'))) class Role(SurrogatePK, Model, RoleMixin): __tablename__ = 'roles' name = Column(db.String(80), unique=True) description = db.Column(db.String(255)) def __repr__(self): return '<Role({name})>'.format(name=self.name) class User(SurrogatePK, Model, UserMixin): __tablename__ = 'users' email = Column(db.String(80), unique=True, nullable=False) #: The hashed password password = Column(db.String(128), nullable=True) created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) active = Column(db.Boolean(), default=False) is_admin = Column(db.Boolean(), default=False) confirmed_at = Column(db.DateTime, nullable=True) last_login_at = Column(db.DateTime()) current_login_at = Column(db.DateTime()) last_login_ip = Column(db.String(100)) current_login_ip = Column(db.String(100)) login_count = Column(db.Integer) <|code_end|> , determine the next line of code. You have imports: import datetime as dt from flask_security import UserMixin, RoleMixin from flask_security.utils import verify_and_update_password, encrypt_password from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin and context (class names, function names, or code) available: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'), lazy='dynamic')
Given snippet: <|code_start|># -*- coding: utf-8 -*- roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('users.id')), db.Column('role_id', db.Integer(), db.ForeignKey('roles.id'))) <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime as dt from flask_security import UserMixin, RoleMixin from flask_security.utils import verify_and_update_password, encrypt_password from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin and context: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): which might include code, classes, or functions. Output only the next line.
class Role(SurrogatePK, Model, RoleMixin):
Using the snippet: <|code_start|> def set_password(self, password): self.password = encrypt_password(password) self.save() def check_password(self, value): return verify_and_update_password(value, self) @classmethod def create(self, **kwargs): """Create a new record and save it the database.""" instance = self(**kwargs) if kwargs['password']: instance.password = encrypt_password(kwargs['password']) return instance.save() @property def get_ips(self): return self.last_login_ip.split(', ') + self.current_login_ip.split(', ') def __repr__(self): return '<User({name})>'.format(name=self.email) def __str__(self): return self.email previous_chars = db.Table('previous_chars', db.Column('user_id', db.Integer(), db.ForeignKey('users.id')), db.Column('character_id', db.String(254), db.ForeignKey('characters.character_id'))) <|code_end|> , determine the next line of code. You have imports: import datetime as dt from flask_security import UserMixin, RoleMixin from flask_security.utils import verify_and_update_password, encrypt_password from recruit_app.extensions import bcrypt from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin and context (class names, function names, or code) available: # Path: recruit_app/extensions.py # # Path: recruit_app/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # class TimeMixin(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, id): # def ReferenceCol(tablename, nullable=True, pk_name='id', **kwargs): . Output only the next line.
class EveCharacter(Model, TimeMixin):
Next line prediction: <|code_start|># -*- coding: utf-8 -*- class BlacklistManager: def __init__(self): pass @staticmethod def create_entry(entry_data, user): try: <|code_end|> . Use current file imports: (from .models import BlacklistCharacter) and context including class names, function names, or small code snippets from other files: # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' . Output only the next line.
entry = BlacklistCharacter()
Continue the code snippet: <|code_start|> def register_admin_views(admin, db): admin.add_view(BlacklistCharacterAdmin(BlacklistCharacter, db.session, category='BlackList')) admin.add_view(BlacklistGSFAdmin(BlacklistGSF, db.session, name='GSF Blacklist Cache', category='BlackList')) # Useful things: column_list, column_labels, column_searchable_list, column_filters, form_columns, form_ajax_refs <|code_end|> . Use current file imports: from recruit_app.admin import AuthenticatedModelView from .models import BlacklistCharacter, BlacklistGSF and context (classes, functions, or code) from other files: # Path: recruit_app/admin.py # class AuthenticatedModelView(ModelView): # column_display_pk = True # # def is_accessible(self): # if current_user.has_role("admin"): # return True # return False # # def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # abort(401) # # Path: recruit_app/blacklist/models.py # class BlacklistCharacter(SurrogatePK, TimeMixin, Model): # __tablename__ = 'blacklist_character' # # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] # # name = Column(db.Unicode, nullable=True) # main_name = Column(db.Unicode, nullable=True) # corporation = Column(db.Unicode) # alliance = Column(db.Unicode) # notes = Column(db.Unicode) # # ip_address = Column(db.Unicode) # # creator_id = ReferenceCol('users', nullable=True) # creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') # # def __repr__(self): # return '<' + self.name + ': ' + self.notes + '>' # # class BlacklistGSF(TimeMixin, Model): # __tablename__ = 'blacklist_gsf' # # status = Column(db.Unicode) # character_id = ReferenceCol('characters', pk_name='character_id', primary_key=True) # character = relationship('EveCharacter', foreign_keys=[character_id], backref=backref('blacklist_gsf', cascade="delete")) # # @staticmethod # def getStatus(character): # try: # entry = BlacklistGSF.query.filter_by(character_id=character.character_id).one() # except: # # No entry, create a new one # entry = BlacklistGSF() # entry.character_id = character.character_id # entry.status = u'UNKNOWN' # # if entry.last_update_time is None or (dt.datetime.utcnow() - entry.last_update_time).total_seconds() > 86400: # 1 day cache # try: # url = current_app.config['GSF_BLACKLIST_URL'] + character.character_name # r = requests.post(url) # entry.status = unicode(r.json()[0]['output']) # entry.last_update_time = dt.datetime.utcnow() # except: # Will except on NONE for URL or connection issues. Just keep status as UNKNOWN # pass # # try: # entry.save() # except: # # It's possible that multiple people are viewing the same new app at the same time, causing multiple threads to make the same cache object, # # which throws an IntegrityError. In that case just ignore the error, this is just a cache anyway. # pass # # return str(entry.status) # # def __repr__(self): # return '<BlacklistCacheEntry' + ': ' + self.character_id + '>' . Output only the next line.
class BlacklistCharacterAdmin(AuthenticatedModelView):
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ Station Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ LOGGER = getLogger(__name__) <|code_end|> . Use current file imports: (from pyweed.options import Options, DateOption, FloatOption, Option from pyweed.pyweed_utils import get_preferred_origin from logging import getLogger) and context including class names, function names, or small code snippets from other files: # Path: pyweed/options.py # class Options(object, metaclass=OptionsMeta): # """ # Base class for a web service request. # """ # # def set_options(self, options): # """ # Set all the options in the given dictionary # """ # LOGGER.debug("Set options: %s", options) # for k, v in options.items(): # if k in self._options: # setattr(self, k, v) # # def get_options(self, keys=None, hidden=True, stringify=False): # """ # Return the options as a dictionary, with a few options # @param keys: only include the options named # @param hidden: if True, include options where Option.hidden is set # @param stringify: convert the option value to a string # """ # options = {} # if not keys: # keys = self.keys(hidden=hidden) # for attr in keys: # option = self._options.get(attr) # if option: # value = getattr(self, attr, None) # if value is not None: # if stringify: # options[attr] = option.to_string(value) # else: # options[attr] = value # LOGGER.debug("get_options: %s", options) # return options # # def keys(self, hidden=True): # """ # Return a list of keys # # @param hidden: if True, include options where Option.hidden is set # """ # return [key for key, option in self._options.items() if hidden or not option.hidden] # # def __setattr__(self, k, v): # if k in self._options: # v = self._options[k].to_option(v) # self.__dict__[k] = v # # def __repr__(self): # return repr(self.get_options()) # # class DateOption(Option): # """ # A date parameter. # """ # def to_option(self, value): # # Value can be a number indicating number of days relative to today # if isinstance(value, Number): # return UTCDateTime() + timedelta(days=value) # else: # return UTCDateTime(value) # # def to_string(self, value): # if hasattr(value, 'isoformat'): # return value.isoformat() # elif isinstance(value, str): # return value # else: # raise ValueError("%s is not a date" % (value,)) # # class FloatOption(Option): # """ # A floating point value # """ # def to_option(self, value): # return float(value) # # class Option(object): # """ # Defines a web service query parameter. This allows the service API to take parameter # values as Python objects, and convert them to the proper string form for the service. # """ # def __init__(self, option_name=None, default=None, hidden=False): # """ # :param options_name: The name of the option (eg. "starttime") # :param default: The default to use if no value is set # :param hidden: Indicate that this option shouldn't be included in the actual query # """ # self.option_name = option_name # self.default = default # self.hidden = hidden # # def to_option(self, value): # """ # Turn the value into a "native" option type # """ # return value # # def to_string(self, value): # return str(value) . Output only the next line.
class StationOptions(Options):
Given snippet: <|code_start|># -*- coding: utf-8 -*- """ Station Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ LOGGER = getLogger(__name__) class StationOptions(Options): TIME_RANGE = 'timeBetween' TIME_EVENTS = 'timeFromEvents' time_choice = Option(hidden=True, default=TIME_RANGE) <|code_end|> , continue by predicting the next line. Consider current file imports: from pyweed.options import Options, DateOption, FloatOption, Option from pyweed.pyweed_utils import get_preferred_origin from logging import getLogger and context: # Path: pyweed/options.py # class Options(object, metaclass=OptionsMeta): # """ # Base class for a web service request. # """ # # def set_options(self, options): # """ # Set all the options in the given dictionary # """ # LOGGER.debug("Set options: %s", options) # for k, v in options.items(): # if k in self._options: # setattr(self, k, v) # # def get_options(self, keys=None, hidden=True, stringify=False): # """ # Return the options as a dictionary, with a few options # @param keys: only include the options named # @param hidden: if True, include options where Option.hidden is set # @param stringify: convert the option value to a string # """ # options = {} # if not keys: # keys = self.keys(hidden=hidden) # for attr in keys: # option = self._options.get(attr) # if option: # value = getattr(self, attr, None) # if value is not None: # if stringify: # options[attr] = option.to_string(value) # else: # options[attr] = value # LOGGER.debug("get_options: %s", options) # return options # # def keys(self, hidden=True): # """ # Return a list of keys # # @param hidden: if True, include options where Option.hidden is set # """ # return [key for key, option in self._options.items() if hidden or not option.hidden] # # def __setattr__(self, k, v): # if k in self._options: # v = self._options[k].to_option(v) # self.__dict__[k] = v # # def __repr__(self): # return repr(self.get_options()) # # class DateOption(Option): # """ # A date parameter. # """ # def to_option(self, value): # # Value can be a number indicating number of days relative to today # if isinstance(value, Number): # return UTCDateTime() + timedelta(days=value) # else: # return UTCDateTime(value) # # def to_string(self, value): # if hasattr(value, 'isoformat'): # return value.isoformat() # elif isinstance(value, str): # return value # else: # raise ValueError("%s is not a date" % (value,)) # # class FloatOption(Option): # """ # A floating point value # """ # def to_option(self, value): # return float(value) # # class Option(object): # """ # Defines a web service query parameter. This allows the service API to take parameter # values as Python objects, and convert them to the proper string form for the service. # """ # def __init__(self, option_name=None, default=None, hidden=False): # """ # :param options_name: The name of the option (eg. "starttime") # :param default: The default to use if no value is set # :param hidden: Indicate that this option shouldn't be included in the actual query # """ # self.option_name = option_name # self.default = default # self.hidden = hidden # # def to_option(self, value): # """ # Turn the value into a "native" option type # """ # return value # # def to_string(self, value): # return str(value) which might include code, classes, or functions. Output only the next line.
starttime = DateOption(default=-30)
Next line prediction: <|code_start|> Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ LOGGER = getLogger(__name__) class StationOptions(Options): TIME_RANGE = 'timeBetween' TIME_EVENTS = 'timeFromEvents' time_choice = Option(hidden=True, default=TIME_RANGE) starttime = DateOption(default=-30) endtime = DateOption(default=0) network = Option(default="_GSN") station = Option(default="*") location = Option(default="*") channel = Option(default="?HZ") LOCATION_GLOBAL = 'locationGlobal' LOCATION_BOX = 'locationRange' LOCATION_POINT = 'locationDistanceFromPoint' LOCATION_EVENTS = 'locationDistanceFromEvents' location_choice = Option(hidden=True, default=LOCATION_GLOBAL) <|code_end|> . Use current file imports: (from pyweed.options import Options, DateOption, FloatOption, Option from pyweed.pyweed_utils import get_preferred_origin from logging import getLogger) and context including class names, function names, or small code snippets from other files: # Path: pyweed/options.py # class Options(object, metaclass=OptionsMeta): # """ # Base class for a web service request. # """ # # def set_options(self, options): # """ # Set all the options in the given dictionary # """ # LOGGER.debug("Set options: %s", options) # for k, v in options.items(): # if k in self._options: # setattr(self, k, v) # # def get_options(self, keys=None, hidden=True, stringify=False): # """ # Return the options as a dictionary, with a few options # @param keys: only include the options named # @param hidden: if True, include options where Option.hidden is set # @param stringify: convert the option value to a string # """ # options = {} # if not keys: # keys = self.keys(hidden=hidden) # for attr in keys: # option = self._options.get(attr) # if option: # value = getattr(self, attr, None) # if value is not None: # if stringify: # options[attr] = option.to_string(value) # else: # options[attr] = value # LOGGER.debug("get_options: %s", options) # return options # # def keys(self, hidden=True): # """ # Return a list of keys # # @param hidden: if True, include options where Option.hidden is set # """ # return [key for key, option in self._options.items() if hidden or not option.hidden] # # def __setattr__(self, k, v): # if k in self._options: # v = self._options[k].to_option(v) # self.__dict__[k] = v # # def __repr__(self): # return repr(self.get_options()) # # class DateOption(Option): # """ # A date parameter. # """ # def to_option(self, value): # # Value can be a number indicating number of days relative to today # if isinstance(value, Number): # return UTCDateTime() + timedelta(days=value) # else: # return UTCDateTime(value) # # def to_string(self, value): # if hasattr(value, 'isoformat'): # return value.isoformat() # elif isinstance(value, str): # return value # else: # raise ValueError("%s is not a date" % (value,)) # # class FloatOption(Option): # """ # A floating point value # """ # def to_option(self, value): # return float(value) # # class Option(object): # """ # Defines a web service query parameter. This allows the service API to take parameter # values as Python objects, and convert them to the proper string form for the service. # """ # def __init__(self, option_name=None, default=None, hidden=False): # """ # :param options_name: The name of the option (eg. "starttime") # :param default: The default to use if no value is set # :param hidden: Indicate that this option shouldn't be included in the actual query # """ # self.option_name = option_name # self.default = default # self.hidden = hidden # # def to_option(self, value): # """ # Turn the value into a "native" option type # """ # return value # # def to_string(self, value): # return str(value) . Output only the next line.
minlatitude = FloatOption(default=-90)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Station Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ LOGGER = getLogger(__name__) class StationOptions(Options): TIME_RANGE = 'timeBetween' TIME_EVENTS = 'timeFromEvents' <|code_end|> . Use current file imports: from pyweed.options import Options, DateOption, FloatOption, Option from pyweed.pyweed_utils import get_preferred_origin from logging import getLogger and context (classes, functions, or code) from other files: # Path: pyweed/options.py # class Options(object, metaclass=OptionsMeta): # """ # Base class for a web service request. # """ # # def set_options(self, options): # """ # Set all the options in the given dictionary # """ # LOGGER.debug("Set options: %s", options) # for k, v in options.items(): # if k in self._options: # setattr(self, k, v) # # def get_options(self, keys=None, hidden=True, stringify=False): # """ # Return the options as a dictionary, with a few options # @param keys: only include the options named # @param hidden: if True, include options where Option.hidden is set # @param stringify: convert the option value to a string # """ # options = {} # if not keys: # keys = self.keys(hidden=hidden) # for attr in keys: # option = self._options.get(attr) # if option: # value = getattr(self, attr, None) # if value is not None: # if stringify: # options[attr] = option.to_string(value) # else: # options[attr] = value # LOGGER.debug("get_options: %s", options) # return options # # def keys(self, hidden=True): # """ # Return a list of keys # # @param hidden: if True, include options where Option.hidden is set # """ # return [key for key, option in self._options.items() if hidden or not option.hidden] # # def __setattr__(self, k, v): # if k in self._options: # v = self._options[k].to_option(v) # self.__dict__[k] = v # # def __repr__(self): # return repr(self.get_options()) # # class DateOption(Option): # """ # A date parameter. # """ # def to_option(self, value): # # Value can be a number indicating number of days relative to today # if isinstance(value, Number): # return UTCDateTime() + timedelta(days=value) # else: # return UTCDateTime(value) # # def to_string(self, value): # if hasattr(value, 'isoformat'): # return value.isoformat() # elif isinstance(value, str): # return value # else: # raise ValueError("%s is not a date" % (value,)) # # class FloatOption(Option): # """ # A floating point value # """ # def to_option(self, value): # return float(value) # # class Option(object): # """ # Defines a web service query parameter. This allows the service API to take parameter # values as Python objects, and convert them to the proper string form for the service. # """ # def __init__(self, option_name=None, default=None, hidden=False): # """ # :param options_name: The name of the option (eg. "starttime") # :param default: The default to use if no value is set # :param hidden: Indicate that this option shouldn't be included in the actual query # """ # self.option_name = option_name # self.default = default # self.hidden = hidden # # def to_option(self, value): # """ # Turn the value into a "native" option type # """ # return value # # def to_string(self, value): # return str(value) . Output only the next line.
time_choice = Option(hidden=True, default=TIME_RANGE)
Given the code snippet: <|code_start|> This is used by the various widget methods to handle arbitrary keyword arguments by translating them into Qt setter calls. For example, passing `textAlignment=QtCore.Qt.AlignCenter` as a keyword argument will result in `widget.setTextAlignment(QtCore.Qt.AlignCenter)` """ # Look for Qt setter for any given prop name for prop, value in props.items(): setter = 'set%s%s' % (prop[:1].capitalize(), prop[1:]) if hasattr(widget, setter): try: getattr(widget, setter)(value) except Exception as e: LOGGER.error("Tried and failed to set %s: %s", prop, e) return widget def stringWidget(self, s, **props): """ Create a new item displaying the given string """ return self.applyProps(QtWidgets.QTableWidgetItem(s), **props) def numericWidget(self, i, text=None, **props): """ Create a new item displaying the given numeric value. Pass a string or a string format as `text` to customize how the number is actually displayed. The numeric value will still be used for sorting. """ if text is None: text = "%s" if '%' in text: text = text % i <|code_end|> , generate the next line using the imports in this file: from pyweed.gui.MyNumericTableWidgetItem import MyNumericTableWidgetItem from PyQt5 import QtWidgets, QtCore from logging import getLogger and context (functions, classes, or occasionally code) from other files: # Path: pyweed/gui/MyNumericTableWidgetItem.py # class MyNumericTableWidgetItem (CustomTableWidgetItemMixin, QtWidgets.QTableWidgetItem): # """ # Custom QTableWidgetItem that forces numerical sorting # # http://stackoverflow.com/questions/25533140/sorting-qtablewidget-items-numerically # """ # # def __init__(self, value, text): # super(MyNumericTableWidgetItem, self).__init__(text) # self.setData(QtCore.Qt.UserRole, value) # # def __lt__(self, other): # if (isinstance(other, MyNumericTableWidgetItem)): # selfDataValue = float(self.data(QtCore.Qt.UserRole)) # otherDataValue = float(other.data(QtCore.Qt.UserRole)) # return selfDataValue < otherDataValue # else: # return QtWidgets.QTableWidgetItem.__lt__(self, other) . Output only the next line.
return self.applyProps(MyNumericTableWidgetItem(i, text), **props)
Given snippet: <|code_start|> :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ LOGGER = getLogger(__name__) try: class EmbedIPython(RichIPythonWidget): def __init__(self, **kwarg): super(RichIPythonWidget, self).__init__() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.push(kwarg) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() except Exception as e: LOGGER.error("Failed to make IPython widget: %s", e) EmbedIPython = None <|code_end|> , continue by predicting the next line. Consider current file imports: from PyQt5 import QtWidgets from pyweed.gui.BaseDialog import BaseDialog from logging import getLogger from qtconsole.rich_ipython_widget import RichIPythonWidget from qtconsole.inprocess import QtInProcessKernelManager import sys and context: # Path: pyweed/gui/BaseDialog.py # class BaseDialog(QtWidgets.QDialog): # def __init__(self, parent=None, *args, **kwargs): # # On non-Mac platforms, a dialog with a parent will always float above the parent. We want these # # windows to be independent, so in that case remove the parent. # # (We need the parent on Mac because it allows all windows to share a menu.) # if not IS_DARWIN: # parent = None # super(BaseDialog, self).__init__(parent=parent, *args, **kwargs) # # On Linux, dialogs don't have window controls, this can be fixed by turning off that window flag # if IS_LINUX: # self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Dialog) which might include code, classes, or functions. Output only the next line.
class ConsoleDialog(BaseDialog):
Given the following code snippet before the placeholder: <|code_start|> Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) LOGGER = logging.getLogger(__name__) def load_stations(client, parameters): """ Execute one query for station metadata. This is a standalone function so we can run it in a separate thread. """ try: LOGGER.info('Loading stations: %s', get_service_url(client, 'station', parameters)) return client.get_stations(**parameters) except Exception as e: # If no results found, the client will raise an exception, we need to trap this # TODO: this should be much cleaner with a fix to https://github.com/obspy/obspy/issues/1656 if str(e).startswith("No data"): LOGGER.warning("No stations found! Your query may be too narrow.") return Inventory([], 'INTERNAL') else: raise <|code_end|> , predict the next line using imports from the current file: import logging import concurrent.futures import doctest from pyweed.signals import SignalingThread, SignalingObject from obspy.core.inventory.inventory import Inventory from pyweed.pyweed_utils import get_service_url, CancelledException, DataRequest, get_distance from PyQt5 import QtCore from pyweed.dist_from_events import get_combined_locations, CrossBorderException and context including class names, function names, and sometimes code from other files: # Path: pyweed/signals.py # class SignalingThread(QtCore.QThread): # """ # Mixin that serves to standardize how we use signals to pass information around # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # def __del__(self): # self.wait() # # class SignalingObject(QtCore.QObject): # """ # Mixin for other objects that manage threaded work, and need to signal completion # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # Path: pyweed/dist_from_events.py # def get_combined_locations(points, distance): # """ # Given a set of points and a distance, return a reasonable set of # bounding areas covering everything within that distance of any point. # """ # # Very simple implementation, try to draw a box around all points # box = LatLonBox(distance) # # if not points: # return [] # # for lat, lon in points: # box.add_point(lat, lon) # LOGGER.info("Combined points into: %s", box) # return [box] # # class CrossBorderException(Exception): # pass . Output only the next line.
class StationsLoader(SignalingThread):
Using the snippet: <|code_start|> else: self.sub_requests = [base_options] def filter_one_station(self, station): """ Filter one station from the results """ for lat, lon in self.event_locations: dist = get_distance(lat, lon, station.latitude, station.longitude) if self.distance_range['mindistance'] <= dist <= self.distance_range['maxdistance']: return True return False def process_result(self, result): """ If the request is based on distance from a set of events, we need to perform a filter after the request, since the low-level request probably overselected. """ result = super(StationsDataRequest, self).process_result(result) if isinstance(result, Inventory) and self.event_locations and self.distance_range: filtered_networks = [] for network in result: filtered_stations = [station for station in network if self.filter_one_station(station)] if filtered_stations: network.stations = filtered_stations filtered_networks.append(network) result.networks = filtered_networks return result <|code_end|> , determine the next line of code. You have imports: import logging import concurrent.futures import doctest from pyweed.signals import SignalingThread, SignalingObject from obspy.core.inventory.inventory import Inventory from pyweed.pyweed_utils import get_service_url, CancelledException, DataRequest, get_distance from PyQt5 import QtCore from pyweed.dist_from_events import get_combined_locations, CrossBorderException and context (class names, function names, or code) available: # Path: pyweed/signals.py # class SignalingThread(QtCore.QThread): # """ # Mixin that serves to standardize how we use signals to pass information around # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # def __del__(self): # self.wait() # # class SignalingObject(QtCore.QObject): # """ # Mixin for other objects that manage threaded work, and need to signal completion # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # Path: pyweed/dist_from_events.py # def get_combined_locations(points, distance): # """ # Given a set of points and a distance, return a reasonable set of # bounding areas covering everything within that distance of any point. # """ # # Very simple implementation, try to draw a box around all points # box = LatLonBox(distance) # # if not points: # return [] # # for lat, lon in points: # box.add_point(lat, lon) # LOGGER.info("Combined points into: %s", box) # return [box] # # class CrossBorderException(Exception): # pass . Output only the next line.
class StationsHandler(SignalingObject):
Predict the next line after this snippet: <|code_start|> if not future.done(): LOGGER.debug("Cancelling unexecuted future") future.cancel() def cancel(self): """ User-requested cancel """ self.done.disconnect() self.progress.disconnect() self.clearFutures() class StationsDataRequest(DataRequest): event_locations = None distance_range = None def __init__(self, client, base_options, distance_range, event_locations): """ :param client: an ObsPy FDSN client :param base_options: the basic query options (ie. from StationOptions) :param distance_range: a tuple of (min, max) if querying by distance from events :param event_locations: a list of selected event locations if querying by distance from events """ super(StationsDataRequest, self).__init__(client) if distance_range and event_locations: # Get a list of just the (lat, lon) for each event self.event_locations = list((loc[1] for loc in event_locations)) self.distance_range = distance_range try: <|code_end|> using the current file's imports: import logging import concurrent.futures import doctest from pyweed.signals import SignalingThread, SignalingObject from obspy.core.inventory.inventory import Inventory from pyweed.pyweed_utils import get_service_url, CancelledException, DataRequest, get_distance from PyQt5 import QtCore from pyweed.dist_from_events import get_combined_locations, CrossBorderException and any relevant context from other files: # Path: pyweed/signals.py # class SignalingThread(QtCore.QThread): # """ # Mixin that serves to standardize how we use signals to pass information around # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # def __del__(self): # self.wait() # # class SignalingObject(QtCore.QObject): # """ # Mixin for other objects that manage threaded work, and need to signal completion # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # Path: pyweed/dist_from_events.py # def get_combined_locations(points, distance): # """ # Given a set of points and a distance, return a reasonable set of # bounding areas covering everything within that distance of any point. # """ # # Very simple implementation, try to draw a box around all points # box = LatLonBox(distance) # # if not points: # return [] # # for lat, lon in points: # box.add_point(lat, lon) # LOGGER.info("Combined points into: %s", box) # return [box] # # class CrossBorderException(Exception): # pass . Output only the next line.
combined_locations = get_combined_locations(self.event_locations, self.distance_range['maxdistance'])
Given the code snippet: <|code_start|> class StationsDataRequest(DataRequest): event_locations = None distance_range = None def __init__(self, client, base_options, distance_range, event_locations): """ :param client: an ObsPy FDSN client :param base_options: the basic query options (ie. from StationOptions) :param distance_range: a tuple of (min, max) if querying by distance from events :param event_locations: a list of selected event locations if querying by distance from events """ super(StationsDataRequest, self).__init__(client) if distance_range and event_locations: # Get a list of just the (lat, lon) for each event self.event_locations = list((loc[1] for loc in event_locations)) self.distance_range = distance_range try: combined_locations = get_combined_locations(self.event_locations, self.distance_range['maxdistance']) self.sub_requests = [ dict( base_options, minlatitude=box.lat1, maxlatitude=box.lat2, minlongitude=box.lon1, maxlongitude=box.lon2 ) for box in combined_locations ] <|code_end|> , generate the next line using the imports in this file: import logging import concurrent.futures import doctest from pyweed.signals import SignalingThread, SignalingObject from obspy.core.inventory.inventory import Inventory from pyweed.pyweed_utils import get_service_url, CancelledException, DataRequest, get_distance from PyQt5 import QtCore from pyweed.dist_from_events import get_combined_locations, CrossBorderException and context (functions, classes, or occasionally code) from other files: # Path: pyweed/signals.py # class SignalingThread(QtCore.QThread): # """ # Mixin that serves to standardize how we use signals to pass information around # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # def __del__(self): # self.wait() # # class SignalingObject(QtCore.QObject): # """ # Mixin for other objects that manage threaded work, and need to signal completion # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # Path: pyweed/dist_from_events.py # def get_combined_locations(points, distance): # """ # Given a set of points and a distance, return a reasonable set of # bounding areas covering everything within that distance of any point. # """ # # Very simple implementation, try to draw a box around all points # box = LatLonBox(distance) # # if not points: # return [] # # for lat, lon in points: # box.add_point(lat, lon) # LOGGER.info("Combined points into: %s", box) # return [box] # # class CrossBorderException(Exception): # pass . Output only the next line.
except CrossBorderException:
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ Custom QTableWidgetItem that forces numerical sorting http://stackoverflow.com/questions/25533140/sorting-qtablewidget-items-numerically :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ <|code_end|> , determine the next line of code. You have imports: from PyQt5 import QtCore from PyQt5 import QtWidgets from pyweed.gui.TableWidget import CustomTableWidgetItemMixin and context (class names, function names, or code) available: # Path: pyweed/gui/TableWidget.py # class CustomTableWidgetItemMixin(object): # def __init__(self, *args, **kwargs): # global _next_type # _next_type += 1 # return super(CustomTableWidgetItemMixin, self).__init__(*args, **kwargs, type=_next_type) . Output only the next line.
class MyNumericTableWidgetItem (CustomTableWidgetItemMixin, QtWidgets.QTableWidgetItem):
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ Custom QTableWidgetItem that embeds an image To be inserted into the QTableWidget with setItem(). http://stackoverflow.com/questions/14365875/qt-cannot-put-an-image-in-a-table :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ <|code_end|> with the help of current file imports: from PyQt5 import QtCore, QtGui, QtWidgets from pyweed.gui.TableWidget import CustomTableWidgetItemMixin and context from other files: # Path: pyweed/gui/TableWidget.py # class CustomTableWidgetItemMixin(object): # def __init__(self, *args, **kwargs): # global _next_type # _next_type += 1 # return super(CustomTableWidgetItemMixin, self).__init__(*args, **kwargs, type=_next_type) , which may contain function names, class names, or code. Output only the next line.
class MyTableWidgetImageItem(CustomTableWidgetItemMixin, QtWidgets.QTableWidgetItem):
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Dialog showing logging information. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ <|code_end|> . Use current file imports: from pyweed.gui.BaseDialog import BaseDialog from pyweed.gui.uic import LoggingDialog from pyweed.gui.MyTextEditLoggingHandler import MyTextEditLoggingHandler from PyQt5 import QtCore import logging and context (classes, functions, or code) from other files: # Path: pyweed/gui/BaseDialog.py # class BaseDialog(QtWidgets.QDialog): # def __init__(self, parent=None, *args, **kwargs): # # On non-Mac platforms, a dialog with a parent will always float above the parent. We want these # # windows to be independent, so in that case remove the parent. # # (We need the parent on Mac because it allows all windows to share a menu.) # if not IS_DARWIN: # parent = None # super(BaseDialog, self).__init__(parent=parent, *args, **kwargs) # # On Linux, dialogs don't have window controls, this can be fixed by turning off that window flag # if IS_LINUX: # self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Dialog) # # Path: pyweed/gui/uic/LoggingDialog.py # class Ui_LoggingDialog(object): # def setupUi(self, LoggingDialog): # def retranslateUi(self, LoggingDialog): # # Path: pyweed/gui/MyTextEditLoggingHandler.py # class MyTextEditLoggingHandler(logging.Handler): # def __init__(self, signal=None): # super(MyTextEditLoggingHandler, self).__init__(logging.INFO) # self.signal = signal # # def emit(self, record): # msg = self.format(record) # self.signal.emit(msg) . Output only the next line.
class LoggingDialog(BaseDialog, LoggingDialog.Ui_LoggingDialog):
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Dialog showing logging information. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ <|code_end|> , generate the next line using the imports in this file: from pyweed.gui.BaseDialog import BaseDialog from pyweed.gui.uic import LoggingDialog from pyweed.gui.MyTextEditLoggingHandler import MyTextEditLoggingHandler from PyQt5 import QtCore import logging and context (functions, classes, or occasionally code) from other files: # Path: pyweed/gui/BaseDialog.py # class BaseDialog(QtWidgets.QDialog): # def __init__(self, parent=None, *args, **kwargs): # # On non-Mac platforms, a dialog with a parent will always float above the parent. We want these # # windows to be independent, so in that case remove the parent. # # (We need the parent on Mac because it allows all windows to share a menu.) # if not IS_DARWIN: # parent = None # super(BaseDialog, self).__init__(parent=parent, *args, **kwargs) # # On Linux, dialogs don't have window controls, this can be fixed by turning off that window flag # if IS_LINUX: # self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Dialog) # # Path: pyweed/gui/uic/LoggingDialog.py # class Ui_LoggingDialog(object): # def setupUi(self, LoggingDialog): # def retranslateUi(self, LoggingDialog): # # Path: pyweed/gui/MyTextEditLoggingHandler.py # class MyTextEditLoggingHandler(logging.Handler): # def __init__(self, signal=None): # super(MyTextEditLoggingHandler, self).__init__(logging.INFO) # self.signal = signal # # def emit(self, record): # msg = self.format(record) # self.signal.emit(msg) . Output only the next line.
class LoggingDialog(BaseDialog, LoggingDialog.Ui_LoggingDialog):
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ Dialog showing logging information. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ class LoggingDialog(BaseDialog, LoggingDialog.Ui_LoggingDialog): """ Dialog window displaying all logs. """ append = QtCore.pyqtSignal(str) def __init__(self, parent=None): super(LoggingDialog, self).__init__(parent=parent) self.setupUi(self) self.setWindowTitle('Logs') # Initialize loggingPlainTextEdit self.loggingPlainTextEdit.setReadOnly(True) # Add a widget logging handler to the logger <|code_end|> , predict the next line using imports from the current file: from pyweed.gui.BaseDialog import BaseDialog from pyweed.gui.uic import LoggingDialog from pyweed.gui.MyTextEditLoggingHandler import MyTextEditLoggingHandler from PyQt5 import QtCore import logging and context including class names, function names, and sometimes code from other files: # Path: pyweed/gui/BaseDialog.py # class BaseDialog(QtWidgets.QDialog): # def __init__(self, parent=None, *args, **kwargs): # # On non-Mac platforms, a dialog with a parent will always float above the parent. We want these # # windows to be independent, so in that case remove the parent. # # (We need the parent on Mac because it allows all windows to share a menu.) # if not IS_DARWIN: # parent = None # super(BaseDialog, self).__init__(parent=parent, *args, **kwargs) # # On Linux, dialogs don't have window controls, this can be fixed by turning off that window flag # if IS_LINUX: # self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Dialog) # # Path: pyweed/gui/uic/LoggingDialog.py # class Ui_LoggingDialog(object): # def setupUi(self, LoggingDialog): # def retranslateUi(self, LoggingDialog): # # Path: pyweed/gui/MyTextEditLoggingHandler.py # class MyTextEditLoggingHandler(logging.Handler): # def __init__(self, signal=None): # super(MyTextEditLoggingHandler, self).__init__(logging.INFO) # self.signal = signal # # def emit(self, record): # msg = self.format(record) # self.signal.emit(msg) . Output only the next line.
loggingHandler = MyTextEditLoggingHandler(signal=self.append)
Given the following code snippet before the placeholder: <|code_start|> Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) LOGGER = logging.getLogger(__name__) def load_events(client, parameters): """ Execute one query for event data. This is a standalone function so we can run it in a separate thread. """ try: LOGGER.info('Loading events: %s', get_service_url(client, 'event', parameters)) return client.get_events(**parameters) except Exception as e: # If no results found, the client will raise an exception, we need to trap this # TODO: this should be much cleaner with a fix to https://github.com/obspy/obspy/issues/1656 if str(e).startswith("No data"): LOGGER.warning("No events found! Your query may be too narrow.") return Catalog() else: raise <|code_end|> , predict the next line using imports from the current file: from pyweed.signals import SignalingThread, SignalingObject from obspy.core.event.catalog import Catalog from pyweed.pyweed_utils import get_service_url, CancelledException from PyQt5 import QtCore import logging import concurrent.futures import doctest and context including class names, function names, and sometimes code from other files: # Path: pyweed/signals.py # class SignalingThread(QtCore.QThread): # """ # Mixin that serves to standardize how we use signals to pass information around # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # def __del__(self): # self.wait() # # class SignalingObject(QtCore.QObject): # """ # Mixin for other objects that manage threaded work, and need to signal completion # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) . Output only the next line.
class EventsLoader(SignalingThread):
Given the following code snippet before the placeholder: <|code_start|> self.progress.emit() except Exception: self.progress.emit() self.futures = {} if not catalog: catalog = Catalog() LOGGER.info("Loader processing") catalog = self.request.process_result(catalog) LOGGER.info("Loader done") self.done.emit(catalog) def clearFutures(self): """ Cancel any outstanding tasks """ if self.futures: for future in self.futures: if not future.done(): LOGGER.debug("Cancelling unexecuted future") future.cancel() def cancel(self): """ User-requested cancel """ self.done.disconnect() self.progress.disconnect() self.clearFutures() <|code_end|> , predict the next line using imports from the current file: from pyweed.signals import SignalingThread, SignalingObject from obspy.core.event.catalog import Catalog from pyweed.pyweed_utils import get_service_url, CancelledException from PyQt5 import QtCore import logging import concurrent.futures import doctest and context including class names, function names, and sometimes code from other files: # Path: pyweed/signals.py # class SignalingThread(QtCore.QThread): # """ # Mixin that serves to standardize how we use signals to pass information around # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # def __del__(self): # self.wait() # # class SignalingObject(QtCore.QObject): # """ # Mixin for other objects that manage threaded work, and need to signal completion # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) . Output only the next line.
class EventsHandler(SignalingObject):
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Event Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ <|code_end|> , generate the next line using the imports in this file: from pyweed.options import Options, DateOption, FloatOption, Option and context (functions, classes, or occasionally code) from other files: # Path: pyweed/options.py # class Options(object, metaclass=OptionsMeta): # """ # Base class for a web service request. # """ # # def set_options(self, options): # """ # Set all the options in the given dictionary # """ # LOGGER.debug("Set options: %s", options) # for k, v in options.items(): # if k in self._options: # setattr(self, k, v) # # def get_options(self, keys=None, hidden=True, stringify=False): # """ # Return the options as a dictionary, with a few options # @param keys: only include the options named # @param hidden: if True, include options where Option.hidden is set # @param stringify: convert the option value to a string # """ # options = {} # if not keys: # keys = self.keys(hidden=hidden) # for attr in keys: # option = self._options.get(attr) # if option: # value = getattr(self, attr, None) # if value is not None: # if stringify: # options[attr] = option.to_string(value) # else: # options[attr] = value # LOGGER.debug("get_options: %s", options) # return options # # def keys(self, hidden=True): # """ # Return a list of keys # # @param hidden: if True, include options where Option.hidden is set # """ # return [key for key, option in self._options.items() if hidden or not option.hidden] # # def __setattr__(self, k, v): # if k in self._options: # v = self._options[k].to_option(v) # self.__dict__[k] = v # # def __repr__(self): # return repr(self.get_options()) # # class DateOption(Option): # """ # A date parameter. # """ # def to_option(self, value): # # Value can be a number indicating number of days relative to today # if isinstance(value, Number): # return UTCDateTime() + timedelta(days=value) # else: # return UTCDateTime(value) # # def to_string(self, value): # if hasattr(value, 'isoformat'): # return value.isoformat() # elif isinstance(value, str): # return value # else: # raise ValueError("%s is not a date" % (value,)) # # class FloatOption(Option): # """ # A floating point value # """ # def to_option(self, value): # return float(value) # # class Option(object): # """ # Defines a web service query parameter. This allows the service API to take parameter # values as Python objects, and convert them to the proper string form for the service. # """ # def __init__(self, option_name=None, default=None, hidden=False): # """ # :param options_name: The name of the option (eg. "starttime") # :param default: The default to use if no value is set # :param hidden: Indicate that this option shouldn't be included in the actual query # """ # self.option_name = option_name # self.default = default # self.hidden = hidden # # def to_option(self, value): # """ # Turn the value into a "native" option type # """ # return value # # def to_string(self, value): # return str(value) . Output only the next line.
class EventOptions(Options):
Given snippet: <|code_start|># -*- coding: utf-8 -*- """ Event Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ class EventOptions(Options): TIME_RANGE = 'timeBetween' TIME_STATIONS = 'timeFromStations' time_choice = Option(hidden=True, default=TIME_RANGE) <|code_end|> , continue by predicting the next line. Consider current file imports: from pyweed.options import Options, DateOption, FloatOption, Option and context: # Path: pyweed/options.py # class Options(object, metaclass=OptionsMeta): # """ # Base class for a web service request. # """ # # def set_options(self, options): # """ # Set all the options in the given dictionary # """ # LOGGER.debug("Set options: %s", options) # for k, v in options.items(): # if k in self._options: # setattr(self, k, v) # # def get_options(self, keys=None, hidden=True, stringify=False): # """ # Return the options as a dictionary, with a few options # @param keys: only include the options named # @param hidden: if True, include options where Option.hidden is set # @param stringify: convert the option value to a string # """ # options = {} # if not keys: # keys = self.keys(hidden=hidden) # for attr in keys: # option = self._options.get(attr) # if option: # value = getattr(self, attr, None) # if value is not None: # if stringify: # options[attr] = option.to_string(value) # else: # options[attr] = value # LOGGER.debug("get_options: %s", options) # return options # # def keys(self, hidden=True): # """ # Return a list of keys # # @param hidden: if True, include options where Option.hidden is set # """ # return [key for key, option in self._options.items() if hidden or not option.hidden] # # def __setattr__(self, k, v): # if k in self._options: # v = self._options[k].to_option(v) # self.__dict__[k] = v # # def __repr__(self): # return repr(self.get_options()) # # class DateOption(Option): # """ # A date parameter. # """ # def to_option(self, value): # # Value can be a number indicating number of days relative to today # if isinstance(value, Number): # return UTCDateTime() + timedelta(days=value) # else: # return UTCDateTime(value) # # def to_string(self, value): # if hasattr(value, 'isoformat'): # return value.isoformat() # elif isinstance(value, str): # return value # else: # raise ValueError("%s is not a date" % (value,)) # # class FloatOption(Option): # """ # A floating point value # """ # def to_option(self, value): # return float(value) # # class Option(object): # """ # Defines a web service query parameter. This allows the service API to take parameter # values as Python objects, and convert them to the proper string form for the service. # """ # def __init__(self, option_name=None, default=None, hidden=False): # """ # :param options_name: The name of the option (eg. "starttime") # :param default: The default to use if no value is set # :param hidden: Indicate that this option shouldn't be included in the actual query # """ # self.option_name = option_name # self.default = default # self.hidden = hidden # # def to_option(self, value): # """ # Turn the value into a "native" option type # """ # return value # # def to_string(self, value): # return str(value) which might include code, classes, or functions. Output only the next line.
starttime = DateOption(default=-30)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ Event Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ class EventOptions(Options): TIME_RANGE = 'timeBetween' TIME_STATIONS = 'timeFromStations' time_choice = Option(hidden=True, default=TIME_RANGE) starttime = DateOption(default=-30) endtime = DateOption(default=0) <|code_end|> with the help of current file imports: from pyweed.options import Options, DateOption, FloatOption, Option and context from other files: # Path: pyweed/options.py # class Options(object, metaclass=OptionsMeta): # """ # Base class for a web service request. # """ # # def set_options(self, options): # """ # Set all the options in the given dictionary # """ # LOGGER.debug("Set options: %s", options) # for k, v in options.items(): # if k in self._options: # setattr(self, k, v) # # def get_options(self, keys=None, hidden=True, stringify=False): # """ # Return the options as a dictionary, with a few options # @param keys: only include the options named # @param hidden: if True, include options where Option.hidden is set # @param stringify: convert the option value to a string # """ # options = {} # if not keys: # keys = self.keys(hidden=hidden) # for attr in keys: # option = self._options.get(attr) # if option: # value = getattr(self, attr, None) # if value is not None: # if stringify: # options[attr] = option.to_string(value) # else: # options[attr] = value # LOGGER.debug("get_options: %s", options) # return options # # def keys(self, hidden=True): # """ # Return a list of keys # # @param hidden: if True, include options where Option.hidden is set # """ # return [key for key, option in self._options.items() if hidden or not option.hidden] # # def __setattr__(self, k, v): # if k in self._options: # v = self._options[k].to_option(v) # self.__dict__[k] = v # # def __repr__(self): # return repr(self.get_options()) # # class DateOption(Option): # """ # A date parameter. # """ # def to_option(self, value): # # Value can be a number indicating number of days relative to today # if isinstance(value, Number): # return UTCDateTime() + timedelta(days=value) # else: # return UTCDateTime(value) # # def to_string(self, value): # if hasattr(value, 'isoformat'): # return value.isoformat() # elif isinstance(value, str): # return value # else: # raise ValueError("%s is not a date" % (value,)) # # class FloatOption(Option): # """ # A floating point value # """ # def to_option(self, value): # return float(value) # # class Option(object): # """ # Defines a web service query parameter. This allows the service API to take parameter # values as Python objects, and convert them to the proper string form for the service. # """ # def __init__(self, option_name=None, default=None, hidden=False): # """ # :param options_name: The name of the option (eg. "starttime") # :param default: The default to use if no value is set # :param hidden: Indicate that this option shouldn't be included in the actual query # """ # self.option_name = option_name # self.default = default # self.hidden = hidden # # def to_option(self, value): # """ # Turn the value into a "native" option type # """ # return value # # def to_string(self, value): # return str(value) , which may contain function names, class names, or code. Output only the next line.
minmagnitude = FloatOption(default=5.0)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ Event Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ class EventOptions(Options): TIME_RANGE = 'timeBetween' TIME_STATIONS = 'timeFromStations' <|code_end|> . Use current file imports: (from pyweed.options import Options, DateOption, FloatOption, Option) and context including class names, function names, or small code snippets from other files: # Path: pyweed/options.py # class Options(object, metaclass=OptionsMeta): # """ # Base class for a web service request. # """ # # def set_options(self, options): # """ # Set all the options in the given dictionary # """ # LOGGER.debug("Set options: %s", options) # for k, v in options.items(): # if k in self._options: # setattr(self, k, v) # # def get_options(self, keys=None, hidden=True, stringify=False): # """ # Return the options as a dictionary, with a few options # @param keys: only include the options named # @param hidden: if True, include options where Option.hidden is set # @param stringify: convert the option value to a string # """ # options = {} # if not keys: # keys = self.keys(hidden=hidden) # for attr in keys: # option = self._options.get(attr) # if option: # value = getattr(self, attr, None) # if value is not None: # if stringify: # options[attr] = option.to_string(value) # else: # options[attr] = value # LOGGER.debug("get_options: %s", options) # return options # # def keys(self, hidden=True): # """ # Return a list of keys # # @param hidden: if True, include options where Option.hidden is set # """ # return [key for key, option in self._options.items() if hidden or not option.hidden] # # def __setattr__(self, k, v): # if k in self._options: # v = self._options[k].to_option(v) # self.__dict__[k] = v # # def __repr__(self): # return repr(self.get_options()) # # class DateOption(Option): # """ # A date parameter. # """ # def to_option(self, value): # # Value can be a number indicating number of days relative to today # if isinstance(value, Number): # return UTCDateTime() + timedelta(days=value) # else: # return UTCDateTime(value) # # def to_string(self, value): # if hasattr(value, 'isoformat'): # return value.isoformat() # elif isinstance(value, str): # return value # else: # raise ValueError("%s is not a date" % (value,)) # # class FloatOption(Option): # """ # A floating point value # """ # def to_option(self, value): # return float(value) # # class Option(object): # """ # Defines a web service query parameter. This allows the service API to take parameter # values as Python objects, and convert them to the proper string form for the service. # """ # def __init__(self, option_name=None, default=None, hidden=False): # """ # :param options_name: The name of the option (eg. "starttime") # :param default: The default to use if no value is set # :param hidden: Indicate that this option shouldn't be included in the actual query # """ # self.option_name = option_name # self.default = default # self.hidden = hidden # # def to_option(self, value): # """ # Turn the value into a "native" option type # """ # return value # # def to_string(self, value): # return str(value) . Output only the next line.
time_choice = Option(hidden=True, default=TIME_RANGE)
Using the snippet: <|code_start|> # Resize the subplot to a hard size, because otherwise it will do it inconsistently h.subplots_adjust(bottom=.2, left=.1, right=.95, top=.95) # Remove the title for c in h.get_children(): if isinstance(c, matplotlib.text.Text): c.remove() # Save with transparency h.savefig(imageFile) matplotlib.pyplot.close(h) waveform.check_files() except Exception as e: # Most common error is "no data" TODO: see https://github.com/obspy/obspy/issues/1656 if str(e).startswith("No data"): waveform.error = NO_DATA_ERROR # Deselect when no data available waveform.keep = False else: waveform.error = str(e) # Reraise the exception to signal an error to the caller raise finally: # Mark as finished loading waveform.loading = False return True <|code_end|> , determine the next line of code. You have imports: import os import collections import obspy import matplotlib import weakref import concurrent.futures import doctest from obspy import UTCDateTime from pyweed.signals import SignalingThread, SignalingObject from PyQt5 import QtCore, QtGui from logging import getLogger from pyweed.pyweed_utils import get_sncl, get_event_id, TimeWindow,\ get_preferred_origin, get_preferred_magnitude, OUTPUT_FORMAT_EXTENSIONS,\ get_event_description, get_arrivals, format_time_str, get_distance, get_service_url, CancelledException from obspy.core.util.attribdict import AttribDict from obspy.io.sac.sactrace import SACTrace from obspy.core.stream import Stream and context (class names, function names, or code) available: # Path: pyweed/signals.py # class SignalingThread(QtCore.QThread): # """ # Mixin that serves to standardize how we use signals to pass information around # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # def __del__(self): # self.wait() # # class SignalingObject(QtCore.QObject): # """ # Mixin for other objects that manage threaded work, and need to signal completion # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) . Output only the next line.
class WaveformsLoader(SignalingThread):
Predict the next line after this snippet: <|code_start|> for result in concurrent.futures.as_completed(self.futures): waveform_id = self.futures.get(result) if waveform_id: LOGGER.debug("Loader finished: %s", waveform_id) try: self.progress.emit(WaveformResult(waveform_id, result.result())) except Exception as e: self.progress.emit(WaveformResult(waveform_id, e)) self.futures = {} self.done.emit(None) def clearFutures(self): """ Cancel any outstanding tasks """ if self.futures: for future in self.futures: if not future.done(): LOGGER.debug("Cancelling unexecuted future") future.cancel() def cancel(self): """ User-requested cancel """ self.done.disconnect() self.progress.disconnect() self.clearFutures() <|code_end|> using the current file's imports: import os import collections import obspy import matplotlib import weakref import concurrent.futures import doctest from obspy import UTCDateTime from pyweed.signals import SignalingThread, SignalingObject from PyQt5 import QtCore, QtGui from logging import getLogger from pyweed.pyweed_utils import get_sncl, get_event_id, TimeWindow,\ get_preferred_origin, get_preferred_magnitude, OUTPUT_FORMAT_EXTENSIONS,\ get_event_description, get_arrivals, format_time_str, get_distance, get_service_url, CancelledException from obspy.core.util.attribdict import AttribDict from obspy.io.sac.sactrace import SACTrace from obspy.core.stream import Stream and any relevant context from other files: # Path: pyweed/signals.py # class SignalingThread(QtCore.QThread): # """ # Mixin that serves to standardize how we use signals to pass information around # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) # # def __del__(self): # self.wait() # # class SignalingObject(QtCore.QObject): # """ # Mixin for other objects that manage threaded work, and need to signal completion # """ # # Signal to indicate success # done = QtCore.pyqtSignal(object) . Output only the next line.
class WaveformsHandler(SignalingObject):
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Preferences dialog :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ LOGGER = getLogger(__name__) <|code_end|> . Use current file imports: from PyQt5 import QtWidgets from pyweed.gui.uic import PreferencesDialog from logging import getLogger from obspy.clients.fdsn.header import URL_MAPPINGS from pyweed.preferences import safe_int from pyweed.gui.Adapters import ComboBoxAdapter and context (classes, functions, or code) from other files: # Path: pyweed/gui/uic/PreferencesDialog.py # class Ui_PreferencesDialog(object): # def setupUi(self, PreferencesDialog): # def retranslateUi(self, PreferencesDialog): # # Path: pyweed/preferences.py # def safe_int(s, default=0): # try: # return int(s) # except: # return default # # Path: pyweed/gui/Adapters.py # class ComboBoxAdapter(QtCore.QObject): # """ # Adapter for handling the fact that QComboBox can only display strings, but usually the "real" value # is something else. # """ # # #: Signal emitted when the QComboBox value changes, passing the actual value # changed = QtCore.pyqtSignal(object) # # def __init__(self, comboBox, options, default=None): # """ # :param comboBox: A QComboBox # :param options: A list of options in the form of (value, label) # :param default: If nothing is selected, what should be returned? # """ # super(ComboBoxAdapter, self).__init__() # self.comboBox = comboBox # self.values = [option[0] for option in options] # if default is None: # default = self.values[0] # self.default = default # labels = [option[1] for option in options] # self.comboBox.addItems(labels) # self.comboBox.currentIndexChanged.connect(self.onChanged) # # def setValue(self, value): # self.comboBox.setCurrentIndex(self.values.index(value)) # # def getValue(self, index=None): # if index is None: # index = self.comboBox.currentIndex() # if index < 0: # return self.default # else: # return self.values[index] # # @pyqtSlot(int) # def onChanged(self, index): # self.changed.emit(self.getValue(index)) . Output only the next line.
class PreferencesDialog(QtWidgets.QDialog, PreferencesDialog.Ui_PreferencesDialog):
Predict the next line for this snippet: <|code_start|> # Ordered list of all available data centers dcs = sorted(URL_MAPPINGS.keys()) self.eventDataCenterAdapter = ComboBoxAdapter( self.eventDataCenterComboBox, [(dc, URL_MAPPINGS[dc]) for dc in dcs] ) self.stationDataCenterAdapter = ComboBoxAdapter( self.stationDataCenterComboBox, [(dc, URL_MAPPINGS[dc]) for dc in dcs] ) self.okButton.pressed.connect(self.accept) self.cancelButton.pressed.connect(self.reject) def showEvent(self, *args, **kwargs): """ Perform any necessary initialization each time the dialog is opened """ super(PreferencesDialog, self).showEvent(*args, **kwargs) # Indicate the currently selected data centers self.eventDataCenterAdapter.setValue( self.pyweed.event_data_center ) self.stationDataCenterAdapter.setValue( self.pyweed.station_data_center ) self.cacheSizeSpinBox.setValue( <|code_end|> with the help of current file imports: from PyQt5 import QtWidgets from pyweed.gui.uic import PreferencesDialog from logging import getLogger from obspy.clients.fdsn.header import URL_MAPPINGS from pyweed.preferences import safe_int from pyweed.gui.Adapters import ComboBoxAdapter and context from other files: # Path: pyweed/gui/uic/PreferencesDialog.py # class Ui_PreferencesDialog(object): # def setupUi(self, PreferencesDialog): # def retranslateUi(self, PreferencesDialog): # # Path: pyweed/preferences.py # def safe_int(s, default=0): # try: # return int(s) # except: # return default # # Path: pyweed/gui/Adapters.py # class ComboBoxAdapter(QtCore.QObject): # """ # Adapter for handling the fact that QComboBox can only display strings, but usually the "real" value # is something else. # """ # # #: Signal emitted when the QComboBox value changes, passing the actual value # changed = QtCore.pyqtSignal(object) # # def __init__(self, comboBox, options, default=None): # """ # :param comboBox: A QComboBox # :param options: A list of options in the form of (value, label) # :param default: If nothing is selected, what should be returned? # """ # super(ComboBoxAdapter, self).__init__() # self.comboBox = comboBox # self.values = [option[0] for option in options] # if default is None: # default = self.values[0] # self.default = default # labels = [option[1] for option in options] # self.comboBox.addItems(labels) # self.comboBox.currentIndexChanged.connect(self.onChanged) # # def setValue(self, value): # self.comboBox.setCurrentIndex(self.values.index(value)) # # def getValue(self, index=None): # if index is None: # index = self.comboBox.currentIndex() # if index < 0: # return self.default # else: # return self.values[index] # # @pyqtSlot(int) # def onChanged(self, index): # self.changed.emit(self.getValue(index)) , which may contain function names, class names, or code. Output only the next line.
safe_int(self.pyweed.preferences.Waveforms.cacheSize, 10)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ Preferences dialog :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ LOGGER = getLogger(__name__) class PreferencesDialog(QtWidgets.QDialog, PreferencesDialog.Ui_PreferencesDialog): """ Dialog window for editing preferences. """ def __init__(self, pyweed, parent=None): super(PreferencesDialog, self).__init__(parent=parent) self.setupUi(self) self.pyweed = pyweed # Ordered list of all available data centers dcs = sorted(URL_MAPPINGS.keys()) <|code_end|> , predict the immediate next line with the help of imports: from PyQt5 import QtWidgets from pyweed.gui.uic import PreferencesDialog from logging import getLogger from obspy.clients.fdsn.header import URL_MAPPINGS from pyweed.preferences import safe_int from pyweed.gui.Adapters import ComboBoxAdapter and context (classes, functions, sometimes code) from other files: # Path: pyweed/gui/uic/PreferencesDialog.py # class Ui_PreferencesDialog(object): # def setupUi(self, PreferencesDialog): # def retranslateUi(self, PreferencesDialog): # # Path: pyweed/preferences.py # def safe_int(s, default=0): # try: # return int(s) # except: # return default # # Path: pyweed/gui/Adapters.py # class ComboBoxAdapter(QtCore.QObject): # """ # Adapter for handling the fact that QComboBox can only display strings, but usually the "real" value # is something else. # """ # # #: Signal emitted when the QComboBox value changes, passing the actual value # changed = QtCore.pyqtSignal(object) # # def __init__(self, comboBox, options, default=None): # """ # :param comboBox: A QComboBox # :param options: A list of options in the form of (value, label) # :param default: If nothing is selected, what should be returned? # """ # super(ComboBoxAdapter, self).__init__() # self.comboBox = comboBox # self.values = [option[0] for option in options] # if default is None: # default = self.values[0] # self.default = default # labels = [option[1] for option in options] # self.comboBox.addItems(labels) # self.comboBox.currentIndexChanged.connect(self.onChanged) # # def setValue(self, value): # self.comboBox.setCurrentIndex(self.values.index(value)) # # def getValue(self, index=None): # if index is None: # index = self.comboBox.currentIndex() # if index < 0: # return self.default # else: # return self.values[index] # # @pyqtSlot(int) # def onChanged(self, index): # self.changed.emit(self.getValue(index)) . Output only the next line.
self.eventDataCenterAdapter = ComboBoxAdapter(