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
#... | 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 sessi... | 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... | 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 li... | 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']
conf... | 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(Transc... | 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 = DefaultC... | 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|>
, predic... | 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,... | 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,... | 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
... | 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_c... | 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'... | 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, ... | 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... | 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_... | 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.... | 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 ... | 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
de... | 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 wit... | 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(HrApplicationCommentHistor... | 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',
... | 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|>
, predi... | 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§ion=login&do=process'
r = s.post(url, data=payload, verify=True)
... | 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 im... | @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 impo... | 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()
<|co... | 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 = SQLAlch... | 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.dia... | 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)
cha... | 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 HrAp... | 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.dia... | 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
... | 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
... | 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 Eve... | 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:
... | 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 == ... | 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[... | _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(... | 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=... | 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, ... | 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=... | 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__(*ar... | 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 = ... | 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, PostGenerationMet... | 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 = Co... | 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 = Co... | 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
f... | 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... | 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 = evel... | @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_... | 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'))
adm... | 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 EveChar... | 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(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(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_ap... | 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 ... | 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
fr... | 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_contex... | 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(... | 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(... | 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:
rai... | 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', 're... | 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', ... | 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', 'review... | 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'... | 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"])
d... | 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 fl... | 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):
... | 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}... | 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:... | 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... | 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, functio... | 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... | 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.optio... | 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'
... | 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 = O... | 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 = 'timeB... | 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(QtCo... | 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(RichIPy... | 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 lo... | 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.... | 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.prog... | 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 option... | 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/... | 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 Less... | 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.BaseDia... | 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... | 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, Log... | 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 lo... | 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")
ca... | 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... | 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'... | 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_STAT... | 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 = 'timeFromSt... | 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.Te... | 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:
... | 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 PyQt... | 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]
)
se... | 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, PreferencesDi... | self.eventDataCenterAdapter = ComboBoxAdapter( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.