Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
# SQLite in Python will complain if you try to use it from multiple threads.
# We create a threadlocal variable that contains the DB, lazily initialized.
osquery_mock_db = threading.local()
def assemble_configuration(node):
configuration = {}
configuration['options'] = assemble_options(node)
configuration['file_paths'] = assemble_file_paths(node)
configuration['schedule'] = assemble_schedule(node)
configuration['packs'] = assemble_packs(node)
return configuration
def assemble_options(node):
options = {}
# https://github.com/facebook/osquery/issues/2048#issuecomment-219200524
if current_app.config['DOORMAN_EXPECTS_UNIQUE_HOST_ID']:
options['host_identifier'] = 'uuid'
else:
options['host_identifier'] = 'hostname'
options['schedule_splay_percent'] = 10
return options
def assemble_file_paths(node):
file_paths = {}
<|code_end|>
, predict the next line using imports from the current file:
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
DistributedQuery, DistributedQueryTask,
Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
and context including class names, function names, and sometimes code from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
# def __init__(self, value, **kwargs):
# def __repr__(self):
# def packs_count(self):
# def nodes_count(self):
# def queries_count(self):
# def file_paths_count(self):
# def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
# version=None, description=None, value=None, removed=True,
# shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, name, platform=None, version=None,
# description=None, shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, host_identifier, node_key=None,
# enroll_secret=None, enrolled_on=None, last_checkin=None,
# is_active=True, last_ip=None,
# **kwargs):
# def __repr__(self):
# def get_config(self, **kwargs):
# def get_new_queries(self, **kwargs):
# def display_name(self):
# def packs(self):
# def queries(self):
# def file_paths(self):
# def to_dict(self):
# def __init__(self, category=None, target_paths=None, *args, **kwargs):
# def to_dict(self):
# def get_paths(self):
# def set_paths(self, *target_paths):
# def __init__(self, name=None, action=None, columns=None, timestamp=None,
# node=None, node_id=None, **kwargs):
# def __table_args__(cls):
# def __init__(self, line=None, message=None, severity=None,
# filename=None, created=None, node=None, node_id=None,
# version=None, **kwargs):
# def __table_args__(cls):
# def __init___(self, sql, description=None, not_before=None):
# def __init__(self, node=None, node_id=None,
# distributed_query=None, distributed_query_id=None):
# def __table_args__(cls):
# def __init__(self, columns, distributed_query=None, distributed_query_task=None):
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# def template(self):
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# def set_password(self, password):
# def check_password(self, value):
# NEW = 0
# PENDING = 1
# COMPLETE = 2
# FAILED = 3
. Output only the next line. | for file_path in node.file_paths.options(db.lazyload('*')): |
Predict the next line after this snippet: <|code_start|> for file_path in node.file_paths.options(db.lazyload('*')):
file_paths.update(file_path.to_dict())
return file_paths
def assemble_schedule(node):
schedule = {}
for query in node.queries.options(db.lazyload('*')):
schedule[query.name] = query.to_dict()
return schedule
def assemble_packs(node):
packs = {}
for pack in node.packs.join(querypacks).join(Query) \
.options(db.contains_eager(Pack.queries)).all():
packs[pack.name] = pack.to_dict()
return packs
def assemble_distributed_queries(node):
'''
Retrieve all distributed queries assigned to a particular node
in the NEW state. This function will change the state of the
distributed query to PENDING, however will not commit the change.
It is the responsibility of the caller to commit or rollback on the
current database session.
'''
now = dt.datetime.utcnow()
query = db.session.query(DistributedQueryTask) \
<|code_end|>
using the current file's imports:
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
DistributedQuery, DistributedQueryTask,
Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
and any relevant context from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
# def __init__(self, value, **kwargs):
# def __repr__(self):
# def packs_count(self):
# def nodes_count(self):
# def queries_count(self):
# def file_paths_count(self):
# def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
# version=None, description=None, value=None, removed=True,
# shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, name, platform=None, version=None,
# description=None, shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, host_identifier, node_key=None,
# enroll_secret=None, enrolled_on=None, last_checkin=None,
# is_active=True, last_ip=None,
# **kwargs):
# def __repr__(self):
# def get_config(self, **kwargs):
# def get_new_queries(self, **kwargs):
# def display_name(self):
# def packs(self):
# def queries(self):
# def file_paths(self):
# def to_dict(self):
# def __init__(self, category=None, target_paths=None, *args, **kwargs):
# def to_dict(self):
# def get_paths(self):
# def set_paths(self, *target_paths):
# def __init__(self, name=None, action=None, columns=None, timestamp=None,
# node=None, node_id=None, **kwargs):
# def __table_args__(cls):
# def __init__(self, line=None, message=None, severity=None,
# filename=None, created=None, node=None, node_id=None,
# version=None, **kwargs):
# def __table_args__(cls):
# def __init___(self, sql, description=None, not_before=None):
# def __init__(self, node=None, node_id=None,
# distributed_query=None, distributed_query_id=None):
# def __table_args__(cls):
# def __init__(self, columns, distributed_query=None, distributed_query_task=None):
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# def template(self):
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# def set_password(self, password):
# def check_password(self, value):
# NEW = 0
# PENDING = 1
# COMPLETE = 2
# FAILED = 3
. Output only the next line. | .join(DistributedQuery) \ |
Predict the next line after this snippet: <|code_start|> file_paths = {}
for file_path in node.file_paths.options(db.lazyload('*')):
file_paths.update(file_path.to_dict())
return file_paths
def assemble_schedule(node):
schedule = {}
for query in node.queries.options(db.lazyload('*')):
schedule[query.name] = query.to_dict()
return schedule
def assemble_packs(node):
packs = {}
for pack in node.packs.join(querypacks).join(Query) \
.options(db.contains_eager(Pack.queries)).all():
packs[pack.name] = pack.to_dict()
return packs
def assemble_distributed_queries(node):
'''
Retrieve all distributed queries assigned to a particular node
in the NEW state. This function will change the state of the
distributed query to PENDING, however will not commit the change.
It is the responsibility of the caller to commit or rollback on the
current database session.
'''
now = dt.datetime.utcnow()
<|code_end|>
using the current file's imports:
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
DistributedQuery, DistributedQueryTask,
Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
and any relevant context from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
# def __init__(self, value, **kwargs):
# def __repr__(self):
# def packs_count(self):
# def nodes_count(self):
# def queries_count(self):
# def file_paths_count(self):
# def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
# version=None, description=None, value=None, removed=True,
# shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, name, platform=None, version=None,
# description=None, shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, host_identifier, node_key=None,
# enroll_secret=None, enrolled_on=None, last_checkin=None,
# is_active=True, last_ip=None,
# **kwargs):
# def __repr__(self):
# def get_config(self, **kwargs):
# def get_new_queries(self, **kwargs):
# def display_name(self):
# def packs(self):
# def queries(self):
# def file_paths(self):
# def to_dict(self):
# def __init__(self, category=None, target_paths=None, *args, **kwargs):
# def to_dict(self):
# def get_paths(self):
# def set_paths(self, *target_paths):
# def __init__(self, name=None, action=None, columns=None, timestamp=None,
# node=None, node_id=None, **kwargs):
# def __table_args__(cls):
# def __init__(self, line=None, message=None, severity=None,
# filename=None, created=None, node=None, node_id=None,
# version=None, **kwargs):
# def __table_args__(cls):
# def __init___(self, sql, description=None, not_before=None):
# def __init__(self, node=None, node_id=None,
# distributed_query=None, distributed_query_id=None):
# def __table_args__(cls):
# def __init__(self, columns, distributed_query=None, distributed_query_task=None):
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# def template(self):
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# def set_password(self, password):
# def check_password(self, value):
# NEW = 0
# PENDING = 1
# COMPLETE = 2
# FAILED = 3
. Output only the next line. | query = db.session.query(DistributedQueryTask) \ |
Predict the next line for this snippet: <|code_start|> map(itemgetter(0),
current_app.config['DOORMAN_CAPTURE_NODE_INFO']
)
)
if not capture_columns:
return
node_info = node.get('node_info', {})
orig_node_info = node_info.copy()
for _, action, columns, _, in extract_results(result):
# only update columns common to both sets
for column in capture_columns & set(columns):
cvalue = node_info.get(column) # current value
value = columns.get(column)
if action == 'removed' and (cvalue is None or cvalue != value):
pass
elif action == 'removed' and cvalue == value:
node_info.pop(column)
elif action == 'added' and (cvalue is None or cvalue != value):
node_info[column] = value
# only update node_info if there's actually a change
if orig_node_info == node_info:
return
<|code_end|>
with the help of current file imports:
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
DistributedQuery, DistributedQueryTask,
Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
and context from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
# def __init__(self, value, **kwargs):
# def __repr__(self):
# def packs_count(self):
# def nodes_count(self):
# def queries_count(self):
# def file_paths_count(self):
# def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
# version=None, description=None, value=None, removed=True,
# shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, name, platform=None, version=None,
# description=None, shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, host_identifier, node_key=None,
# enroll_secret=None, enrolled_on=None, last_checkin=None,
# is_active=True, last_ip=None,
# **kwargs):
# def __repr__(self):
# def get_config(self, **kwargs):
# def get_new_queries(self, **kwargs):
# def display_name(self):
# def packs(self):
# def queries(self):
# def file_paths(self):
# def to_dict(self):
# def __init__(self, category=None, target_paths=None, *args, **kwargs):
# def to_dict(self):
# def get_paths(self):
# def set_paths(self, *target_paths):
# def __init__(self, name=None, action=None, columns=None, timestamp=None,
# node=None, node_id=None, **kwargs):
# def __table_args__(cls):
# def __init__(self, line=None, message=None, severity=None,
# filename=None, created=None, node=None, node_id=None,
# version=None, **kwargs):
# def __table_args__(cls):
# def __init___(self, sql, description=None, not_before=None):
# def __init__(self, node=None, node_id=None,
# distributed_query=None, distributed_query_id=None):
# def __table_args__(cls):
# def __init__(self, columns, distributed_query=None, distributed_query_task=None):
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# def template(self):
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# def set_password(self, password):
# def check_password(self, value):
# NEW = 0
# PENDING = 1
# COMPLETE = 2
# FAILED = 3
, which may contain function names, class names, or code. Output only the next line. | node = Node.get_by_id(node['id']) |
Using the snippet: <|code_start|>def assemble_options(node):
options = {}
# https://github.com/facebook/osquery/issues/2048#issuecomment-219200524
if current_app.config['DOORMAN_EXPECTS_UNIQUE_HOST_ID']:
options['host_identifier'] = 'uuid'
else:
options['host_identifier'] = 'hostname'
options['schedule_splay_percent'] = 10
return options
def assemble_file_paths(node):
file_paths = {}
for file_path in node.file_paths.options(db.lazyload('*')):
file_paths.update(file_path.to_dict())
return file_paths
def assemble_schedule(node):
schedule = {}
for query in node.queries.options(db.lazyload('*')):
schedule[query.name] = query.to_dict()
return schedule
def assemble_packs(node):
packs = {}
for pack in node.packs.join(querypacks).join(Query) \
<|code_end|>
, determine the next line of code. You have imports:
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
DistributedQuery, DistributedQueryTask,
Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
and context (class names, function names, or code) available:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
# def __init__(self, value, **kwargs):
# def __repr__(self):
# def packs_count(self):
# def nodes_count(self):
# def queries_count(self):
# def file_paths_count(self):
# def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
# version=None, description=None, value=None, removed=True,
# shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, name, platform=None, version=None,
# description=None, shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, host_identifier, node_key=None,
# enroll_secret=None, enrolled_on=None, last_checkin=None,
# is_active=True, last_ip=None,
# **kwargs):
# def __repr__(self):
# def get_config(self, **kwargs):
# def get_new_queries(self, **kwargs):
# def display_name(self):
# def packs(self):
# def queries(self):
# def file_paths(self):
# def to_dict(self):
# def __init__(self, category=None, target_paths=None, *args, **kwargs):
# def to_dict(self):
# def get_paths(self):
# def set_paths(self, *target_paths):
# def __init__(self, name=None, action=None, columns=None, timestamp=None,
# node=None, node_id=None, **kwargs):
# def __table_args__(cls):
# def __init__(self, line=None, message=None, severity=None,
# filename=None, created=None, node=None, node_id=None,
# version=None, **kwargs):
# def __table_args__(cls):
# def __init___(self, sql, description=None, not_before=None):
# def __init__(self, node=None, node_id=None,
# distributed_query=None, distributed_query_id=None):
# def __table_args__(cls):
# def __init__(self, columns, distributed_query=None, distributed_query_task=None):
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# def template(self):
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# def set_password(self, password):
# def check_password(self, value):
# NEW = 0
# PENDING = 1
# COMPLETE = 2
# FAILED = 3
. Output only the next line. | .options(db.contains_eager(Pack.queries)).all(): |
Given snippet: <|code_start|>
def assemble_options(node):
options = {}
# https://github.com/facebook/osquery/issues/2048#issuecomment-219200524
if current_app.config['DOORMAN_EXPECTS_UNIQUE_HOST_ID']:
options['host_identifier'] = 'uuid'
else:
options['host_identifier'] = 'hostname'
options['schedule_splay_percent'] = 10
return options
def assemble_file_paths(node):
file_paths = {}
for file_path in node.file_paths.options(db.lazyload('*')):
file_paths.update(file_path.to_dict())
return file_paths
def assemble_schedule(node):
schedule = {}
for query in node.queries.options(db.lazyload('*')):
schedule[query.name] = query.to_dict()
return schedule
def assemble_packs(node):
packs = {}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
DistributedQuery, DistributedQueryTask,
Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
and context:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
# def __init__(self, value, **kwargs):
# def __repr__(self):
# def packs_count(self):
# def nodes_count(self):
# def queries_count(self):
# def file_paths_count(self):
# def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
# version=None, description=None, value=None, removed=True,
# shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, name, platform=None, version=None,
# description=None, shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, host_identifier, node_key=None,
# enroll_secret=None, enrolled_on=None, last_checkin=None,
# is_active=True, last_ip=None,
# **kwargs):
# def __repr__(self):
# def get_config(self, **kwargs):
# def get_new_queries(self, **kwargs):
# def display_name(self):
# def packs(self):
# def queries(self):
# def file_paths(self):
# def to_dict(self):
# def __init__(self, category=None, target_paths=None, *args, **kwargs):
# def to_dict(self):
# def get_paths(self):
# def set_paths(self, *target_paths):
# def __init__(self, name=None, action=None, columns=None, timestamp=None,
# node=None, node_id=None, **kwargs):
# def __table_args__(cls):
# def __init__(self, line=None, message=None, severity=None,
# filename=None, created=None, node=None, node_id=None,
# version=None, **kwargs):
# def __table_args__(cls):
# def __init___(self, sql, description=None, not_before=None):
# def __init__(self, node=None, node_id=None,
# distributed_query=None, distributed_query_id=None):
# def __table_args__(cls):
# def __init__(self, columns, distributed_query=None, distributed_query_task=None):
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# def template(self):
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# def set_password(self, password):
# def check_password(self, value):
# NEW = 0
# PENDING = 1
# COMPLETE = 2
# FAILED = 3
which might include code, classes, or functions. Output only the next line. | for pack in node.packs.join(querypacks).join(Query) \ |
Given snippet: <|code_start|> for _, action, columns, _, in extract_results(result):
# only update columns common to both sets
for column in capture_columns & set(columns):
cvalue = node_info.get(column) # current value
value = columns.get(column)
if action == 'removed' and (cvalue is None or cvalue != value):
pass
elif action == 'removed' and cvalue == value:
node_info.pop(column)
elif action == 'added' and (cvalue is None or cvalue != value):
node_info[column] = value
# only update node_info if there's actually a change
if orig_node_info == node_info:
return
node = Node.get_by_id(node['id'])
node.update(node_info=node_info)
return
def process_result(result, node):
if not result['data']:
current_app.logger.error("No results to process from %s", node)
return
for name, action, columns, timestamp, in extract_results(result):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
DistributedQuery, DistributedQueryTask,
Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
and context:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
# def __init__(self, value, **kwargs):
# def __repr__(self):
# def packs_count(self):
# def nodes_count(self):
# def queries_count(self):
# def file_paths_count(self):
# def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
# version=None, description=None, value=None, removed=True,
# shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, name, platform=None, version=None,
# description=None, shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, host_identifier, node_key=None,
# enroll_secret=None, enrolled_on=None, last_checkin=None,
# is_active=True, last_ip=None,
# **kwargs):
# def __repr__(self):
# def get_config(self, **kwargs):
# def get_new_queries(self, **kwargs):
# def display_name(self):
# def packs(self):
# def queries(self):
# def file_paths(self):
# def to_dict(self):
# def __init__(self, category=None, target_paths=None, *args, **kwargs):
# def to_dict(self):
# def get_paths(self):
# def set_paths(self, *target_paths):
# def __init__(self, name=None, action=None, columns=None, timestamp=None,
# node=None, node_id=None, **kwargs):
# def __table_args__(cls):
# def __init__(self, line=None, message=None, severity=None,
# filename=None, created=None, node=None, node_id=None,
# version=None, **kwargs):
# def __table_args__(cls):
# def __init___(self, sql, description=None, not_before=None):
# def __init__(self, node=None, node_id=None,
# distributed_query=None, distributed_query_id=None):
# def __table_args__(cls):
# def __init__(self, columns, distributed_query=None, distributed_query_task=None):
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# def template(self):
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# def set_password(self, password):
# def check_password(self, value):
# NEW = 0
# PENDING = 1
# COMPLETE = 2
# FAILED = 3
which might include code, classes, or functions. Output only the next line. | yield ResultLog(name=name, |
Given snippet: <|code_start|>
def assemble_options(node):
options = {}
# https://github.com/facebook/osquery/issues/2048#issuecomment-219200524
if current_app.config['DOORMAN_EXPECTS_UNIQUE_HOST_ID']:
options['host_identifier'] = 'uuid'
else:
options['host_identifier'] = 'hostname'
options['schedule_splay_percent'] = 10
return options
def assemble_file_paths(node):
file_paths = {}
for file_path in node.file_paths.options(db.lazyload('*')):
file_paths.update(file_path.to_dict())
return file_paths
def assemble_schedule(node):
schedule = {}
for query in node.queries.options(db.lazyload('*')):
schedule[query.name] = query.to_dict()
return schedule
def assemble_packs(node):
packs = {}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
DistributedQuery, DistributedQueryTask,
Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
and context:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
# def __init__(self, value, **kwargs):
# def __repr__(self):
# def packs_count(self):
# def nodes_count(self):
# def queries_count(self):
# def file_paths_count(self):
# def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
# version=None, description=None, value=None, removed=True,
# shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, name, platform=None, version=None,
# description=None, shard=None, **kwargs):
# def __repr__(self):
# def to_dict(self):
# def __init__(self, host_identifier, node_key=None,
# enroll_secret=None, enrolled_on=None, last_checkin=None,
# is_active=True, last_ip=None,
# **kwargs):
# def __repr__(self):
# def get_config(self, **kwargs):
# def get_new_queries(self, **kwargs):
# def display_name(self):
# def packs(self):
# def queries(self):
# def file_paths(self):
# def to_dict(self):
# def __init__(self, category=None, target_paths=None, *args, **kwargs):
# def to_dict(self):
# def get_paths(self):
# def set_paths(self, *target_paths):
# def __init__(self, name=None, action=None, columns=None, timestamp=None,
# node=None, node_id=None, **kwargs):
# def __table_args__(cls):
# def __init__(self, line=None, message=None, severity=None,
# filename=None, created=None, node=None, node_id=None,
# version=None, **kwargs):
# def __table_args__(cls):
# def __init___(self, sql, description=None, not_before=None):
# def __init__(self, node=None, node_id=None,
# distributed_query=None, distributed_query_id=None):
# def __table_args__(cls):
# def __init__(self, columns, distributed_query=None, distributed_query_task=None):
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# def template(self):
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# def set_password(self, password):
# def check_password(self, value):
# NEW = 0
# PENDING = 1
# COMPLETE = 2
# FAILED = 3
which might include code, classes, or functions. Output only the next line. | for pack in node.packs.join(querypacks).join(Query) \ |
Here is a snippet: <|code_start|> db.session.add(self)
if commit:
db.session.commit()
return self
def delete(self, commit=True):
"""Remove the record from the database."""
db.session.delete(self)
return commit and db.session.commit()
class Model(CRUDMixin, db.Model):
"""Base model class that includes CRUD convenience methods."""
__abstract__ = True
# From Mike Bayer's "Building the app" talk
# https://speakerdeck.com/zzzeek/building-the-app
class SurrogatePK(object):
"""A mixin that adds a surrogate integer 'primary key' column named ``id`` to any declarative-mapped class."""
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
@classmethod
def get_by_id(cls, record_id):
"""Get record by ID."""
if any(
<|code_end|>
. Write the next line using the current file imports:
from sqlalchemy.dialects.postgresql import ARRAY, JSONB, INET # noqa
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import relationship
from doorman.compat import basestring
from doorman.extensions import db
and context from other files:
# Path: doorman/compat.py
# PY2 = int(sys.version[0]) == 2
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# class metaclass(meta):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
, which may include functions, classes, or code. Output only the next line. | (isinstance(record_id, basestring) and record_id.isdigit(), |
Predict the next line after this snippet: <|code_start|> )
response = provider.get('https://www.googleapis.com/oauth2/v1/userinfo')
userinfo = response.json()
if not userinfo:
current_app.logger.error("No userinfo object returned!")
abort(500)
current_app.logger.debug("Got userinfo: %s", userinfo)
if self.allowed_users and userinfo['email'] not in self.allowed_users:
current_app.logger.error("%s is not authorized for this application",
userinfo['email'])
flash(u"{0} is not authorized for this application.".format(
userinfo['email']), 'danger')
abort(401)
if self.allowed_domains and userinfo['hd'] not in self.allowed_domains:
current_app.logger.error("%s domain and %s not authorized",
userinfo['hd'], userinfo['email'])
flash(u"{0} is not authorized for this application.".format(
userinfo['email']), 'danger')
abort(401)
if not userinfo['verified_email']:
flash(u"You must verify your email before using this application.",
'danger')
abort(401)
<|code_end|>
using the current file's imports:
from flask import abort, current_app, flash, request, session, url_for
from requests_oauthlib import OAuth2Session
from doorman.models import User
and any relevant context from other files:
# Path: doorman/models.py
# class User(UserMixin, SurrogatePK, Model):
#
# username = Column(db.String(80), unique=True, nullable=False)
# email = Column(db.String)
#
# password = Column(db.String, nullable=True)
# created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# # oauth related stuff
# social_id = Column(db.String)
# first_name = Column(db.String)
# last_name = Column(db.String)
#
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# self.username = username
# self.email = email
# if password:
# self.set_password(password)
# else:
# self.password = None
#
# self.social_id = social_id
# self.first_name = first_name
# self.last_name = last_name
#
# def set_password(self, password):
# self.update(password=bcrypt.generate_password_hash(password))
# return
#
# def check_password(self, value):
# if not self.password:
# # still do the computation
# return bcrypt.generate_password_hash(value) and False
# return bcrypt.check_password_hash(self.password, value)
. Output only the next line. | user = User.query.filter_by( |
Given the following code snippet before the placeholder: <|code_start|> params.update(node)
params.update(node.get('node_info', {}))
params.update(match.result['columns'])
subject = string.Template(
render_template(
subject_template,
prefix=subject_prefix,
match=match,
timestamp=dt.datetime.utcnow(),
node=node
)
).safe_substitute(**params)
body = string.Template(
render_template(
message_template,
match=match,
timestamp=dt.datetime.utcnow(),
node=node
)
).safe_substitute(**params)
message = Message(
subject.strip(),
recipients=self.recipients,
body=body,
charset='utf-8',
)
<|code_end|>
, predict the next line using imports from the current file:
import datetime as dt
import string
from flask import render_template
from flask_mail import Message
from doorman.extensions import mail
from .base import AbstractAlerterPlugin
and context including class names, function names, and sometimes code from other files:
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/plugins/alerters/base.py
# class AbstractAlerterPlugin(with_metaclass(ABCMeta)):
# """
# AbstractAlerterPlugin is the base class for all alerters in Doorman. It
# defines the interface that an alerter should implement in order to support
# sending an alert.
# """
# @abstractmethod
# def handle_alert(self, node, match):
# raise NotImplementedError()
. Output only the next line. | return mail.send(message) |
Given snippet: <|code_start|> return User.get_by_id(int(user_id))
@ldap_manager.save_user
def save_user(dn, username, userdata, memberships):
user = User.query.filter_by(username=username).first()
kwargs = {}
kwargs['username'] = username
if 'givenName' in userdata:
kwargs['first_name'] = userdata['givenName'][0]
if 'sn' in userdata:
kwargs['last_name'] = userdata['sn'][0]
return user.update(**kwargs) if user else User.create(**kwargs)
@blueprint.route('/login', methods=['GET', 'POST'])
def login():
next = request.args.get('next', url_for('manage.index'))
if current_user and current_user.is_authenticated:
return safe_redirect(next, url_for('manage.index'))
if current_app.config['DOORMAN_AUTH_METHOD'] not in (None, 'doorman', 'ldap'):
authorization_url = current_app.oauth_provider.get_authorize_url()
current_app.logger.debug("Redirecting user to %s", authorization_url)
return redirect(authorization_url)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from urlparse import urlparse, urljoin
from urllib.parse import urlparse, urljoin
from flask import (
Blueprint, abort, current_app, flash, redirect, render_template,
request, session, url_for
)
from flask_login import current_user, login_user, logout_user, COOKIE_NAME
from oauthlib.oauth2 import OAuth2Error
from .forms import LoginForm
from doorman.extensions import csrf, ldap_manager, login_manager
from doorman.models import User
from doorman.utils import flash_errors
from doorman.users.mixins import NoAuthUserMixin
and context:
# Path: doorman/users/forms.py
# class LoginForm(Form):
#
# username = StringField('Username', validators=[DataRequired()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember me', validators=[Optional()])
#
# def __init__(self, *args, **kwargs):
# """Create instance."""
# super(LoginForm, self).__init__(*args, **kwargs)
# self.user = None
#
# def validate(self):
# initial_validation = super(LoginForm, self).validate()
# if not initial_validation:
# return False
#
# error_message = u'Invalid username or password.'
#
# if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman':
# self.user = User.query.filter_by(username=self.username.data).first()
#
# if not self.user:
# from doorman.extensions import bcrypt
# # avoid timing leaks
# bcrypt.generate_password_hash(self.password.data)
# self.username.errors.append(error_message)
# return False
#
# if not self.user.check_password(self.password.data):
# self.username.errors.append(error_message)
# return False
#
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap':
# result = ldap_manager.authenticate(
# self.username.data,
# self.password.data
# )
#
# if result.status == AuthenticationResponseStatus.fail:
# self.username.errors.append(error_message)
# return False
#
# self.user = ldap_manager._save_user(
# result.user_dn,
# result.user_id,
# result.user_info,
# result.user_groups
# )
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] is None:
# return True
#
# return False
#
# @property
# def auth_method(self):
# return current_app.config['DOORMAN_AUTH_METHOD']
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/models.py
# class User(UserMixin, SurrogatePK, Model):
#
# username = Column(db.String(80), unique=True, nullable=False)
# email = Column(db.String)
#
# password = Column(db.String, nullable=True)
# created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# # oauth related stuff
# social_id = Column(db.String)
# first_name = Column(db.String)
# last_name = Column(db.String)
#
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# self.username = username
# self.email = email
# if password:
# self.set_password(password)
# else:
# self.password = None
#
# self.social_id = social_id
# self.first_name = first_name
# self.last_name = last_name
#
# def set_password(self, password):
# self.update(password=bcrypt.generate_password_hash(password))
# return
#
# def check_password(self, value):
# if not self.password:
# # still do the computation
# return bcrypt.generate_password_hash(value) and False
# return bcrypt.check_password_hash(self.password, value)
#
# Path: doorman/utils.py
# def flash_errors(form):
# '''http://flask.pocoo.org/snippets/12/'''
# for field, errors in form.errors.items():
# for error in errors:
# message = u"Error in the {0} field - {1}".format(
# getattr(form, field).label.text, error
# )
# flash(message, 'danger')
which might include code, classes, or functions. Output only the next line. | form = LoginForm() |
Given snippet: <|code_start|> flash(u'Invalid username or password.', 'danger')
return render_template('login.html', form=form)
@blueprint.route('/logout')
def logout():
username = getattr(current_user, 'username', None)
oauth = False
logout_user()
# clear any oauth state
for key in ('_oauth_state', '_oauth_token'):
oauth |= not not session.pop(key, None)
response = redirect(url_for('users.login'))
if username and not oauth:
flash(u"You have successfully logged out.", "info")
current_app.logger.info("%s logged out", username)
# explicitly log the user out, and clear their remember me cookie
cookie_name = current_app.config.get('REMEMBER_COOKIE_NAME', COOKIE_NAME)
cookie_path = current_app.config.get('REMEMBER_COOKIE_PATH', '/')
response.set_cookie(cookie_name, path=cookie_path, expires=0)
return response, 302
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from urlparse import urlparse, urljoin
from urllib.parse import urlparse, urljoin
from flask import (
Blueprint, abort, current_app, flash, redirect, render_template,
request, session, url_for
)
from flask_login import current_user, login_user, logout_user, COOKIE_NAME
from oauthlib.oauth2 import OAuth2Error
from .forms import LoginForm
from doorman.extensions import csrf, ldap_manager, login_manager
from doorman.models import User
from doorman.utils import flash_errors
from doorman.users.mixins import NoAuthUserMixin
and context:
# Path: doorman/users/forms.py
# class LoginForm(Form):
#
# username = StringField('Username', validators=[DataRequired()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember me', validators=[Optional()])
#
# def __init__(self, *args, **kwargs):
# """Create instance."""
# super(LoginForm, self).__init__(*args, **kwargs)
# self.user = None
#
# def validate(self):
# initial_validation = super(LoginForm, self).validate()
# if not initial_validation:
# return False
#
# error_message = u'Invalid username or password.'
#
# if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman':
# self.user = User.query.filter_by(username=self.username.data).first()
#
# if not self.user:
# from doorman.extensions import bcrypt
# # avoid timing leaks
# bcrypt.generate_password_hash(self.password.data)
# self.username.errors.append(error_message)
# return False
#
# if not self.user.check_password(self.password.data):
# self.username.errors.append(error_message)
# return False
#
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap':
# result = ldap_manager.authenticate(
# self.username.data,
# self.password.data
# )
#
# if result.status == AuthenticationResponseStatus.fail:
# self.username.errors.append(error_message)
# return False
#
# self.user = ldap_manager._save_user(
# result.user_dn,
# result.user_id,
# result.user_info,
# result.user_groups
# )
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] is None:
# return True
#
# return False
#
# @property
# def auth_method(self):
# return current_app.config['DOORMAN_AUTH_METHOD']
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/models.py
# class User(UserMixin, SurrogatePK, Model):
#
# username = Column(db.String(80), unique=True, nullable=False)
# email = Column(db.String)
#
# password = Column(db.String, nullable=True)
# created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# # oauth related stuff
# social_id = Column(db.String)
# first_name = Column(db.String)
# last_name = Column(db.String)
#
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# self.username = username
# self.email = email
# if password:
# self.set_password(password)
# else:
# self.password = None
#
# self.social_id = social_id
# self.first_name = first_name
# self.last_name = last_name
#
# def set_password(self, password):
# self.update(password=bcrypt.generate_password_hash(password))
# return
#
# def check_password(self, value):
# if not self.password:
# # still do the computation
# return bcrypt.generate_password_hash(value) and False
# return bcrypt.check_password_hash(self.password, value)
#
# Path: doorman/utils.py
# def flash_errors(form):
# '''http://flask.pocoo.org/snippets/12/'''
# for field, errors in form.errors.items():
# for error in errors:
# message = u"Error in the {0} field - {1}".format(
# getattr(form, field).label.text, error
# )
# flash(message, 'danger')
which might include code, classes, or functions. Output only the next line. | @csrf.exempt |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
blueprint = Blueprint('users', __name__)
@login_manager.user_loader
def load_user(user_id):
if current_app.config['DOORMAN_AUTH_METHOD'] is None:
return NoAuthUserMixin()
return User.get_by_id(int(user_id))
<|code_end|>
, determine the next line of code. You have imports:
from urlparse import urlparse, urljoin
from urllib.parse import urlparse, urljoin
from flask import (
Blueprint, abort, current_app, flash, redirect, render_template,
request, session, url_for
)
from flask_login import current_user, login_user, logout_user, COOKIE_NAME
from oauthlib.oauth2 import OAuth2Error
from .forms import LoginForm
from doorman.extensions import csrf, ldap_manager, login_manager
from doorman.models import User
from doorman.utils import flash_errors
from doorman.users.mixins import NoAuthUserMixin
and context (class names, function names, or code) available:
# Path: doorman/users/forms.py
# class LoginForm(Form):
#
# username = StringField('Username', validators=[DataRequired()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember me', validators=[Optional()])
#
# def __init__(self, *args, **kwargs):
# """Create instance."""
# super(LoginForm, self).__init__(*args, **kwargs)
# self.user = None
#
# def validate(self):
# initial_validation = super(LoginForm, self).validate()
# if not initial_validation:
# return False
#
# error_message = u'Invalid username or password.'
#
# if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman':
# self.user = User.query.filter_by(username=self.username.data).first()
#
# if not self.user:
# from doorman.extensions import bcrypt
# # avoid timing leaks
# bcrypt.generate_password_hash(self.password.data)
# self.username.errors.append(error_message)
# return False
#
# if not self.user.check_password(self.password.data):
# self.username.errors.append(error_message)
# return False
#
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap':
# result = ldap_manager.authenticate(
# self.username.data,
# self.password.data
# )
#
# if result.status == AuthenticationResponseStatus.fail:
# self.username.errors.append(error_message)
# return False
#
# self.user = ldap_manager._save_user(
# result.user_dn,
# result.user_id,
# result.user_info,
# result.user_groups
# )
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] is None:
# return True
#
# return False
#
# @property
# def auth_method(self):
# return current_app.config['DOORMAN_AUTH_METHOD']
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/models.py
# class User(UserMixin, SurrogatePK, Model):
#
# username = Column(db.String(80), unique=True, nullable=False)
# email = Column(db.String)
#
# password = Column(db.String, nullable=True)
# created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# # oauth related stuff
# social_id = Column(db.String)
# first_name = Column(db.String)
# last_name = Column(db.String)
#
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# self.username = username
# self.email = email
# if password:
# self.set_password(password)
# else:
# self.password = None
#
# self.social_id = social_id
# self.first_name = first_name
# self.last_name = last_name
#
# def set_password(self, password):
# self.update(password=bcrypt.generate_password_hash(password))
# return
#
# def check_password(self, value):
# if not self.password:
# # still do the computation
# return bcrypt.generate_password_hash(value) and False
# return bcrypt.check_password_hash(self.password, value)
#
# Path: doorman/utils.py
# def flash_errors(form):
# '''http://flask.pocoo.org/snippets/12/'''
# for field, errors in form.errors.items():
# for error in errors:
# message = u"Error in the {0} field - {1}".format(
# getattr(form, field).label.text, error
# )
# flash(message, 'danger')
. Output only the next line. | @ldap_manager.save_user |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
blueprint = Blueprint('users', __name__)
<|code_end|>
, determine the next line of code. You have imports:
from urlparse import urlparse, urljoin
from urllib.parse import urlparse, urljoin
from flask import (
Blueprint, abort, current_app, flash, redirect, render_template,
request, session, url_for
)
from flask_login import current_user, login_user, logout_user, COOKIE_NAME
from oauthlib.oauth2 import OAuth2Error
from .forms import LoginForm
from doorman.extensions import csrf, ldap_manager, login_manager
from doorman.models import User
from doorman.utils import flash_errors
from doorman.users.mixins import NoAuthUserMixin
and context (class names, function names, or code) available:
# Path: doorman/users/forms.py
# class LoginForm(Form):
#
# username = StringField('Username', validators=[DataRequired()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember me', validators=[Optional()])
#
# def __init__(self, *args, **kwargs):
# """Create instance."""
# super(LoginForm, self).__init__(*args, **kwargs)
# self.user = None
#
# def validate(self):
# initial_validation = super(LoginForm, self).validate()
# if not initial_validation:
# return False
#
# error_message = u'Invalid username or password.'
#
# if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman':
# self.user = User.query.filter_by(username=self.username.data).first()
#
# if not self.user:
# from doorman.extensions import bcrypt
# # avoid timing leaks
# bcrypt.generate_password_hash(self.password.data)
# self.username.errors.append(error_message)
# return False
#
# if not self.user.check_password(self.password.data):
# self.username.errors.append(error_message)
# return False
#
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap':
# result = ldap_manager.authenticate(
# self.username.data,
# self.password.data
# )
#
# if result.status == AuthenticationResponseStatus.fail:
# self.username.errors.append(error_message)
# return False
#
# self.user = ldap_manager._save_user(
# result.user_dn,
# result.user_id,
# result.user_info,
# result.user_groups
# )
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] is None:
# return True
#
# return False
#
# @property
# def auth_method(self):
# return current_app.config['DOORMAN_AUTH_METHOD']
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/models.py
# class User(UserMixin, SurrogatePK, Model):
#
# username = Column(db.String(80), unique=True, nullable=False)
# email = Column(db.String)
#
# password = Column(db.String, nullable=True)
# created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# # oauth related stuff
# social_id = Column(db.String)
# first_name = Column(db.String)
# last_name = Column(db.String)
#
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# self.username = username
# self.email = email
# if password:
# self.set_password(password)
# else:
# self.password = None
#
# self.social_id = social_id
# self.first_name = first_name
# self.last_name = last_name
#
# def set_password(self, password):
# self.update(password=bcrypt.generate_password_hash(password))
# return
#
# def check_password(self, value):
# if not self.password:
# # still do the computation
# return bcrypt.generate_password_hash(value) and False
# return bcrypt.check_password_hash(self.password, value)
#
# Path: doorman/utils.py
# def flash_errors(form):
# '''http://flask.pocoo.org/snippets/12/'''
# for field, errors in form.errors.items():
# for error in errors:
# message = u"Error in the {0} field - {1}".format(
# getattr(form, field).label.text, error
# )
# flash(message, 'danger')
. Output only the next line. | @login_manager.user_loader |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
blueprint = Blueprint('users', __name__)
@login_manager.user_loader
def load_user(user_id):
if current_app.config['DOORMAN_AUTH_METHOD'] is None:
return NoAuthUserMixin()
<|code_end|>
, generate the next line using the imports in this file:
from urlparse import urlparse, urljoin
from urllib.parse import urlparse, urljoin
from flask import (
Blueprint, abort, current_app, flash, redirect, render_template,
request, session, url_for
)
from flask_login import current_user, login_user, logout_user, COOKIE_NAME
from oauthlib.oauth2 import OAuth2Error
from .forms import LoginForm
from doorman.extensions import csrf, ldap_manager, login_manager
from doorman.models import User
from doorman.utils import flash_errors
from doorman.users.mixins import NoAuthUserMixin
and context (functions, classes, or occasionally code) from other files:
# Path: doorman/users/forms.py
# class LoginForm(Form):
#
# username = StringField('Username', validators=[DataRequired()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember me', validators=[Optional()])
#
# def __init__(self, *args, **kwargs):
# """Create instance."""
# super(LoginForm, self).__init__(*args, **kwargs)
# self.user = None
#
# def validate(self):
# initial_validation = super(LoginForm, self).validate()
# if not initial_validation:
# return False
#
# error_message = u'Invalid username or password.'
#
# if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman':
# self.user = User.query.filter_by(username=self.username.data).first()
#
# if not self.user:
# from doorman.extensions import bcrypt
# # avoid timing leaks
# bcrypt.generate_password_hash(self.password.data)
# self.username.errors.append(error_message)
# return False
#
# if not self.user.check_password(self.password.data):
# self.username.errors.append(error_message)
# return False
#
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap':
# result = ldap_manager.authenticate(
# self.username.data,
# self.password.data
# )
#
# if result.status == AuthenticationResponseStatus.fail:
# self.username.errors.append(error_message)
# return False
#
# self.user = ldap_manager._save_user(
# result.user_dn,
# result.user_id,
# result.user_info,
# result.user_groups
# )
# return True
#
# elif current_app.config['DOORMAN_AUTH_METHOD'] is None:
# return True
#
# return False
#
# @property
# def auth_method(self):
# return current_app.config['DOORMAN_AUTH_METHOD']
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/models.py
# class User(UserMixin, SurrogatePK, Model):
#
# username = Column(db.String(80), unique=True, nullable=False)
# email = Column(db.String)
#
# password = Column(db.String, nullable=True)
# created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# # oauth related stuff
# social_id = Column(db.String)
# first_name = Column(db.String)
# last_name = Column(db.String)
#
# def __init__(self, username, password=None, email=None, social_id=None,
# first_name=None, last_name=None):
# self.username = username
# self.email = email
# if password:
# self.set_password(password)
# else:
# self.password = None
#
# self.social_id = social_id
# self.first_name = first_name
# self.last_name = last_name
#
# def set_password(self, password):
# self.update(password=bcrypt.generate_password_hash(password))
# return
#
# def check_password(self, value):
# if not self.password:
# # still do the computation
# return bcrypt.generate_password_hash(value) and False
# return bcrypt.check_password_hash(self.password, value)
#
# Path: doorman/utils.py
# def flash_errors(form):
# '''http://flask.pocoo.org/snippets/12/'''
# for field, errors in form.errors.items():
# for error in errors:
# message = u"Error in the {0} field - {1}".format(
# getattr(form, field).label.text, error
# )
# flash(message, 'danger')
. Output only the next line. | return User.get_by_id(int(user_id)) |
Given the following code snippet before the placeholder: <|code_start|> count=self.incident_count
)
description = match.rule.template.safe_substitute(
match.result['columns'],
**node
).rstrip()
description = ":".join(description.split('\r\n\r\n', 1))
details = {
'node': node,
'rule_name': match.rule.name,
'rule_description': match.rule.description,
'action': match.result['action'],
'match': match.result['columns'],
}
headers = {
'Content-type': 'application/json',
}
payload = json.dumps({
'event_type': 'trigger',
'service_key': self.service_key,
'incident_key': key,
'description': description,
'client': 'Doorman',
"client_url": self.client_url,
'details': details,
<|code_end|>
, predict the next line using imports from the current file:
import json
import logging
import requests
from doorman.utils import DateTimeEncoder
from .base import AbstractAlerterPlugin
and context including class names, function names, and sometimes code from other files:
# Path: doorman/utils.py
# class DateTimeEncoder(json.JSONEncoder):
# def default(self, o):
# if isinstance(o, dt.datetime):
# return o.isoformat()
#
# return json.JSONEncoder.default(self, o)
#
# Path: doorman/plugins/alerters/base.py
# class AbstractAlerterPlugin(with_metaclass(ABCMeta)):
# """
# AbstractAlerterPlugin is the base class for all alerters in Doorman. It
# defines the interface that an alerter should implement in order to support
# sending an alert.
# """
# @abstractmethod
# def handle_alert(self, node, match):
# raise NotImplementedError()
. Output only the next line. | }, cls=DateTimeEncoder) |
Continue the code snippet: <|code_start|> self.target_paths = '!!'.join(target_paths)
class ResultLog(SurrogatePK, Model):
name = Column(db.String, nullable=False)
timestamp = Column(db.DateTime, default=dt.datetime.utcnow)
action = Column(db.String)
columns = Column(JSONB)
node_id = reference_col('node', nullable=False)
node = relationship(
'Node',
backref=db.backref('result_logs', lazy='dynamic')
)
def __init__(self, name=None, action=None, columns=None, timestamp=None,
node=None, node_id=None, **kwargs):
self.name = name
self.action = action
self.columns = columns or {}
self.timestamp = timestamp
if node:
self.node = node
elif node_id:
self.node_id = node_id
@declared_attr
def __table_args__(cls):
return (
<|code_end|>
. Use current file imports:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context (classes, functions, or code) from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
. Output only the next line. | Index('idx_%s_node_id_timestamp_desc' % cls.__tablename__, |
Given snippet: <|code_start|> 'query_packs',
Column('pack.id', db.Integer, ForeignKey('pack.id')),
Column('query.id', db.Integer, ForeignKey('query.id'))
)
pack_tags = Table(
'pack_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('pack.id', db.Integer, ForeignKey('pack.id'), index=True)
)
node_tags = Table(
'node_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('node.id', db.Integer, ForeignKey('node.id'), index=True)
)
query_tags = Table(
'query_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('query.id', db.Integer, ForeignKey('query.id'), index=True)
)
file_path_tags = Table(
'file_path_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('file_path.id', db.Integer, ForeignKey('file_path.id'), index=True)
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
which might include code, classes, or functions. Output only the next line. | class Tag(SurrogatePK, Model): |
Based on the snippet: <|code_start|> 'query_packs',
Column('pack.id', db.Integer, ForeignKey('pack.id')),
Column('query.id', db.Integer, ForeignKey('query.id'))
)
pack_tags = Table(
'pack_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('pack.id', db.Integer, ForeignKey('pack.id'), index=True)
)
node_tags = Table(
'node_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('node.id', db.Integer, ForeignKey('node.id'), index=True)
)
query_tags = Table(
'query_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('query.id', db.Integer, ForeignKey('query.id'), index=True)
)
file_path_tags = Table(
'file_path_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('file_path.id', db.Integer, ForeignKey('file_path.id'), index=True)
)
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context (classes, functions, sometimes code) from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
. Output only the next line. | class Tag(SurrogatePK, Model): |
Here is a snippet: <|code_start|>
def __init__(self, category=None, target_paths=None, *args, **kwargs):
self.category = category
if target_paths is not None:
self.set_paths(*target_paths)
elif args:
self.set_paths(*args)
else:
self.target_paths = ''
def to_dict(self):
return {
self.category: self.get_paths()
}
def get_paths(self):
return self.target_paths.split('!!')
def set_paths(self, *target_paths):
self.target_paths = '!!'.join(target_paths)
class ResultLog(SurrogatePK, Model):
name = Column(db.String, nullable=False)
timestamp = Column(db.DateTime, default=dt.datetime.utcnow)
action = Column(db.String)
columns = Column(JSONB)
<|code_end|>
. Write the next line using the current file imports:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
, which may include functions, classes, or code. Output only the next line. | node_id = reference_col('node', nullable=False) |
Next line prediction: <|code_start|>
pack_tags = Table(
'pack_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('pack.id', db.Integer, ForeignKey('pack.id'), index=True)
)
node_tags = Table(
'node_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('node.id', db.Integer, ForeignKey('node.id'), index=True)
)
query_tags = Table(
'query_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('query.id', db.Integer, ForeignKey('query.id'), index=True)
)
file_path_tags = Table(
'file_path_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('file_path.id', db.Integer, ForeignKey('file_path.id'), index=True)
)
class Tag(SurrogatePK, Model):
value = Column(db.String, nullable=False, unique=True)
<|code_end|>
. Use current file imports:
(import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries)
and context including class names, function names, or small code snippets from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
. Output only the next line. | nodes = relationship( |
Predict the next line for this snippet: <|code_start|>class DistributedQueryResult(SurrogatePK, Model):
columns = Column(JSONB)
timestamp = Column(db.DateTime, default=dt.datetime.utcnow)
distributed_query_task_id = reference_col('distributed_query_task', nullable=False)
distributed_query_task = relationship(
'DistributedQueryTask',
backref=db.backref('results',
cascade='all, delete-orphan',
lazy='joined'),
)
distributed_query_id = reference_col('distributed_query', nullable=False)
distributed_query = relationship(
'DistributedQuery',
backref=db.backref('results',
cascade='all, delete-orphan',
lazy='joined'),
)
def __init__(self, columns, distributed_query=None, distributed_query_task=None):
self.columns = columns
self.distributed_query = distributed_query
self.distributed_query_task = distributed_query_task
class Rule(SurrogatePK, Model):
name = Column(db.String, nullable=False)
<|code_end|>
with the help of current file imports:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
, which may contain function names, class names, or code. Output only the next line. | alerters = Column(ARRAY(db.String), nullable=False) |
Given the following code snippet before the placeholder: <|code_start|>
def __repr__(self):
return '<Pack: {0.name}>'.format(self)
def to_dict(self):
queries = {}
discovery = []
for query in self.queries:
if 'discovery' in (t.value for t in query.tags):
discovery.append(query.sql)
else:
queries[query.name] = query.to_dict()
return {
'platform': self.platform,
'version': self.version,
'shard': self.shard,
'discovery': discovery,
'queries': queries,
}
class Node(SurrogatePK, Model):
node_key = Column(db.String, nullable=False, unique=True)
enroll_secret = Column(db.String)
enrolled_on = Column(db.DateTime)
host_identifier = Column(db.String)
last_checkin = Column(db.DateTime)
<|code_end|>
, predict the next line using imports from the current file:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context including class names, function names, and sometimes code from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
. Output only the next line. | node_info = Column(JSONB, default={}, nullable=False) |
Given snippet: <|code_start|> return '<Pack: {0.name}>'.format(self)
def to_dict(self):
queries = {}
discovery = []
for query in self.queries:
if 'discovery' in (t.value for t in query.tags):
discovery.append(query.sql)
else:
queries[query.name] = query.to_dict()
return {
'platform': self.platform,
'version': self.version,
'shard': self.shard,
'discovery': discovery,
'queries': queries,
}
class Node(SurrogatePK, Model):
node_key = Column(db.String, nullable=False, unique=True)
enroll_secret = Column(db.String)
enrolled_on = Column(db.DateTime)
host_identifier = Column(db.String)
last_checkin = Column(db.DateTime)
node_info = Column(JSONB, default={}, nullable=False)
is_active = Column(db.Boolean, default=True, nullable=False)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
which might include code, classes, or functions. Output only the next line. | last_ip = Column(INET, nullable=True) |
Predict the next line for this snippet: <|code_start|> return self.target_paths.split('!!')
def set_paths(self, *target_paths):
self.target_paths = '!!'.join(target_paths)
class ResultLog(SurrogatePK, Model):
name = Column(db.String, nullable=False)
timestamp = Column(db.DateTime, default=dt.datetime.utcnow)
action = Column(db.String)
columns = Column(JSONB)
node_id = reference_col('node', nullable=False)
node = relationship(
'Node',
backref=db.backref('result_logs', lazy='dynamic')
)
def __init__(self, name=None, action=None, columns=None, timestamp=None,
node=None, node_id=None, **kwargs):
self.name = name
self.action = action
self.columns = columns or {}
self.timestamp = timestamp
if node:
self.node = node
elif node_id:
self.node_id = node_id
<|code_end|>
with the help of current file imports:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
, which may contain function names, class names, or code. Output only the next line. | @declared_attr |
Given the following code snippet before the placeholder: <|code_start|> )
class User(UserMixin, SurrogatePK, Model):
username = Column(db.String(80), unique=True, nullable=False)
email = Column(db.String)
password = Column(db.String, nullable=True)
created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
# oauth related stuff
social_id = Column(db.String)
first_name = Column(db.String)
last_name = Column(db.String)
def __init__(self, username, password=None, email=None, social_id=None,
first_name=None, last_name=None):
self.username = username
self.email = email
if password:
self.set_password(password)
else:
self.password = None
self.social_id = social_id
self.first_name = first_name
self.last_name = last_name
def set_password(self, password):
<|code_end|>
, predict the next line using imports from the current file:
import datetime as dt
import string
import uuid
from flask_login import UserMixin
from doorman.database import (
Column,
Table,
ForeignKey,
Index,
Model,
SurrogatePK,
db,
reference_col,
relationship,
ARRAY,
JSONB,
INET,
declared_attr,
)
from doorman.extensions import bcrypt
from doorman.utils import assemble_configuration
from doorman.utils import assemble_distributed_queries
and context including class names, function names, and sometimes code from other files:
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
. Output only the next line. | self.update(password=bcrypt.generate_password_hash(password)) |
Predict the next line for this snippet: <|code_start|>def api():
"""An api instance for the tests, no manager"""
# the mere presence of the env var should prevent the manage
# blueprint from being registered
os.environ['DOORMAN_NO_MANAGER'] = '1'
_app = create_app(config=TestConfig)
ctx = _app.test_request_context()
ctx.push()
try:
yield _app
finally:
ctx.pop()
@pytest.fixture(scope='function')
def testapp(app):
"""A Webtest app."""
return TestApp(app)
@pytest.fixture(scope='function')
def testapi(api):
return TestApp(api)
@pytest.yield_fixture(scope='function')
def db(app):
"""A database for the tests."""
<|code_end|>
with the help of current file imports:
import pytest
import os
from webtest import TestApp
from doorman.application import create_app
from doorman.database import db as _db
from doorman.models import Rule
from doorman.settings import TestConfig
from .factories import NodeFactory, RuleFactory
and context from other files:
# Path: doorman/application.py
# def create_app(config=ProdConfig):
# app = Flask(__name__)
# app.config.from_object(config)
# app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
#
# register_blueprints(app)
# register_errorhandlers(app)
# register_loggers(app)
# register_extensions(app)
# register_auth_method(app)
# register_filters(app)
#
# return app
#
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Rule(SurrogatePK, Model):
#
# name = Column(db.String, nullable=False)
# alerters = Column(ARRAY(db.String), nullable=False)
# description = Column(db.String, nullable=True)
# conditions = Column(JSONB)
# updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# self.name = name
# self.description = description
# self.alerters = alerters
# self.conditions = conditions
# self.updated_at = updated_at
#
# @property
# def template(self):
# return string.Template("{name}\r\n\r\n{description}".format(
# name=self.name, description=self.description or '')
# )
#
# Path: doorman/settings.py
# class TestConfig(Config):
# """
# This class specifies a configuration that is used for our tests.
# """
# TESTING = True
# DEBUG = True
#
# SQLALCHEMY_DATABASE_URI = 'postgresql://localhost:5432/doorman_test'
#
# WTF_CSRF_ENABLED = False
#
# DOORMAN_ENROLL_SECRET = [
# 'secret',
# ]
# DOORMAN_EXPECTS_UNIQUE_HOST_ID = False
#
# DOORMAN_AUTH_METHOD = None
#
# DOORMAN_COLUMN_RENDER = {
# 'computer_name': '<a href="https://{{ value | urlencode }}/">{{ value }}</a>'
# }
#
# Path: tests/factories.py
# class NodeFactory(BaseFactory):
#
# class Meta:
# model = Node
#
# class RuleFactory(BaseFactory):
#
# class Meta:
# model = Rule
, which may contain function names, class names, or code. Output only the next line. | _db.app = app |
Next line prediction: <|code_start|>
@pytest.fixture(scope='function')
def testapp(app):
"""A Webtest app."""
return TestApp(app)
@pytest.fixture(scope='function')
def testapi(api):
return TestApp(api)
@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()
_db.drop_all()
@pytest.fixture
def node(db):
"""A node for the tests."""
<|code_end|>
. Use current file imports:
(import pytest
import os
from webtest import TestApp
from doorman.application import create_app
from doorman.database import db as _db
from doorman.models import Rule
from doorman.settings import TestConfig
from .factories import NodeFactory, RuleFactory)
and context including class names, function names, or small code snippets from other files:
# Path: doorman/application.py
# def create_app(config=ProdConfig):
# app = Flask(__name__)
# app.config.from_object(config)
# app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
#
# register_blueprints(app)
# register_errorhandlers(app)
# register_loggers(app)
# register_extensions(app)
# register_auth_method(app)
# register_filters(app)
#
# return app
#
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Rule(SurrogatePK, Model):
#
# name = Column(db.String, nullable=False)
# alerters = Column(ARRAY(db.String), nullable=False)
# description = Column(db.String, nullable=True)
# conditions = Column(JSONB)
# updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# self.name = name
# self.description = description
# self.alerters = alerters
# self.conditions = conditions
# self.updated_at = updated_at
#
# @property
# def template(self):
# return string.Template("{name}\r\n\r\n{description}".format(
# name=self.name, description=self.description or '')
# )
#
# Path: doorman/settings.py
# class TestConfig(Config):
# """
# This class specifies a configuration that is used for our tests.
# """
# TESTING = True
# DEBUG = True
#
# SQLALCHEMY_DATABASE_URI = 'postgresql://localhost:5432/doorman_test'
#
# WTF_CSRF_ENABLED = False
#
# DOORMAN_ENROLL_SECRET = [
# 'secret',
# ]
# DOORMAN_EXPECTS_UNIQUE_HOST_ID = False
#
# DOORMAN_AUTH_METHOD = None
#
# DOORMAN_COLUMN_RENDER = {
# 'computer_name': '<a href="https://{{ value | urlencode }}/">{{ value }}</a>'
# }
#
# Path: tests/factories.py
# class NodeFactory(BaseFactory):
#
# class Meta:
# model = Node
#
# class RuleFactory(BaseFactory):
#
# class Meta:
# model = Rule
. Output only the next line. | node = NodeFactory(host_identifier='foobar', enroll_secret='foobar') |
Based on the snippet: <|code_start|>
@pytest.fixture(scope='function')
def testapi(api):
return TestApp(api)
@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()
_db.drop_all()
@pytest.fixture
def node(db):
"""A node for the tests."""
node = NodeFactory(host_identifier='foobar', enroll_secret='foobar')
db.session.commit()
return node
@pytest.fixture
def rule(db):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
import os
from webtest import TestApp
from doorman.application import create_app
from doorman.database import db as _db
from doorman.models import Rule
from doorman.settings import TestConfig
from .factories import NodeFactory, RuleFactory
and context (classes, functions, sometimes code) from other files:
# Path: doorman/application.py
# def create_app(config=ProdConfig):
# app = Flask(__name__)
# app.config.from_object(config)
# app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
#
# register_blueprints(app)
# register_errorhandlers(app)
# register_loggers(app)
# register_extensions(app)
# register_auth_method(app)
# register_filters(app)
#
# return app
#
# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(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, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
#
# Path: doorman/models.py
# class Rule(SurrogatePK, Model):
#
# name = Column(db.String, nullable=False)
# alerters = Column(ARRAY(db.String), nullable=False)
# description = Column(db.String, nullable=True)
# conditions = Column(JSONB)
# updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# self.name = name
# self.description = description
# self.alerters = alerters
# self.conditions = conditions
# self.updated_at = updated_at
#
# @property
# def template(self):
# return string.Template("{name}\r\n\r\n{description}".format(
# name=self.name, description=self.description or '')
# )
#
# Path: doorman/settings.py
# class TestConfig(Config):
# """
# This class specifies a configuration that is used for our tests.
# """
# TESTING = True
# DEBUG = True
#
# SQLALCHEMY_DATABASE_URI = 'postgresql://localhost:5432/doorman_test'
#
# WTF_CSRF_ENABLED = False
#
# DOORMAN_ENROLL_SECRET = [
# 'secret',
# ]
# DOORMAN_EXPECTS_UNIQUE_HOST_ID = False
#
# DOORMAN_AUTH_METHOD = None
#
# DOORMAN_COLUMN_RENDER = {
# 'computer_name': '<a href="https://{{ value | urlencode }}/">{{ value }}</a>'
# }
#
# Path: tests/factories.py
# class NodeFactory(BaseFactory):
#
# class Meta:
# model = Node
#
# class RuleFactory(BaseFactory):
#
# class Meta:
# model = Rule
. Output only the next line. | rule = RuleFactory( |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class DJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': '__datetime__',
'epoch': int(mktime(obj.timetuple()))
}
else:
return json.JSONEncoder.default(self, obj)
def djson_decoder(obj):
if '__type__' in obj:
if obj['__type__'] == '__datetime__':
return datetime.fromtimestamp(obj['epoch'])
return obj
# Encoder function
def djson_dumps(obj):
return json.dumps(obj, cls=DJSONEncoder)
# Decoder function
def djson_loads(s):
<|code_end|>
with the help of current file imports:
from datetime import datetime
from time import mktime
from doorman.compat import string_types
import json
and context from other files:
# Path: doorman/compat.py
# PY2 = int(sys.version[0]) == 2
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# class metaclass(meta):
, which may contain function names, class names, or code. Output only the next line. | if not isinstance(s, string_types): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class TestCreateTagForm:
def test_tag_validate_failure(self, testapp):
form = CreateTagForm()
assert form.validate() is False
def test_tag_validate_success(self, testapp):
form = CreateTagForm(value='foo')
assert form.validate() is True
class TestCreateQueryForm:
def test_sql_validate_failure(self, testapp, db):
<|code_end|>
, determine the next line of code. You have imports:
from doorman.manage.forms import (
CreateQueryForm,
UpdateQueryForm,
UploadPackForm,
CreateTagForm,
)
from .factories import QueryFactory
and context (class names, function names, or code) available:
# Path: doorman/manage/forms.py
# class CreateQueryForm(QueryForm):
#
# def validate(self):
# from doorman.models import Query
# initial_validation = super(CreateQueryForm, self).validate()
# if not initial_validation:
# return False
#
# query = Query.query.filter(Query.name == self.name.data).first()
# if query:
# self.name.errors.append(
# u"Query with the name {0} already exists!".format(
# self.name.data)
# )
# return False
#
# # TODO could do some validation of the sql query
# return True
#
# class UpdateQueryForm(QueryForm):
#
# def __init__(self, *args, **kwargs):
# super(UpdateQueryForm, self).__init__(*args, **kwargs)
# self.set_choices()
# query = kwargs.pop('obj', None)
# if query:
# self.packs.process_data([p.name for p in query.packs])
# self.tags.process_data('\n'.join(t.value for t in query.tags))
#
# class UploadPackForm(Form):
#
# pack = FileField(u'Pack configuration', validators=[FileRequired()])
#
# class CreateTagForm(Form):
# value = TextAreaField('Tag', validators=[DataRequired()])
#
# Path: tests/factories.py
# class QueryFactory(BaseFactory):
#
# class Meta:
# model = Query
. Output only the next line. | form = CreateQueryForm( |
Next line prediction: <|code_start|> form = CreateTagForm(value='foo')
assert form.validate() is True
class TestCreateQueryForm:
def test_sql_validate_failure(self, testapp, db):
form = CreateQueryForm(
name='foobar',
sql='select * from foobar;'
)
assert form.validate() is False
assert 'sql' in form.errors
assert 'name' not in form.errors
def test_sql_validate_success(self, testapp, db):
form = CreateQueryForm(
name='foobar',
sql='select * from osquery_info;',
)
assert form.validate() is True
class TestUpdateQueryForm:
def test_sql_validate_failure(self, testapp, db):
query = QueryFactory(
name='foobar',
sql='select * from osquery_info;'
)
<|code_end|>
. Use current file imports:
(from doorman.manage.forms import (
CreateQueryForm,
UpdateQueryForm,
UploadPackForm,
CreateTagForm,
)
from .factories import QueryFactory)
and context including class names, function names, or small code snippets from other files:
# Path: doorman/manage/forms.py
# class CreateQueryForm(QueryForm):
#
# def validate(self):
# from doorman.models import Query
# initial_validation = super(CreateQueryForm, self).validate()
# if not initial_validation:
# return False
#
# query = Query.query.filter(Query.name == self.name.data).first()
# if query:
# self.name.errors.append(
# u"Query with the name {0} already exists!".format(
# self.name.data)
# )
# return False
#
# # TODO could do some validation of the sql query
# return True
#
# class UpdateQueryForm(QueryForm):
#
# def __init__(self, *args, **kwargs):
# super(UpdateQueryForm, self).__init__(*args, **kwargs)
# self.set_choices()
# query = kwargs.pop('obj', None)
# if query:
# self.packs.process_data([p.name for p in query.packs])
# self.tags.process_data('\n'.join(t.value for t in query.tags))
#
# class UploadPackForm(Form):
#
# pack = FileField(u'Pack configuration', validators=[FileRequired()])
#
# class CreateTagForm(Form):
# value = TextAreaField('Tag', validators=[DataRequired()])
#
# Path: tests/factories.py
# class QueryFactory(BaseFactory):
#
# class Meta:
# model = Query
. Output only the next line. | form = UpdateQueryForm( |
Predict the next line after this snippet: <|code_start|> form = CreateTagForm()
assert form.validate() is False
def test_tag_validate_success(self, testapp):
form = CreateTagForm(value='foo')
assert form.validate() is True
class TestCreateQueryForm:
def test_sql_validate_failure(self, testapp, db):
form = CreateQueryForm(
name='foobar',
sql='select * from foobar;'
)
assert form.validate() is False
assert 'sql' in form.errors
assert 'name' not in form.errors
def test_sql_validate_success(self, testapp, db):
form = CreateQueryForm(
name='foobar',
sql='select * from osquery_info;',
)
assert form.validate() is True
class TestUpdateQueryForm:
def test_sql_validate_failure(self, testapp, db):
<|code_end|>
using the current file's imports:
from doorman.manage.forms import (
CreateQueryForm,
UpdateQueryForm,
UploadPackForm,
CreateTagForm,
)
from .factories import QueryFactory
and any relevant context from other files:
# Path: doorman/manage/forms.py
# class CreateQueryForm(QueryForm):
#
# def validate(self):
# from doorman.models import Query
# initial_validation = super(CreateQueryForm, self).validate()
# if not initial_validation:
# return False
#
# query = Query.query.filter(Query.name == self.name.data).first()
# if query:
# self.name.errors.append(
# u"Query with the name {0} already exists!".format(
# self.name.data)
# )
# return False
#
# # TODO could do some validation of the sql query
# return True
#
# class UpdateQueryForm(QueryForm):
#
# def __init__(self, *args, **kwargs):
# super(UpdateQueryForm, self).__init__(*args, **kwargs)
# self.set_choices()
# query = kwargs.pop('obj', None)
# if query:
# self.packs.process_data([p.name for p in query.packs])
# self.tags.process_data('\n'.join(t.value for t in query.tags))
#
# class UploadPackForm(Form):
#
# pack = FileField(u'Pack configuration', validators=[FileRequired()])
#
# class CreateTagForm(Form):
# value = TextAreaField('Tag', validators=[DataRequired()])
#
# Path: tests/factories.py
# class QueryFactory(BaseFactory):
#
# class Meta:
# model = Query
. Output only the next line. | query = QueryFactory( |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
DUMMY_INPUT = RuleInput(result_log={}, node={})
class TestNetwork:
def test_will_cache_condition_instances(self):
<|code_end|>
. Use current file imports:
(import json
import logging
import datetime as dt
from collections import defaultdict
from doorman.rules import (
BaseCondition,
EqualCondition,
LessCondition,
GreaterEqualCondition,
LogicCondition,
MatchesRegexCondition,
Network,
NotMatchesRegexCondition,
RuleInput,
))
and context including class names, function names, or small code snippets from other files:
# Path: doorman/rules.py
# class Network(object):
# class BaseCondition(object):
# class AndCondition(BaseCondition):
# class OrCondition(BaseCondition):
# class LogicCondition(BaseCondition):
# class EqualCondition(LogicCondition):
# class NotEqualCondition(LogicCondition):
# class BeginsWithCondition(LogicCondition):
# class NotBeginsWithCondition(LogicCondition):
# class ContainsCondition(LogicCondition):
# class NotContainsCondition(LogicCondition):
# class EndsWithCondition(LogicCondition):
# class NotEndsWithCondition(LogicCondition):
# class IsEmptyCondition(LogicCondition):
# class IsNotEmptyCondition(LogicCondition):
# class LessCondition(LogicCondition):
# class LessEqualCondition(LogicCondition):
# class GreaterCondition(LogicCondition):
# class GreaterEqualCondition(LogicCondition):
# class MatchesRegexCondition(LogicCondition):
# class NotMatchesRegexCondition(LogicCondition):
# def __init__(self):
# def make_condition(self, klass, *args, **kwargs):
# def tupleify(obj):
# def make_alert_condition(self, alert, dependent, rule_id=None):
# def process(self, entry, node):
# def parse_query(self, query, alerters=None, rule_id=None):
# def parse_condition(d):
# def parse_group(d):
# def parse(d):
# def __init__(self):
# def init_network(self, network):
# def run(self, input):
# def local_run(self, input):
# def __repr__(self):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, key, expected, column_name=None):
# def maybe_make_number(self, value):
# def local_run(self, input):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# OPERATOR_MAP = {
# 'equal': EqualCondition,
# 'not_equal': NotEqualCondition,
# 'begins_with': BeginsWithCondition,
# 'not_begins_with': NotBeginsWithCondition,
# 'contains': ContainsCondition,
# 'not_contains': NotContainsCondition,
# 'ends_with': EndsWithCondition,
# 'not_ends_with': NotEndsWithCondition,
# 'is_empty': IsEmptyCondition,
# 'is_not_empty': IsNotEmptyCondition,
# 'less': LessCondition,
# 'less_or_equal': LessEqualCondition,
# 'greater': GreaterCondition,
# 'greater_or_equal': GreaterEqualCondition,
# 'matches_regex': MatchesRegexCondition,
# 'not_matches_regex': NotMatchesRegexCondition,
# }
. Output only the next line. | class TestCondition(BaseCondition): |
Using the snippet: <|code_start|> def compare(self, value):
self.compare_val = value
inp = RuleInput(node={}, result_log={
'columns': {
'int_col': '1234',
'float_col': '56.78',
},
})
condition = TestCondition(None, None, column_name='int_col')
condition.local_run(inp)
assert condition.compare_val == 1234
condition = TestCondition(None, None, column_name='float_col')
condition.local_run(inp)
assert condition.compare_val == 56.78
def test_less_with_number_values(self):
""" Functional test for LessCondition that it uses the number conversion. """
inp = RuleInput(node={}, result_log={
'columns': {
'val': '112',
},
})
# assert that the rule does not alert when the column value
# posted by osquery ('112') is less than configured in the rule ('12')
<|code_end|>
, determine the next line of code. You have imports:
import json
import logging
import datetime as dt
from collections import defaultdict
from doorman.rules import (
BaseCondition,
EqualCondition,
LessCondition,
GreaterEqualCondition,
LogicCondition,
MatchesRegexCondition,
Network,
NotMatchesRegexCondition,
RuleInput,
)
and context (class names, function names, or code) available:
# Path: doorman/rules.py
# class Network(object):
# class BaseCondition(object):
# class AndCondition(BaseCondition):
# class OrCondition(BaseCondition):
# class LogicCondition(BaseCondition):
# class EqualCondition(LogicCondition):
# class NotEqualCondition(LogicCondition):
# class BeginsWithCondition(LogicCondition):
# class NotBeginsWithCondition(LogicCondition):
# class ContainsCondition(LogicCondition):
# class NotContainsCondition(LogicCondition):
# class EndsWithCondition(LogicCondition):
# class NotEndsWithCondition(LogicCondition):
# class IsEmptyCondition(LogicCondition):
# class IsNotEmptyCondition(LogicCondition):
# class LessCondition(LogicCondition):
# class LessEqualCondition(LogicCondition):
# class GreaterCondition(LogicCondition):
# class GreaterEqualCondition(LogicCondition):
# class MatchesRegexCondition(LogicCondition):
# class NotMatchesRegexCondition(LogicCondition):
# def __init__(self):
# def make_condition(self, klass, *args, **kwargs):
# def tupleify(obj):
# def make_alert_condition(self, alert, dependent, rule_id=None):
# def process(self, entry, node):
# def parse_query(self, query, alerters=None, rule_id=None):
# def parse_condition(d):
# def parse_group(d):
# def parse(d):
# def __init__(self):
# def init_network(self, network):
# def run(self, input):
# def local_run(self, input):
# def __repr__(self):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, key, expected, column_name=None):
# def maybe_make_number(self, value):
# def local_run(self, input):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# OPERATOR_MAP = {
# 'equal': EqualCondition,
# 'not_equal': NotEqualCondition,
# 'begins_with': BeginsWithCondition,
# 'not_begins_with': NotBeginsWithCondition,
# 'contains': ContainsCondition,
# 'not_contains': NotContainsCondition,
# 'ends_with': EndsWithCondition,
# 'not_ends_with': NotEndsWithCondition,
# 'is_empty': IsEmptyCondition,
# 'is_not_empty': IsNotEmptyCondition,
# 'less': LessCondition,
# 'less_or_equal': LessEqualCondition,
# 'greater': GreaterCondition,
# 'greater_or_equal': GreaterEqualCondition,
# 'matches_regex': MatchesRegexCondition,
# 'not_matches_regex': NotMatchesRegexCondition,
# }
. Output only the next line. | condition = LessCondition(None, '12', column_name='val') |
Predict the next line after this snippet: <|code_start|> """ Functional test for LessCondition that it uses the number conversion. """
inp = RuleInput(node={}, result_log={
'columns': {
'val': '112',
},
})
# assert that the rule does not alert when the column value
# posted by osquery ('112') is less than configured in the rule ('12')
condition = LessCondition(None, '12', column_name='val')
assert condition.local_run(inp) is False
condition = LessCondition(None, '112', column_name='val')
assert condition.local_run(inp) is False
condition = LessCondition(None, '113', column_name='val')
assert condition.local_run(inp) is True
def test_greater_or_equal_to_number_values(self):
inp = RuleInput(node={}, result_log={
'columns': {
'val': '112',
},
})
# assert that the rule does not alert when the column value
# posted by osquery ('112') is less than configured in the rule ('12')
<|code_end|>
using the current file's imports:
import json
import logging
import datetime as dt
from collections import defaultdict
from doorman.rules import (
BaseCondition,
EqualCondition,
LessCondition,
GreaterEqualCondition,
LogicCondition,
MatchesRegexCondition,
Network,
NotMatchesRegexCondition,
RuleInput,
)
and any relevant context from other files:
# Path: doorman/rules.py
# class Network(object):
# class BaseCondition(object):
# class AndCondition(BaseCondition):
# class OrCondition(BaseCondition):
# class LogicCondition(BaseCondition):
# class EqualCondition(LogicCondition):
# class NotEqualCondition(LogicCondition):
# class BeginsWithCondition(LogicCondition):
# class NotBeginsWithCondition(LogicCondition):
# class ContainsCondition(LogicCondition):
# class NotContainsCondition(LogicCondition):
# class EndsWithCondition(LogicCondition):
# class NotEndsWithCondition(LogicCondition):
# class IsEmptyCondition(LogicCondition):
# class IsNotEmptyCondition(LogicCondition):
# class LessCondition(LogicCondition):
# class LessEqualCondition(LogicCondition):
# class GreaterCondition(LogicCondition):
# class GreaterEqualCondition(LogicCondition):
# class MatchesRegexCondition(LogicCondition):
# class NotMatchesRegexCondition(LogicCondition):
# def __init__(self):
# def make_condition(self, klass, *args, **kwargs):
# def tupleify(obj):
# def make_alert_condition(self, alert, dependent, rule_id=None):
# def process(self, entry, node):
# def parse_query(self, query, alerters=None, rule_id=None):
# def parse_condition(d):
# def parse_group(d):
# def parse(d):
# def __init__(self):
# def init_network(self, network):
# def run(self, input):
# def local_run(self, input):
# def __repr__(self):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, key, expected, column_name=None):
# def maybe_make_number(self, value):
# def local_run(self, input):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# OPERATOR_MAP = {
# 'equal': EqualCondition,
# 'not_equal': NotEqualCondition,
# 'begins_with': BeginsWithCondition,
# 'not_begins_with': NotBeginsWithCondition,
# 'contains': ContainsCondition,
# 'not_contains': NotContainsCondition,
# 'ends_with': EndsWithCondition,
# 'not_ends_with': NotEndsWithCondition,
# 'is_empty': IsEmptyCondition,
# 'is_not_empty': IsNotEmptyCondition,
# 'less': LessCondition,
# 'less_or_equal': LessEqualCondition,
# 'greater': GreaterCondition,
# 'greater_or_equal': GreaterEqualCondition,
# 'matches_regex': MatchesRegexCondition,
# 'not_matches_regex': NotMatchesRegexCondition,
# }
. Output only the next line. | condition = GreaterEqualCondition(None, '12', column_name='val') |
Continue the code snippet: <|code_start|> def __init__(self):
BaseCondition.__init__(self)
self.called_run = False
def local_run(self, input):
self.called_run = True
condition = SubCondition()
condition.run(DUMMY_INPUT)
assert condition.called_run
def test_will_cache_result(self):
class SubCondition(BaseCondition):
def __init__(self):
BaseCondition.__init__(self)
self.runs = 0
def local_run(self, input):
self.runs += 1
condition = SubCondition()
condition.run(DUMMY_INPUT)
condition.run(DUMMY_INPUT)
assert condition.runs == 1
class TestLogicCondition:
def test_will_convert_to_numbers(self):
<|code_end|>
. Use current file imports:
import json
import logging
import datetime as dt
from collections import defaultdict
from doorman.rules import (
BaseCondition,
EqualCondition,
LessCondition,
GreaterEqualCondition,
LogicCondition,
MatchesRegexCondition,
Network,
NotMatchesRegexCondition,
RuleInput,
)
and context (classes, functions, or code) from other files:
# Path: doorman/rules.py
# class Network(object):
# class BaseCondition(object):
# class AndCondition(BaseCondition):
# class OrCondition(BaseCondition):
# class LogicCondition(BaseCondition):
# class EqualCondition(LogicCondition):
# class NotEqualCondition(LogicCondition):
# class BeginsWithCondition(LogicCondition):
# class NotBeginsWithCondition(LogicCondition):
# class ContainsCondition(LogicCondition):
# class NotContainsCondition(LogicCondition):
# class EndsWithCondition(LogicCondition):
# class NotEndsWithCondition(LogicCondition):
# class IsEmptyCondition(LogicCondition):
# class IsNotEmptyCondition(LogicCondition):
# class LessCondition(LogicCondition):
# class LessEqualCondition(LogicCondition):
# class GreaterCondition(LogicCondition):
# class GreaterEqualCondition(LogicCondition):
# class MatchesRegexCondition(LogicCondition):
# class NotMatchesRegexCondition(LogicCondition):
# def __init__(self):
# def make_condition(self, klass, *args, **kwargs):
# def tupleify(obj):
# def make_alert_condition(self, alert, dependent, rule_id=None):
# def process(self, entry, node):
# def parse_query(self, query, alerters=None, rule_id=None):
# def parse_condition(d):
# def parse_group(d):
# def parse(d):
# def __init__(self):
# def init_network(self, network):
# def run(self, input):
# def local_run(self, input):
# def __repr__(self):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, key, expected, column_name=None):
# def maybe_make_number(self, value):
# def local_run(self, input):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# OPERATOR_MAP = {
# 'equal': EqualCondition,
# 'not_equal': NotEqualCondition,
# 'begins_with': BeginsWithCondition,
# 'not_begins_with': NotBeginsWithCondition,
# 'contains': ContainsCondition,
# 'not_contains': NotContainsCondition,
# 'ends_with': EndsWithCondition,
# 'not_ends_with': NotEndsWithCondition,
# 'is_empty': IsEmptyCondition,
# 'is_not_empty': IsNotEmptyCondition,
# 'less': LessCondition,
# 'less_or_equal': LessEqualCondition,
# 'greater': GreaterCondition,
# 'greater_or_equal': GreaterEqualCondition,
# 'matches_regex': MatchesRegexCondition,
# 'not_matches_regex': NotMatchesRegexCondition,
# }
. Output only the next line. | class TestCondition(LogicCondition): |
Predict the next line after this snippet: <|code_start|>
condition = LessCondition(None, '112', column_name='val')
assert condition.local_run(inp) is False
condition = LessCondition(None, '113', column_name='val')
assert condition.local_run(inp) is True
def test_greater_or_equal_to_number_values(self):
inp = RuleInput(node={}, result_log={
'columns': {
'val': '112',
},
})
# assert that the rule does not alert when the column value
# posted by osquery ('112') is less than configured in the rule ('12')
condition = GreaterEqualCondition(None, '12', column_name='val')
assert condition.local_run(inp) is True
condition = GreaterEqualCondition(None, '112', column_name='val')
assert condition.local_run(inp) is True
condition = GreaterEqualCondition(None, '113', column_name='val')
assert condition.local_run(inp) is False
class TestRegexConditions:
def test_matches_regex(self):
<|code_end|>
using the current file's imports:
import json
import logging
import datetime as dt
from collections import defaultdict
from doorman.rules import (
BaseCondition,
EqualCondition,
LessCondition,
GreaterEqualCondition,
LogicCondition,
MatchesRegexCondition,
Network,
NotMatchesRegexCondition,
RuleInput,
)
and any relevant context from other files:
# Path: doorman/rules.py
# class Network(object):
# class BaseCondition(object):
# class AndCondition(BaseCondition):
# class OrCondition(BaseCondition):
# class LogicCondition(BaseCondition):
# class EqualCondition(LogicCondition):
# class NotEqualCondition(LogicCondition):
# class BeginsWithCondition(LogicCondition):
# class NotBeginsWithCondition(LogicCondition):
# class ContainsCondition(LogicCondition):
# class NotContainsCondition(LogicCondition):
# class EndsWithCondition(LogicCondition):
# class NotEndsWithCondition(LogicCondition):
# class IsEmptyCondition(LogicCondition):
# class IsNotEmptyCondition(LogicCondition):
# class LessCondition(LogicCondition):
# class LessEqualCondition(LogicCondition):
# class GreaterCondition(LogicCondition):
# class GreaterEqualCondition(LogicCondition):
# class MatchesRegexCondition(LogicCondition):
# class NotMatchesRegexCondition(LogicCondition):
# def __init__(self):
# def make_condition(self, klass, *args, **kwargs):
# def tupleify(obj):
# def make_alert_condition(self, alert, dependent, rule_id=None):
# def process(self, entry, node):
# def parse_query(self, query, alerters=None, rule_id=None):
# def parse_condition(d):
# def parse_group(d):
# def parse(d):
# def __init__(self):
# def init_network(self, network):
# def run(self, input):
# def local_run(self, input):
# def __repr__(self):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, key, expected, column_name=None):
# def maybe_make_number(self, value):
# def local_run(self, input):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# OPERATOR_MAP = {
# 'equal': EqualCondition,
# 'not_equal': NotEqualCondition,
# 'begins_with': BeginsWithCondition,
# 'not_begins_with': NotBeginsWithCondition,
# 'contains': ContainsCondition,
# 'not_contains': NotContainsCondition,
# 'ends_with': EndsWithCondition,
# 'not_ends_with': NotEndsWithCondition,
# 'is_empty': IsEmptyCondition,
# 'is_not_empty': IsNotEmptyCondition,
# 'less': LessCondition,
# 'less_or_equal': LessEqualCondition,
# 'greater': GreaterCondition,
# 'greater_or_equal': GreaterEqualCondition,
# 'matches_regex': MatchesRegexCondition,
# 'not_matches_regex': NotMatchesRegexCondition,
# }
. Output only the next line. | cond = MatchesRegexCondition('unused', r'a+b+') |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
DUMMY_INPUT = RuleInput(result_log={}, node={})
class TestNetwork:
def test_will_cache_condition_instances(self):
class TestCondition(BaseCondition):
pass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import logging
import datetime as dt
from collections import defaultdict
from doorman.rules import (
BaseCondition,
EqualCondition,
LessCondition,
GreaterEqualCondition,
LogicCondition,
MatchesRegexCondition,
Network,
NotMatchesRegexCondition,
RuleInput,
)
and context:
# Path: doorman/rules.py
# class Network(object):
# class BaseCondition(object):
# class AndCondition(BaseCondition):
# class OrCondition(BaseCondition):
# class LogicCondition(BaseCondition):
# class EqualCondition(LogicCondition):
# class NotEqualCondition(LogicCondition):
# class BeginsWithCondition(LogicCondition):
# class NotBeginsWithCondition(LogicCondition):
# class ContainsCondition(LogicCondition):
# class NotContainsCondition(LogicCondition):
# class EndsWithCondition(LogicCondition):
# class NotEndsWithCondition(LogicCondition):
# class IsEmptyCondition(LogicCondition):
# class IsNotEmptyCondition(LogicCondition):
# class LessCondition(LogicCondition):
# class LessEqualCondition(LogicCondition):
# class GreaterCondition(LogicCondition):
# class GreaterEqualCondition(LogicCondition):
# class MatchesRegexCondition(LogicCondition):
# class NotMatchesRegexCondition(LogicCondition):
# def __init__(self):
# def make_condition(self, klass, *args, **kwargs):
# def tupleify(obj):
# def make_alert_condition(self, alert, dependent, rule_id=None):
# def process(self, entry, node):
# def parse_query(self, query, alerters=None, rule_id=None):
# def parse_condition(d):
# def parse_group(d):
# def parse(d):
# def __init__(self):
# def init_network(self, network):
# def run(self, input):
# def local_run(self, input):
# def __repr__(self):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, key, expected, column_name=None):
# def maybe_make_number(self, value):
# def local_run(self, input):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# OPERATOR_MAP = {
# 'equal': EqualCondition,
# 'not_equal': NotEqualCondition,
# 'begins_with': BeginsWithCondition,
# 'not_begins_with': NotBeginsWithCondition,
# 'contains': ContainsCondition,
# 'not_contains': NotContainsCondition,
# 'ends_with': EndsWithCondition,
# 'not_ends_with': NotEndsWithCondition,
# 'is_empty': IsEmptyCondition,
# 'is_not_empty': IsNotEmptyCondition,
# 'less': LessCondition,
# 'less_or_equal': LessEqualCondition,
# 'greater': GreaterCondition,
# 'greater_or_equal': GreaterEqualCondition,
# 'matches_regex': MatchesRegexCondition,
# 'not_matches_regex': NotMatchesRegexCondition,
# }
which might include code, classes, or functions. Output only the next line. | network = Network() |
Using the snippet: <|code_start|> assert condition.local_run(inp) is True
def test_greater_or_equal_to_number_values(self):
inp = RuleInput(node={}, result_log={
'columns': {
'val': '112',
},
})
# assert that the rule does not alert when the column value
# posted by osquery ('112') is less than configured in the rule ('12')
condition = GreaterEqualCondition(None, '12', column_name='val')
assert condition.local_run(inp) is True
condition = GreaterEqualCondition(None, '112', column_name='val')
assert condition.local_run(inp) is True
condition = GreaterEqualCondition(None, '113', column_name='val')
assert condition.local_run(inp) is False
class TestRegexConditions:
def test_matches_regex(self):
cond = MatchesRegexCondition('unused', r'a+b+')
assert cond.compare('aaaaaabb') is True
assert cond.compare('caaaabbb') is False
def test_not_matches_regex(self):
<|code_end|>
, determine the next line of code. You have imports:
import json
import logging
import datetime as dt
from collections import defaultdict
from doorman.rules import (
BaseCondition,
EqualCondition,
LessCondition,
GreaterEqualCondition,
LogicCondition,
MatchesRegexCondition,
Network,
NotMatchesRegexCondition,
RuleInput,
)
and context (class names, function names, or code) available:
# Path: doorman/rules.py
# class Network(object):
# class BaseCondition(object):
# class AndCondition(BaseCondition):
# class OrCondition(BaseCondition):
# class LogicCondition(BaseCondition):
# class EqualCondition(LogicCondition):
# class NotEqualCondition(LogicCondition):
# class BeginsWithCondition(LogicCondition):
# class NotBeginsWithCondition(LogicCondition):
# class ContainsCondition(LogicCondition):
# class NotContainsCondition(LogicCondition):
# class EndsWithCondition(LogicCondition):
# class NotEndsWithCondition(LogicCondition):
# class IsEmptyCondition(LogicCondition):
# class IsNotEmptyCondition(LogicCondition):
# class LessCondition(LogicCondition):
# class LessEqualCondition(LogicCondition):
# class GreaterCondition(LogicCondition):
# class GreaterEqualCondition(LogicCondition):
# class MatchesRegexCondition(LogicCondition):
# class NotMatchesRegexCondition(LogicCondition):
# def __init__(self):
# def make_condition(self, klass, *args, **kwargs):
# def tupleify(obj):
# def make_alert_condition(self, alert, dependent, rule_id=None):
# def process(self, entry, node):
# def parse_query(self, query, alerters=None, rule_id=None):
# def parse_condition(d):
# def parse_group(d):
# def parse(d):
# def __init__(self):
# def init_network(self, network):
# def run(self, input):
# def local_run(self, input):
# def __repr__(self):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, upstream):
# def local_run(self, input):
# def __init__(self, key, expected, column_name=None):
# def maybe_make_number(self, value):
# def local_run(self, input):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# def __init__(self, key, expected, **kwargs):
# def compare(self, value):
# OPERATOR_MAP = {
# 'equal': EqualCondition,
# 'not_equal': NotEqualCondition,
# 'begins_with': BeginsWithCondition,
# 'not_begins_with': NotBeginsWithCondition,
# 'contains': ContainsCondition,
# 'not_contains': NotContainsCondition,
# 'ends_with': EndsWithCondition,
# 'not_ends_with': NotEndsWithCondition,
# 'is_empty': IsEmptyCondition,
# 'is_not_empty': IsNotEmptyCondition,
# 'less': LessCondition,
# 'less_or_equal': LessEqualCondition,
# 'greater': GreaterCondition,
# 'greater_or_equal': GreaterEqualCondition,
# 'matches_regex': MatchesRegexCondition,
# 'not_matches_regex': NotMatchesRegexCondition,
# }
. Output only the next line. | cond = NotMatchesRegexCondition('unused', r'c+d') |
Predict the next line after this snippet: <|code_start|> finally:
# Remove final entry from the config.
current_app.config['DOORMAN_EXTRA_SCHEMA'] = \
current_app.config['DOORMAN_EXTRA_SCHEMA'][:-1]
class TestQuote:
def test_will_quote_string(self):
assert quote('foobar') == '"foobar"'
assert quote('foo bar baz') == '"foo bar baz"'
assert quote('foobar', quote='`') == '`foobar`'
def test_will_escape(self):
assert quote(r'foo"bar') == r'"foo\"bar"'
assert quote(r'foo\bar') == r'"foo\\bar"'
def test_quote_control_characters(self):
assert quote("\r\n\t") == r'"\r\n\t"'
def test_quote_unprintable_chars(self):
assert quote('\x8Ffoo\xA3bar').lower() == r'"\x8Ffoo\xA3bar"'.lower()
class TestDateTimeEncoder:
def test_will_serialize_datetime(self):
time = dt.datetime(year=2016, month=5, day=16, hour=11, minute=11, second=11)
data = {'foo': time}
<|code_end|>
using the current file's imports:
import json
import datetime as dt
import pytest
from flask import current_app
from doorman.utils import (
DateTimeEncoder,
osquery_mock_db,
quote,
validate_osquery_query,
)
and any relevant context from other files:
# Path: doorman/utils.py
# def assemble_configuration(node):
# def assemble_options(node):
# def assemble_file_paths(node):
# def assemble_schedule(node):
# def assemble_packs(node):
# def assemble_distributed_queries(node):
# def create_query_pack_from_upload(upload):
# def get_node_health(node):
# def pretty_operator(cond):
# def pretty_field(field):
# def quote(s, quote='"'):
# def create_mock_db():
# def validate_osquery_query(query):
# def learn_from_result(result, node):
# def process_result(result, node):
# def extract_results(result):
# def flash_errors(form):
# def get_paginate_options(request, model, choices, existing_query=None,
# default='id', page=1, max_pp=20, default_sort='asc'):
# def default(self, o):
# def render_column(value, column):
# PRETTY_OPERATORS = {
# 'equal': 'equals',
# 'not_equal': "doesn't equal",
# 'begins_with': 'begins with',
# 'not_begins_with': "doesn't begins with",
# 'contains': 'contains',
# 'not_contains': "doesn't contain",
# 'ends_with': 'ends with',
# 'not_ends_with': "doesn't end with",
# 'is_empty': 'is empty',
# 'is_not_empty': 'is not empty',
# 'less': 'less than',
# 'less_or_equal': 'less than or equal',
# 'greater': 'greater than',
# 'greater_or_equal': 'greater than or equal',
# 'matches_regex': 'matches regex',
# 'not_matches_regex': "doesn't match regex",
# }
# PRETTY_FIELDS = {
# 'query_name': 'Query name',
# 'action': 'Action',
# 'host_identifier': 'Host identifier',
# 'timestamp': 'Timestamp',
# }
# PRINTABLE = string.ascii_letters + string.digits + string.punctuation + ' '
# class DateTimeEncoder(json.JSONEncoder):
. Output only the next line. | s = json.dumps(data, cls=DateTimeEncoder) |
Using the snippet: <|code_start|>
class TestValidate:
def test_simple_validate(self):
query = 'SELECT * FROM osquery_info;'
assert validate_osquery_query(query) is True
def test_complex_validate(self):
# From Facebook's blog post: https://code.facebook.com/posts/844436395567983/introducing-osquery/
query = 'SELECT DISTINCT process.name, listening.port, listening.address, process.pid FROM processes AS process JOIN listening_ports AS listening ON process.pid = listening.pid;'
assert validate_osquery_query(query) is True
def test_syntax_error(self):
query = 'SELECT * FROM'
assert validate_osquery_query(query) is False
def test_bad_table(self):
query = 'SELECT * FROM a_table_that_does_not_exist;'
assert validate_osquery_query(query) is False
def test_custom_schema(self):
query = 'SELECT * FROM custom_table;'
assert validate_osquery_query(query) is False
try:
# This is a bit hacky, but it clears the mock DB so the next call
# will re-create it.
<|code_end|>
, determine the next line of code. You have imports:
import json
import datetime as dt
import pytest
from flask import current_app
from doorman.utils import (
DateTimeEncoder,
osquery_mock_db,
quote,
validate_osquery_query,
)
and context (class names, function names, or code) available:
# Path: doorman/utils.py
# def assemble_configuration(node):
# def assemble_options(node):
# def assemble_file_paths(node):
# def assemble_schedule(node):
# def assemble_packs(node):
# def assemble_distributed_queries(node):
# def create_query_pack_from_upload(upload):
# def get_node_health(node):
# def pretty_operator(cond):
# def pretty_field(field):
# def quote(s, quote='"'):
# def create_mock_db():
# def validate_osquery_query(query):
# def learn_from_result(result, node):
# def process_result(result, node):
# def extract_results(result):
# def flash_errors(form):
# def get_paginate_options(request, model, choices, existing_query=None,
# default='id', page=1, max_pp=20, default_sort='asc'):
# def default(self, o):
# def render_column(value, column):
# PRETTY_OPERATORS = {
# 'equal': 'equals',
# 'not_equal': "doesn't equal",
# 'begins_with': 'begins with',
# 'not_begins_with': "doesn't begins with",
# 'contains': 'contains',
# 'not_contains': "doesn't contain",
# 'ends_with': 'ends with',
# 'not_ends_with': "doesn't end with",
# 'is_empty': 'is empty',
# 'is_not_empty': 'is not empty',
# 'less': 'less than',
# 'less_or_equal': 'less than or equal',
# 'greater': 'greater than',
# 'greater_or_equal': 'greater than or equal',
# 'matches_regex': 'matches regex',
# 'not_matches_regex': "doesn't match regex",
# }
# PRETTY_FIELDS = {
# 'query_name': 'Query name',
# 'action': 'Action',
# 'host_identifier': 'Host identifier',
# 'timestamp': 'Timestamp',
# }
# PRINTABLE = string.ascii_letters + string.digits + string.punctuation + ' '
# class DateTimeEncoder(json.JSONEncoder):
. Output only the next line. | osquery_mock_db.db = None |
Using the snippet: <|code_start|> def test_syntax_error(self):
query = 'SELECT * FROM'
assert validate_osquery_query(query) is False
def test_bad_table(self):
query = 'SELECT * FROM a_table_that_does_not_exist;'
assert validate_osquery_query(query) is False
def test_custom_schema(self):
query = 'SELECT * FROM custom_table;'
assert validate_osquery_query(query) is False
try:
# This is a bit hacky, but it clears the mock DB so the next call
# will re-create it.
osquery_mock_db.db = None
current_app.config['DOORMAN_EXTRA_SCHEMA'].append(
'CREATE TABLE custom_table (id INTEGER);'
)
assert validate_osquery_query(query) is True
finally:
# Remove final entry from the config.
current_app.config['DOORMAN_EXTRA_SCHEMA'] = \
current_app.config['DOORMAN_EXTRA_SCHEMA'][:-1]
class TestQuote:
def test_will_quote_string(self):
<|code_end|>
, determine the next line of code. You have imports:
import json
import datetime as dt
import pytest
from flask import current_app
from doorman.utils import (
DateTimeEncoder,
osquery_mock_db,
quote,
validate_osquery_query,
)
and context (class names, function names, or code) available:
# Path: doorman/utils.py
# def assemble_configuration(node):
# def assemble_options(node):
# def assemble_file_paths(node):
# def assemble_schedule(node):
# def assemble_packs(node):
# def assemble_distributed_queries(node):
# def create_query_pack_from_upload(upload):
# def get_node_health(node):
# def pretty_operator(cond):
# def pretty_field(field):
# def quote(s, quote='"'):
# def create_mock_db():
# def validate_osquery_query(query):
# def learn_from_result(result, node):
# def process_result(result, node):
# def extract_results(result):
# def flash_errors(form):
# def get_paginate_options(request, model, choices, existing_query=None,
# default='id', page=1, max_pp=20, default_sort='asc'):
# def default(self, o):
# def render_column(value, column):
# PRETTY_OPERATORS = {
# 'equal': 'equals',
# 'not_equal': "doesn't equal",
# 'begins_with': 'begins with',
# 'not_begins_with': "doesn't begins with",
# 'contains': 'contains',
# 'not_contains': "doesn't contain",
# 'ends_with': 'ends with',
# 'not_ends_with': "doesn't end with",
# 'is_empty': 'is empty',
# 'is_not_empty': 'is not empty',
# 'less': 'less than',
# 'less_or_equal': 'less than or equal',
# 'greater': 'greater than',
# 'greater_or_equal': 'greater than or equal',
# 'matches_regex': 'matches regex',
# 'not_matches_regex': "doesn't match regex",
# }
# PRETTY_FIELDS = {
# 'query_name': 'Query name',
# 'action': 'Action',
# 'host_identifier': 'Host identifier',
# 'timestamp': 'Timestamp',
# }
# PRINTABLE = string.ascii_letters + string.digits + string.punctuation + ' '
# class DateTimeEncoder(json.JSONEncoder):
. Output only the next line. | assert quote('foobar') == '"foobar"' |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class TestValidate:
def test_simple_validate(self):
query = 'SELECT * FROM osquery_info;'
<|code_end|>
using the current file's imports:
import json
import datetime as dt
import pytest
from flask import current_app
from doorman.utils import (
DateTimeEncoder,
osquery_mock_db,
quote,
validate_osquery_query,
)
and any relevant context from other files:
# Path: doorman/utils.py
# def assemble_configuration(node):
# def assemble_options(node):
# def assemble_file_paths(node):
# def assemble_schedule(node):
# def assemble_packs(node):
# def assemble_distributed_queries(node):
# def create_query_pack_from_upload(upload):
# def get_node_health(node):
# def pretty_operator(cond):
# def pretty_field(field):
# def quote(s, quote='"'):
# def create_mock_db():
# def validate_osquery_query(query):
# def learn_from_result(result, node):
# def process_result(result, node):
# def extract_results(result):
# def flash_errors(form):
# def get_paginate_options(request, model, choices, existing_query=None,
# default='id', page=1, max_pp=20, default_sort='asc'):
# def default(self, o):
# def render_column(value, column):
# PRETTY_OPERATORS = {
# 'equal': 'equals',
# 'not_equal': "doesn't equal",
# 'begins_with': 'begins with',
# 'not_begins_with': "doesn't begins with",
# 'contains': 'contains',
# 'not_contains': "doesn't contain",
# 'ends_with': 'ends with',
# 'not_ends_with': "doesn't end with",
# 'is_empty': 'is empty',
# 'is_not_empty': 'is not empty',
# 'less': 'less than',
# 'less_or_equal': 'less than or equal',
# 'greater': 'greater than',
# 'greater_or_equal': 'greater than or equal',
# 'matches_regex': 'matches regex',
# 'not_matches_regex': "doesn't match regex",
# }
# PRETTY_FIELDS = {
# 'query_name': 'Query name',
# 'action': 'Action',
# 'host_identifier': 'Host identifier',
# 'timestamp': 'Timestamp',
# }
# PRINTABLE = string.ascii_letters + string.digits + string.punctuation + ' '
# class DateTimeEncoder(json.JSONEncoder):
. Output only the next line. | assert validate_osquery_query(query) is True |
Continue the code snippet: <|code_start|> def __init__(self, *args, **kwargs):
super(FilePathUpdateForm, self).__init__(*args, **kwargs)
# self.set_choices()
file_path = kwargs.pop('obj', None)
if file_path:
self.target_paths.process_data('\n'.join(file_path.get_paths()))
self.tags.process_data('\n'.join(t.value for t in file_path.tags))
class RuleForm(Form):
name = StringField('Rule Name', validators=[DataRequired()])
alerters = SelectMultipleField('Alerters', default=None, choices=[
])
description = TextAreaField('Description', validators=[Optional()])
conditions = HiddenJSONField('Conditions')
def set_choices(self):
alerter_ids = list(current_app.config.get('DOORMAN_ALERTER_PLUGINS', {}).keys())
self.alerters.choices = [(a, a.title()) for a in alerter_ids]
class CreateRuleForm(RuleForm):
def validate(self):
initial_validation = super(CreateRuleForm, self).validate()
if not initial_validation:
return False
<|code_end|>
. Use current file imports:
import json
from flask import current_app
from flask_wtf import FlaskForm as Form
from flask_wtf.file import FileField, FileRequired
from wtforms.fields import (
BooleanField,
DateTimeField,
Field,
IntegerField,
SelectField,
SelectMultipleField,
StringField,
TextAreaField
)
from wtforms.validators import DataRequired, Optional, ValidationError
from wtforms.widgets import HiddenInput
from doorman.models import Rule
from doorman.utils import validate_osquery_query
from doorman.models import Pack
from doorman.models import Query
from doorman.models import Node, Tag
from doorman.models import Rule
and context (classes, functions, or code) from other files:
# Path: doorman/models.py
# class Rule(SurrogatePK, Model):
#
# name = Column(db.String, nullable=False)
# alerters = Column(ARRAY(db.String), nullable=False)
# description = Column(db.String, nullable=True)
# conditions = Column(JSONB)
# updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# self.name = name
# self.description = description
# self.alerters = alerters
# self.conditions = conditions
# self.updated_at = updated_at
#
# @property
# def template(self):
# return string.Template("{name}\r\n\r\n{description}".format(
# name=self.name, description=self.description or '')
# )
#
# Path: doorman/utils.py
# def validate_osquery_query(query):
# # Check if this thread has an instance of the SQLite database
# db = getattr(osquery_mock_db, 'db', None)
# if db is None:
# db = create_mock_db()
# osquery_mock_db.db = db
#
# try:
# db.execute(query)
# except sqlite3.Error:
# current_app.logger.exception("Invalid query: %s", query)
# return False
#
# return True
. Output only the next line. | query = Rule.query.filter(Rule.name == self.name.data).first() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class ValidSQL(object):
def __init__(self, message=None):
if not message:
message = u'Field must contain valid SQL to be run against osquery tables'
self.message = message
def __call__(self, form, field):
<|code_end|>
. Write the next line using the current file imports:
import json
from flask import current_app
from flask_wtf import FlaskForm as Form
from flask_wtf.file import FileField, FileRequired
from wtforms.fields import (
BooleanField,
DateTimeField,
Field,
IntegerField,
SelectField,
SelectMultipleField,
StringField,
TextAreaField
)
from wtforms.validators import DataRequired, Optional, ValidationError
from wtforms.widgets import HiddenInput
from doorman.models import Rule
from doorman.utils import validate_osquery_query
from doorman.models import Pack
from doorman.models import Query
from doorman.models import Node, Tag
from doorman.models import Rule
and context from other files:
# Path: doorman/models.py
# class Rule(SurrogatePK, Model):
#
# name = Column(db.String, nullable=False)
# alerters = Column(ARRAY(db.String), nullable=False)
# description = Column(db.String, nullable=True)
# conditions = Column(JSONB)
# updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
#
# def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
# self.name = name
# self.description = description
# self.alerters = alerters
# self.conditions = conditions
# self.updated_at = updated_at
#
# @property
# def template(self):
# return string.Template("{name}\r\n\r\n{description}".format(
# name=self.name, description=self.description or '')
# )
#
# Path: doorman/utils.py
# def validate_osquery_query(query):
# # Check if this thread has an instance of the SQLite database
# db = getattr(osquery_mock_db, 'db', None)
# if db is None:
# db = create_mock_db()
# osquery_mock_db.db = db
#
# try:
# db.execute(query)
# except sqlite3.Error:
# current_app.logger.exception("Invalid query: %s", query)
# return False
#
# return True
, which may include functions, classes, or code. Output only the next line. | if not validate_osquery_query(field.data): |
Continue the code snippet: <|code_start|>
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend blueprint. This is useful when you want
# to only deploy the api as a standalone service.
if 'DOORMAN_NO_MANAGER' in os.environ:
return
app.register_blueprint(backend)
def register_extensions(app):
bcrypt.init_app(app)
csrf.init_app(app)
db.init_app(app)
migrate.init_app(app, db)
<|code_end|>
. Use current file imports:
import os
import logging
import sys
from flask import Flask, render_template
from doorman.api import blueprint as api
from doorman.assets import assets
from doorman.manage import blueprint as backend
from doorman.extensions import (
bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager,
mail, make_celery, migrate, rule_manager, sentry
)
from doorman.settings import ProdConfig
from doorman.tasks import celery
from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column
from flask_sslify import SSLify
from logging.handlers import WatchedFileHandler
from doorman.users import views
from doorman.users.mixins import NoAuthUserMixin
from doorman.users.oauth import OAuthLogin
and context (classes, functions, or code) from other files:
# Path: doorman/api.py
# def node_required(f):
# def decorated_function(*args, **kwargs):
# def index():
# def enroll():
# def configuration(node=None):
# def logger(node=None):
# def distributed_read(node=None):
# def distributed_write(node=None):
#
# Path: doorman/assets.py
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/settings.py
# class ProdConfig(Config):
#
# ENV = 'prod'
# DEBUG = False
# DEBUG_TB_ENABLED = False
# DEBUG_TB_INTERCEPT_REDIRECTS = False
#
# ENFORCE_SSL = True
#
# SQLALCHEMY_DATABASE_URI = ''
#
# DOORMAN_ENROLL_SECRET = [
#
# ]
# DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1
#
# BROKER_URL = ''
# CELERY_RESULT_BACKEND = ''
#
# Path: doorman/tasks.py
# def analyze_result(result, node):
# def learn_from_result(result, node):
# def example_task(one, two):
# def notify_of_node_enrollment(node):
# def alert_when_node_goes_offline():
#
# Path: doorman/utils.py
# def get_node_health(node):
# checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL']
# if isinstance(checkin_interval, (int, float)):
# checkin_interval = dt.timedelta(seconds=checkin_interval)
# if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval:
# return u'danger'
# else:
# return ''
#
# def pretty_field(field):
# return PRETTY_FIELDS.get(field, field)
#
# def pretty_operator(cond):
# return PRETTY_OPERATORS.get(cond, cond)
#
# def render_column(value, column):
# renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {})
# if column not in renders:
# return value
#
# template = renders[column]
#
# try:
# if callable(template):
# return template(value)
# else:
# template = Template(template, autoescape=True)
# rendered = template.render(value=value)
#
# # return a markup object so that the template where this is
# # rendered is not escaped again
#
# return Markup(rendered)
# except Exception:
# current_app.logger.exception(
# "Failed to render %s, returning original value",
# column
# )
# return value
. Output only the next line. | assets.init_app(app) |
Here is a snippet: <|code_start|>def create_app(config=ProdConfig):
app = Flask(__name__)
app.config.from_object(config)
app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend blueprint. This is useful when you want
# to only deploy the api as a standalone service.
if 'DOORMAN_NO_MANAGER' in os.environ:
return
app.register_blueprint(backend)
def register_extensions(app):
<|code_end|>
. Write the next line using the current file imports:
import os
import logging
import sys
from flask import Flask, render_template
from doorman.api import blueprint as api
from doorman.assets import assets
from doorman.manage import blueprint as backend
from doorman.extensions import (
bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager,
mail, make_celery, migrate, rule_manager, sentry
)
from doorman.settings import ProdConfig
from doorman.tasks import celery
from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column
from flask_sslify import SSLify
from logging.handlers import WatchedFileHandler
from doorman.users import views
from doorman.users.mixins import NoAuthUserMixin
from doorman.users.oauth import OAuthLogin
and context from other files:
# Path: doorman/api.py
# def node_required(f):
# def decorated_function(*args, **kwargs):
# def index():
# def enroll():
# def configuration(node=None):
# def logger(node=None):
# def distributed_read(node=None):
# def distributed_write(node=None):
#
# Path: doorman/assets.py
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/settings.py
# class ProdConfig(Config):
#
# ENV = 'prod'
# DEBUG = False
# DEBUG_TB_ENABLED = False
# DEBUG_TB_INTERCEPT_REDIRECTS = False
#
# ENFORCE_SSL = True
#
# SQLALCHEMY_DATABASE_URI = ''
#
# DOORMAN_ENROLL_SECRET = [
#
# ]
# DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1
#
# BROKER_URL = ''
# CELERY_RESULT_BACKEND = ''
#
# Path: doorman/tasks.py
# def analyze_result(result, node):
# def learn_from_result(result, node):
# def example_task(one, two):
# def notify_of_node_enrollment(node):
# def alert_when_node_goes_offline():
#
# Path: doorman/utils.py
# def get_node_health(node):
# checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL']
# if isinstance(checkin_interval, (int, float)):
# checkin_interval = dt.timedelta(seconds=checkin_interval)
# if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval:
# return u'danger'
# else:
# return ''
#
# def pretty_field(field):
# return PRETTY_FIELDS.get(field, field)
#
# def pretty_operator(cond):
# return PRETTY_OPERATORS.get(cond, cond)
#
# def render_column(value, column):
# renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {})
# if column not in renders:
# return value
#
# template = renders[column]
#
# try:
# if callable(template):
# return template(value)
# else:
# template = Template(template, autoescape=True)
# rendered = template.render(value=value)
#
# # return a markup object so that the template where this is
# # rendered is not escaped again
#
# return Markup(rendered)
# except Exception:
# current_app.logger.exception(
# "Failed to render %s, returning original value",
# column
# )
# return value
, which may include functions, classes, or code. Output only the next line. | bcrypt.init_app(app) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def create_app(config=ProdConfig):
app = Flask(__name__)
app.config.from_object(config)
app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
<|code_end|>
, determine the next line of code. You have imports:
import os
import logging
import sys
from flask import Flask, render_template
from doorman.api import blueprint as api
from doorman.assets import assets
from doorman.manage import blueprint as backend
from doorman.extensions import (
bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager,
mail, make_celery, migrate, rule_manager, sentry
)
from doorman.settings import ProdConfig
from doorman.tasks import celery
from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column
from flask_sslify import SSLify
from logging.handlers import WatchedFileHandler
from doorman.users import views
from doorman.users.mixins import NoAuthUserMixin
from doorman.users.oauth import OAuthLogin
and context (class names, function names, or code) available:
# Path: doorman/api.py
# def node_required(f):
# def decorated_function(*args, **kwargs):
# def index():
# def enroll():
# def configuration(node=None):
# def logger(node=None):
# def distributed_read(node=None):
# def distributed_write(node=None):
#
# Path: doorman/assets.py
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/settings.py
# class ProdConfig(Config):
#
# ENV = 'prod'
# DEBUG = False
# DEBUG_TB_ENABLED = False
# DEBUG_TB_INTERCEPT_REDIRECTS = False
#
# ENFORCE_SSL = True
#
# SQLALCHEMY_DATABASE_URI = ''
#
# DOORMAN_ENROLL_SECRET = [
#
# ]
# DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1
#
# BROKER_URL = ''
# CELERY_RESULT_BACKEND = ''
#
# Path: doorman/tasks.py
# def analyze_result(result, node):
# def learn_from_result(result, node):
# def example_task(one, two):
# def notify_of_node_enrollment(node):
# def alert_when_node_goes_offline():
#
# Path: doorman/utils.py
# def get_node_health(node):
# checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL']
# if isinstance(checkin_interval, (int, float)):
# checkin_interval = dt.timedelta(seconds=checkin_interval)
# if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval:
# return u'danger'
# else:
# return ''
#
# def pretty_field(field):
# return PRETTY_FIELDS.get(field, field)
#
# def pretty_operator(cond):
# return PRETTY_OPERATORS.get(cond, cond)
#
# def render_column(value, column):
# renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {})
# if column not in renders:
# return value
#
# template = renders[column]
#
# try:
# if callable(template):
# return template(value)
# else:
# template = Template(template, autoescape=True)
# rendered = template.render(value=value)
#
# # return a markup object so that the template where this is
# # rendered is not escaped again
#
# return Markup(rendered)
# except Exception:
# current_app.logger.exception(
# "Failed to render %s, returning original value",
# column
# )
# return value
. Output only the next line. | csrf.exempt(api) |
Given the code snippet: <|code_start|> app.config.from_object(config)
app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend blueprint. This is useful when you want
# to only deploy the api as a standalone service.
if 'DOORMAN_NO_MANAGER' in os.environ:
return
app.register_blueprint(backend)
def register_extensions(app):
bcrypt.init_app(app)
csrf.init_app(app)
<|code_end|>
, generate the next line using the imports in this file:
import os
import logging
import sys
from flask import Flask, render_template
from doorman.api import blueprint as api
from doorman.assets import assets
from doorman.manage import blueprint as backend
from doorman.extensions import (
bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager,
mail, make_celery, migrate, rule_manager, sentry
)
from doorman.settings import ProdConfig
from doorman.tasks import celery
from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column
from flask_sslify import SSLify
from logging.handlers import WatchedFileHandler
from doorman.users import views
from doorman.users.mixins import NoAuthUserMixin
from doorman.users.oauth import OAuthLogin
and context (functions, classes, or occasionally code) from other files:
# Path: doorman/api.py
# def node_required(f):
# def decorated_function(*args, **kwargs):
# def index():
# def enroll():
# def configuration(node=None):
# def logger(node=None):
# def distributed_read(node=None):
# def distributed_write(node=None):
#
# Path: doorman/assets.py
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/settings.py
# class ProdConfig(Config):
#
# ENV = 'prod'
# DEBUG = False
# DEBUG_TB_ENABLED = False
# DEBUG_TB_INTERCEPT_REDIRECTS = False
#
# ENFORCE_SSL = True
#
# SQLALCHEMY_DATABASE_URI = ''
#
# DOORMAN_ENROLL_SECRET = [
#
# ]
# DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1
#
# BROKER_URL = ''
# CELERY_RESULT_BACKEND = ''
#
# Path: doorman/tasks.py
# def analyze_result(result, node):
# def learn_from_result(result, node):
# def example_task(one, two):
# def notify_of_node_enrollment(node):
# def alert_when_node_goes_offline():
#
# Path: doorman/utils.py
# def get_node_health(node):
# checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL']
# if isinstance(checkin_interval, (int, float)):
# checkin_interval = dt.timedelta(seconds=checkin_interval)
# if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval:
# return u'danger'
# else:
# return ''
#
# def pretty_field(field):
# return PRETTY_FIELDS.get(field, field)
#
# def pretty_operator(cond):
# return PRETTY_OPERATORS.get(cond, cond)
#
# def render_column(value, column):
# renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {})
# if column not in renders:
# return value
#
# template = renders[column]
#
# try:
# if callable(template):
# return template(value)
# else:
# template = Template(template, autoescape=True)
# rendered = template.render(value=value)
#
# # return a markup object so that the template where this is
# # rendered is not escaped again
#
# return Markup(rendered)
# except Exception:
# current_app.logger.exception(
# "Failed to render %s, returning original value",
# column
# )
# return value
. Output only the next line. | db.init_app(app) |
Given the following code snippet before the placeholder: <|code_start|> register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend blueprint. This is useful when you want
# to only deploy the api as a standalone service.
if 'DOORMAN_NO_MANAGER' in os.environ:
return
app.register_blueprint(backend)
def register_extensions(app):
bcrypt.init_app(app)
csrf.init_app(app)
db.init_app(app)
migrate.init_app(app, db)
assets.init_app(app)
<|code_end|>
, predict the next line using imports from the current file:
import os
import logging
import sys
from flask import Flask, render_template
from doorman.api import blueprint as api
from doorman.assets import assets
from doorman.manage import blueprint as backend
from doorman.extensions import (
bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager,
mail, make_celery, migrate, rule_manager, sentry
)
from doorman.settings import ProdConfig
from doorman.tasks import celery
from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column
from flask_sslify import SSLify
from logging.handlers import WatchedFileHandler
from doorman.users import views
from doorman.users.mixins import NoAuthUserMixin
from doorman.users.oauth import OAuthLogin
and context including class names, function names, and sometimes code from other files:
# Path: doorman/api.py
# def node_required(f):
# def decorated_function(*args, **kwargs):
# def index():
# def enroll():
# def configuration(node=None):
# def logger(node=None):
# def distributed_read(node=None):
# def distributed_write(node=None):
#
# Path: doorman/assets.py
#
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
# class ContextTask(TaskBase):
# def __init__(self, app=None):
# def init_app(self, app):
# def handle_status(self, data, **kwargs):
# def handle_result(self, data, **kwargs):
# def __init__(self, app=None):
# def init_app(self, app):
# def load_alerters(self):
# def should_reload_rules(self):
# def load_rules(self):
# def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
# def __call__(self, *args, **kwargs):
#
# Path: doorman/settings.py
# class ProdConfig(Config):
#
# ENV = 'prod'
# DEBUG = False
# DEBUG_TB_ENABLED = False
# DEBUG_TB_INTERCEPT_REDIRECTS = False
#
# ENFORCE_SSL = True
#
# SQLALCHEMY_DATABASE_URI = ''
#
# DOORMAN_ENROLL_SECRET = [
#
# ]
# DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1
#
# BROKER_URL = ''
# CELERY_RESULT_BACKEND = ''
#
# Path: doorman/tasks.py
# def analyze_result(result, node):
# def learn_from_result(result, node):
# def example_task(one, two):
# def notify_of_node_enrollment(node):
# def alert_when_node_goes_offline():
#
# Path: doorman/utils.py
# def get_node_health(node):
# checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL']
# if isinstance(checkin_interval, (int, float)):
# checkin_interval = dt.timedelta(seconds=checkin_interval)
# if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval:
# return u'danger'
# else:
# return ''
#
# def pretty_field(field):
# return PRETTY_FIELDS.get(field, field)
#
# def pretty_operator(cond):
# return PRETTY_OPERATORS.get(cond, cond)
#
# def render_column(value, column):
# renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {})
# if column not in renders:
# return value
#
# template = renders[column]
#
# try:
# if callable(template):
# return template(value)
# else:
# template = Template(template, autoescape=True)
# rendered = template.render(value=value)
#
# # return a markup object so that the template where this is
# # rendered is not escaped again
#
# return Markup(rendered)
# except Exception:
# current_app.logger.exception(
# "Failed to render %s, returning original value",
# column
# )
# return value
. Output only the next line. | debug_toolbar.init_app(app) |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4