Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
class DummyExecutor(BaseExecutorPlugin):
hook_prefix = 'executors.dummy'
hooks = ('execute',)
def _parse_args_dict(self, args_dict):
if 'cmd' not in args_dict:
raise PluginError('DummyExecutor got incorrect arguments, got: {}'.format(
args_dict.keys()
))
return args_dict['cmd']
<|code_end|>
, predict the next line using imports from the current file:
from pipelines.plugins.base_executor import BaseExecutorPlugin
from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL
from pipelines.plugin.exceptions import PluginError
and context including class names, function names, and sometimes code from other files:
# Path: pipelines/plugins/base_executor.py
# class BaseExecutorPlugin(BasePlugin):
# dry_run = False
#
# def call(self, *args, **kwargs):
# result = self.execute(*args, **kwargs)
# if not isinstance(result, TaskResult):
# raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result)))
#
# return result
#
# def execute(self, command):
# print 'Running executor with command: %s' % command
#
# Path: pipelines/pipeline/task.py
# class TaskResult(dict):
# def __init__(self, status, message='', data={}, return_obj={}):
# self['status'] = status
# self['message'] = message
# self['data'] = data
# self['return_obj'] = return_obj
#
# @property
# def status(self):
# return self.get('status')
#
# @property
# def message(self):
# return self.get('message')
#
# @property
# def data(self):
# return self.get('data')
#
# @property
# def return_obj(self):
# return self.get('return_obj')
#
# def is_successful(self):
# return self.status == EXECUTION_SUCCESSFUL
#
# EXECUTION_SUCCESSFUL = 0
#
# Path: pipelines/plugin/exceptions.py
# class PluginError(RuntimeError):
# pass
. Output only the next line. | def execute(self, args_dict): |
Continue the code snippet: <|code_start|>
class DummyExecutor(BaseExecutorPlugin):
hook_prefix = 'executors.dummy'
hooks = ('execute',)
def _parse_args_dict(self, args_dict):
<|code_end|>
. Use current file imports:
from pipelines.plugins.base_executor import BaseExecutorPlugin
from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL
from pipelines.plugin.exceptions import PluginError
and context (classes, functions, or code) from other files:
# Path: pipelines/plugins/base_executor.py
# class BaseExecutorPlugin(BasePlugin):
# dry_run = False
#
# def call(self, *args, **kwargs):
# result = self.execute(*args, **kwargs)
# if not isinstance(result, TaskResult):
# raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result)))
#
# return result
#
# def execute(self, command):
# print 'Running executor with command: %s' % command
#
# Path: pipelines/pipeline/task.py
# class TaskResult(dict):
# def __init__(self, status, message='', data={}, return_obj={}):
# self['status'] = status
# self['message'] = message
# self['data'] = data
# self['return_obj'] = return_obj
#
# @property
# def status(self):
# return self.get('status')
#
# @property
# def message(self):
# return self.get('message')
#
# @property
# def data(self):
# return self.get('data')
#
# @property
# def return_obj(self):
# return self.get('return_obj')
#
# def is_successful(self):
# return self.status == EXECUTION_SUCCESSFUL
#
# EXECUTION_SUCCESSFUL = 0
#
# Path: pipelines/plugin/exceptions.py
# class PluginError(RuntimeError):
# pass
. Output only the next line. | if 'cmd' not in args_dict: |
Using the snippet: <|code_start|>
class DummyExecutor(BaseExecutorPlugin):
hook_prefix = 'executors.dummy'
hooks = ('execute',)
def _parse_args_dict(self, args_dict):
if 'cmd' not in args_dict:
raise PluginError('DummyExecutor got incorrect arguments, got: {}'.format(
<|code_end|>
, determine the next line of code. You have imports:
from pipelines.plugins.base_executor import BaseExecutorPlugin
from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL
from pipelines.plugin.exceptions import PluginError
and context (class names, function names, or code) available:
# Path: pipelines/plugins/base_executor.py
# class BaseExecutorPlugin(BasePlugin):
# dry_run = False
#
# def call(self, *args, **kwargs):
# result = self.execute(*args, **kwargs)
# if not isinstance(result, TaskResult):
# raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result)))
#
# return result
#
# def execute(self, command):
# print 'Running executor with command: %s' % command
#
# Path: pipelines/pipeline/task.py
# class TaskResult(dict):
# def __init__(self, status, message='', data={}, return_obj={}):
# self['status'] = status
# self['message'] = message
# self['data'] = data
# self['return_obj'] = return_obj
#
# @property
# def status(self):
# return self.get('status')
#
# @property
# def message(self):
# return self.get('message')
#
# @property
# def data(self):
# return self.get('data')
#
# @property
# def return_obj(self):
# return self.get('return_obj')
#
# def is_successful(self):
# return self.status == EXECUTION_SUCCESSFUL
#
# EXECUTION_SUCCESSFUL = 0
#
# Path: pipelines/plugin/exceptions.py
# class PluginError(RuntimeError):
# pass
. Output only the next line. | args_dict.keys() |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class UserProfileView(UpdateView):
template_name = "accounts/user_profile.html"
model = User
fields = ['first_name', 'last_name']
form_class = UserProfileForm
def get_object(self):
return self.request.user
def get_success_url(self):
return reverse('account_profile')
def get_context_data(self, *args, **kwargs):
context = super(UserProfileView, self).get_context_data(*args, **kwargs)
context['nav_user_profile'] = True
return context
class PasswordChangeView(TemplateView):
template_name = "registration/password_change.html"
def get_context_data(self, *args, **kwargs):
<|code_end|>
. Use current file imports:
from django.views.generic import TemplateView, UpdateView
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from .forms import UserProfileForm
and context (classes, functions, or code) from other files:
# Path: nsupdate/accounts/forms.py
# class UserProfileForm(forms.ModelForm):
# class Meta:
# model = User
# fields = ['first_name', 'last_name', ]
. Output only the next line. | context = super(PasswordChangeView, self).get_context_data(*args, **kwargs) |
Given the following code snippet before the placeholder: <|code_start|> self.defects = set()
@property
def all_cards(self):
return self.cards.union(self.defects)
def add_card(self, card):
defect_types = app.config.get('DEFECT_TYPES', ())
if card.type in defect_types:
self.defects.add(card)
else:
self.cards.add(card)
@property
def count(self):
return len(self.cards)
@property
def sorted_cards(self):
cards = list(self.cards)
cards.sort(key=lambda c: c.done_date, reverse=True)
return cards
@property
def sorted_defects(self):
defects = list(self.defects)
defects.sort(key=lambda c: c.done_date, reverse=True)
return defects
@property
<|code_end|>
, predict the next line using imports from the current file:
from kardboard.app import app
and context including class names, function names, and sometimes code from other files:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
. Output only the next line. | def cycle_time(self): |
Predict the next line after this snippet: <|code_start|>
self.config['CARD_STATES'] = [
'Todo',
'Doing',
'Done',
]
self.Form = self._get_target_class()
self.required_data = {
'key': u'CMSIF-199',
'title': u'You gotta lock that down',
'backlog_date': u"06/11/2011",
'state': u'Todo',
'team': u'Team 1',
'start_date': u'',
'done_date': u'',
'priority': u'',
}
def _post_data(self, thedict=None):
if thedict is None:
thedict = self.required_data
return MultiDict(thedict)
def _get_target_class(self, new=True):
return get_card_form(new=new)
def _test_form(self, post_data, new=True):
f = self._get_target_class(new)(self._post_data(post_data))
f.validate()
<|code_end|>
using the current file's imports:
import datetime
import unittest
from kardboard.tests.core import FormTests
from werkzeug.datastructures import MultiDict
from kardboard.forms import CardBlockForm
from werkzeug.datastructures import MultiDict
from kardboard.forms import get_card_form
from kardboard.models import States
from kardboard.models import States
from kardboard.models import States
and any relevant context from other files:
# Path: kardboard/tests/core.py
# class FormTests(KardboardTestCase):
# pass
. Output only the next line. | self.assertEquals(0, len(f.errors)) |
Given the code snippet: <|code_start|>
try:
DEBUG_TOOLBAR = True
except ImportError:
DEBUG_TOOLBAR = False
try:
SENTRY_SUPPORT = True
except ImportError:
SENTRY_SUPPORT = False
<|code_end|>
, generate the next line using the imports in this file:
import os
import socket
import path
import statsd
from flask import Flask
from flaskext.cache import Cache
from flask.ext.mongoengine import MongoEngine
from jinja2 import ModuleLoader
from flask_debugtoolbar import DebugToolbarExtension
from raven.contrib.flask import Sentry
from kardboard.util import (
slugify,
timesince,
timeuntil,
jsonencode,
configure_logging,
newrelic_head,
newrelic_foot,
FixGunicorn
)
and context (functions, classes, or occasionally code) from other files:
# Path: kardboard/util.py
# def slugify(text, delim=u'-'):
# """Generates an ASCII-only slug."""
# result = []
# text = text.replace("'", "")
# for word in _punct_re.split(text.lower()):
# word = word.encode('translit/long')
# if word:
# result.append(word)
# return unicode(delim.join(result)).strip()
#
# def timesince(dt, default="just now"):
# """
# Returns string representing "time since" e.g.
# 3 days ago, 5 hours ago etc.
# """
#
# now = datetime.datetime.now()
# diff = now - dt
#
# periods = (
# (diff.days / 365, "year", "years"),
# (diff.days / 30, "month", "months"),
# (diff.days / 7, "week", "weeks"),
# (diff.days, "day", "days"),
# (diff.seconds / 3600, "hour", "hours"),
# (diff.seconds / 60, "minute", "minutes"),
# (diff.seconds, "second", "seconds"),
# )
#
# for period, singular, plural in periods:
#
# if period:
# return "%d %s ago" % (period, singular if period == 1 else plural)
#
# return default
#
# def timeuntil(dt):
# """
# Returns string representing "time util" e.g.
# 3 days, 5 hours, etc.
# """
# tardis = 'future'
# now = datetime.datetime.now()
# if dt < now:
# tardis = 'past'
#
# if tardis == 'future':
# diff = relativedelta(dt, now)
# elif tardis == 'past':
# diff = relativedelta(now, dt)
#
# msg = []
# if diff.months > 0:
# msg.append("%s months" % diff.months)
# if diff.days > 0:
# msg.append("%s days" % diff.days)
# if diff.hours > 0 and diff.days <= 0:
# msg.append("%s hours" % diff.hours)
# if diff.minutes > 0 and diff.hours <= 0:
# msg.append("%s minutes" % diff.minutes)
#
# if len(msg) > 1:
# msg = ', '.join(msg)
# elif len(msg) == 1:
# msg = ''.join(msg)
#
# if tardis == 'future':
# msg = "In %s" % msg
# elif tardis == 'past':
# msg = "%s ago" % msg
#
# if msg:
# return msg
#
# return dt.strftime("%m/%d/%Y")
#
# def jsonencode(data):
# import json
# return json.dumps(data)
#
# def configure_logging(app):
# LEVELS = {'debug': logging.DEBUG,
# 'info': logging.INFO,
# 'warning': logging.WARNING,
# 'error': logging.ERROR,
# 'critical': logging.CRITICAL}
#
# if app.config.get('LOG_FILE'):
# log_file = app.config['LOG_FILE']
# log_file = os.path.abspath(os.path.expanduser(log_file))
# new_handler = RotatingFileHandler(
# log_file, maxBytes=100000, backupCount=3)
# if app.config.get('LOG_LEVEL'):
# new_level = app.config['LOG_LEVEL']
# new_level = LEVELS.get(new_level, logging.error)
# new_handler.setLevel(new_level)
#
# log_format = (
# '-' * 80 + '\n' +
# '%(asctime)-15s\n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +
# '%(message)s\n' +
# '-' * 80
# )
# new_handler.setFormatter(logging.Formatter(log_format))
#
# app.logger.addHandler(new_handler)
#
# def newrelic_head():
# agent = get_newrelic_agent()
# if agent:
# content = [
# '<!-- New Relic tracking -->'
# ]
# header = agent.get_browser_timing_header()
# content.append(header)
# return '\n'.join(content)
# return ''
#
# def newrelic_foot():
# agent = get_newrelic_agent()
# if agent:
# content = [
# '<!-- New Relic tracking -->'
# ]
# footer = agent.get_browser_timing_footer()
# content.append(footer)
# return '\n'.join(content)
# return ''
#
# class FixGunicorn(object):
# def __init__(self, app):
# self.app = app
#
# def __call__(self, environ, start_response):
# environ['SERVER_PORT'] = str(environ['SERVER_PORT'])
# return self.app(environ, start_response)
. Output only the next line. | def get_app(): |
Given the code snippet: <|code_start|>
try:
DEBUG_TOOLBAR = True
except ImportError:
DEBUG_TOOLBAR = False
try:
SENTRY_SUPPORT = True
except ImportError:
SENTRY_SUPPORT = False
def get_app():
app = Flask('kardboard')
<|code_end|>
, generate the next line using the imports in this file:
import os
import socket
import path
import statsd
from flask import Flask
from flaskext.cache import Cache
from flask.ext.mongoengine import MongoEngine
from jinja2 import ModuleLoader
from flask_debugtoolbar import DebugToolbarExtension
from raven.contrib.flask import Sentry
from kardboard.util import (
slugify,
timesince,
timeuntil,
jsonencode,
configure_logging,
newrelic_head,
newrelic_foot,
FixGunicorn
)
and context (functions, classes, or occasionally code) from other files:
# Path: kardboard/util.py
# def slugify(text, delim=u'-'):
# """Generates an ASCII-only slug."""
# result = []
# text = text.replace("'", "")
# for word in _punct_re.split(text.lower()):
# word = word.encode('translit/long')
# if word:
# result.append(word)
# return unicode(delim.join(result)).strip()
#
# def timesince(dt, default="just now"):
# """
# Returns string representing "time since" e.g.
# 3 days ago, 5 hours ago etc.
# """
#
# now = datetime.datetime.now()
# diff = now - dt
#
# periods = (
# (diff.days / 365, "year", "years"),
# (diff.days / 30, "month", "months"),
# (diff.days / 7, "week", "weeks"),
# (diff.days, "day", "days"),
# (diff.seconds / 3600, "hour", "hours"),
# (diff.seconds / 60, "minute", "minutes"),
# (diff.seconds, "second", "seconds"),
# )
#
# for period, singular, plural in periods:
#
# if period:
# return "%d %s ago" % (period, singular if period == 1 else plural)
#
# return default
#
# def timeuntil(dt):
# """
# Returns string representing "time util" e.g.
# 3 days, 5 hours, etc.
# """
# tardis = 'future'
# now = datetime.datetime.now()
# if dt < now:
# tardis = 'past'
#
# if tardis == 'future':
# diff = relativedelta(dt, now)
# elif tardis == 'past':
# diff = relativedelta(now, dt)
#
# msg = []
# if diff.months > 0:
# msg.append("%s months" % diff.months)
# if diff.days > 0:
# msg.append("%s days" % diff.days)
# if diff.hours > 0 and diff.days <= 0:
# msg.append("%s hours" % diff.hours)
# if diff.minutes > 0 and diff.hours <= 0:
# msg.append("%s minutes" % diff.minutes)
#
# if len(msg) > 1:
# msg = ', '.join(msg)
# elif len(msg) == 1:
# msg = ''.join(msg)
#
# if tardis == 'future':
# msg = "In %s" % msg
# elif tardis == 'past':
# msg = "%s ago" % msg
#
# if msg:
# return msg
#
# return dt.strftime("%m/%d/%Y")
#
# def jsonencode(data):
# import json
# return json.dumps(data)
#
# def configure_logging(app):
# LEVELS = {'debug': logging.DEBUG,
# 'info': logging.INFO,
# 'warning': logging.WARNING,
# 'error': logging.ERROR,
# 'critical': logging.CRITICAL}
#
# if app.config.get('LOG_FILE'):
# log_file = app.config['LOG_FILE']
# log_file = os.path.abspath(os.path.expanduser(log_file))
# new_handler = RotatingFileHandler(
# log_file, maxBytes=100000, backupCount=3)
# if app.config.get('LOG_LEVEL'):
# new_level = app.config['LOG_LEVEL']
# new_level = LEVELS.get(new_level, logging.error)
# new_handler.setLevel(new_level)
#
# log_format = (
# '-' * 80 + '\n' +
# '%(asctime)-15s\n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +
# '%(message)s\n' +
# '-' * 80
# )
# new_handler.setFormatter(logging.Formatter(log_format))
#
# app.logger.addHandler(new_handler)
#
# def newrelic_head():
# agent = get_newrelic_agent()
# if agent:
# content = [
# '<!-- New Relic tracking -->'
# ]
# header = agent.get_browser_timing_header()
# content.append(header)
# return '\n'.join(content)
# return ''
#
# def newrelic_foot():
# agent = get_newrelic_agent()
# if agent:
# content = [
# '<!-- New Relic tracking -->'
# ]
# footer = agent.get_browser_timing_footer()
# content.append(footer)
# return '\n'.join(content)
# return ''
#
# class FixGunicorn(object):
# def __init__(self, app):
# self.app = app
#
# def __call__(self, environ, start_response):
# environ['SERVER_PORT'] = str(environ['SERVER_PORT'])
# return self.app(environ, start_response)
. Output only the next line. | app.config.from_object('kardboard.default_settings') |
Continue the code snippet: <|code_start|>
class Team(object):
def __init__(self, name):
self.name = name.strip()
@property
def slug(self):
return slugify(self.name)
class TeamList(list):
def __init__(self, *args):
super(TeamList, self).__init__(args)
self.teams = args
@property
def names(self):
return [t.name for t in self.teams]
<|code_end|>
. Use current file imports:
from kardboard.util import slugify
and context (classes, functions, or code) from other files:
# Path: kardboard/util.py
# def slugify(text, delim=u'-'):
# """Generates an ASCII-only slug."""
# result = []
# text = text.replace("'", "")
# for word in _punct_re.split(text.lower()):
# word = word.encode('translit/long')
# if word:
# result.append(word)
# return unicode(delim.join(result)).strip()
. Output only the next line. | @property |
Here is a snippet: <|code_start|>#!/usr/bin/env python
from __future__ import absolute_import
celery = Celery(app)
manager = Manager(app)
install_celery_commands(manager)
if __name__ == "__main__":
<|code_end|>
. Write the next line using the current file imports:
from flask.ext.script import Manager
from flask.ext.celery import Celery
from flask.ext.celery import install_commands as install_celery_commands
from kardboard.app import app
and context from other files:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
, which may include functions, classes, or code. Output only the next line. | manager.run() |
Using the snippet: <|code_start|>
def report_on_cards(cards):
data = {}
for k in cards:
class_cards = data.get(k.service_class.get('name'), [])
class_cards.append(k)
data[k.service_class.get('name')] = class_cards
total = sum([len(v) for k, v in data.items()])
report = {}
for classname, cards in data.items():
sclass = cards[0].service_class
cycle_time_average = int(round(average(
[c.current_cycle_time() for c in cards])))
cards_hit_goal = len([c.key for c in cards
if c.current_cycle_time() <= sclass.get('upper')])
report[classname] = {
'service_class': sclass.get('name'),
'wip': len(cards),
'wip_percent': len(cards) / float(total),
'cycle_time_average': cycle_time_average,
'cards_hit_goal': cards_hit_goal,
<|code_end|>
, determine the next line of code. You have imports:
from kardboard.app import app
from kardboard.util import (
now,
make_end_date,
make_start_date,
average,
)
from kardboard.models import Kard
from kardboard.models import ReportGroup
from kardboard.models import Kard
from kardboard.models import ReportGroup
and context (class names, function names, or code) available:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# def now():
# return datetime.datetime.now()
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
. Output only the next line. | 'cards_hit_goal_percent': cards_hit_goal / float(len(cards)), |
Here is a snippet: <|code_start|>
def report_on_cards(cards):
data = {}
for k in cards:
class_cards = data.get(k.service_class.get('name'), [])
class_cards.append(k)
data[k.service_class.get('name')] = class_cards
total = sum([len(v) for k, v in data.items()])
report = {}
for classname, cards in data.items():
sclass = cards[0].service_class
cycle_time_average = int(round(average(
[c.current_cycle_time() for c in cards])))
cards_hit_goal = len([c.key for c in cards
if c.current_cycle_time() <= sclass.get('upper')])
report[classname] = {
'service_class': sclass.get('name'),
<|code_end|>
. Write the next line using the current file imports:
from kardboard.app import app
from kardboard.util import (
now,
make_end_date,
make_start_date,
average,
)
from kardboard.models import Kard
from kardboard.models import ReportGroup
from kardboard.models import Kard
from kardboard.models import ReportGroup
and context from other files:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# def now():
# return datetime.datetime.now()
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
, which may include functions, classes, or code. Output only the next line. | 'wip': len(cards), |
Given snippet: <|code_start|>
def report_on_cards(cards):
data = {}
for k in cards:
class_cards = data.get(k.service_class.get('name'), [])
class_cards.append(k)
data[k.service_class.get('name')] = class_cards
total = sum([len(v) for k, v in data.items()])
report = {}
for classname, cards in data.items():
sclass = cards[0].service_class
cycle_time_average = int(round(average(
[c.current_cycle_time() for c in cards])))
cards_hit_goal = len([c.key for c in cards
if c.current_cycle_time() <= sclass.get('upper')])
report[classname] = {
'service_class': sclass.get('name'),
'wip': len(cards),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from kardboard.app import app
from kardboard.util import (
now,
make_end_date,
make_start_date,
average,
)
from kardboard.models import Kard
from kardboard.models import ReportGroup
from kardboard.models import Kard
from kardboard.models import ReportGroup
and context:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# def now():
# return datetime.datetime.now()
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
which might include code, classes, or functions. Output only the next line. | 'wip_percent': len(cards) / float(total), |
Using the snippet: <|code_start|>
def report_on_cards(cards):
data = {}
for k in cards:
class_cards = data.get(k.service_class.get('name'), [])
class_cards.append(k)
data[k.service_class.get('name')] = class_cards
total = sum([len(v) for k, v in data.items()])
report = {}
for classname, cards in data.items():
sclass = cards[0].service_class
cycle_time_average = int(round(average(
[c.current_cycle_time() for c in cards])))
cards_hit_goal = len([c.key for c in cards
if c.current_cycle_time() <= sclass.get('upper')])
report[classname] = {
'service_class': sclass.get('name'),
'wip': len(cards),
'wip_percent': len(cards) / float(total),
'cycle_time_average': cycle_time_average,
'cards_hit_goal': cards_hit_goal,
'cards_hit_goal_percent': cards_hit_goal / float(len(cards)),
<|code_end|>
, determine the next line of code. You have imports:
from kardboard.app import app
from kardboard.util import (
now,
make_end_date,
make_start_date,
average,
)
from kardboard.models import Kard
from kardboard.models import ReportGroup
from kardboard.models import Kard
from kardboard.models import ReportGroup
and context (class names, function names, or code) available:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# def now():
# return datetime.datetime.now()
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
. Output only the next line. | } |
Predict the next line after this snippet: <|code_start|>
class KardTimeMachineTests(KardboardTestCase):
def setUp(self):
super(KardTimeMachineTests, self).setUp()
self._set_up_data()
def _get_target_class(self):
return self._get_card_class()
def _make_one(self, **kwargs):
return self.make_card(**kwargs)
def _set_up_data(self):
klass = self._get_target_class()
# Simulate creating 5 cards and moving
# some forward
backlog_date = datetime.datetime(
year=2011, month=5, day=30)
for i in xrange(0, 5):
c = self._make_one(backlog_date=backlog_date)
c.save()
cards = klass.objects.all()[:2]
for c in cards:
<|code_end|>
using the current file's imports:
import datetime
from kardboard.tests.core import KardboardTestCase
and any relevant context from other files:
# Path: kardboard/tests/core.py
# class KardboardTestCase(unittest2.TestCase):
# def setUp(self):
# if os.environ.get('KARDBOARD_SETTINGS'):
# os.environ['KARDBOARD_SETTINGS'] = ''
#
# from kardboard import default_settings
# default_settings.TEMPLATE_DEBUG = True
# from kardboard.views import app
# from flask.ext.mongoengine import MongoEngine
# from kardboard.util import now
#
# delattr(app, 'db')
# from mongoengine.connection import connect, disconnect
# disconnect()
#
# app.config.from_object('kardboard.default_settings')
# app.config['MONGODB_DB'] = 'kardboard_unittest'
# app.config['TESTING'] = True
# app.config['CELERY_ALWAYS_EAGER'] = True
# connect(app.config['MONGODB_DB'])
# app.db = MongoEngine(app)
#
# self.config = app.config
# self.app = app.test_client()
# self.flask_app = app
#
# self.used_keys = []
# self._setup_logging()
# self.now = now
#
# super(KardboardTestCase, self).setUp()
#
# def tearDown(self):
# if hasattr(self.config, 'TICKET_HELPER'):
# del self.config['TICKET_HELPER']
# self._flush_db()
# self.flask_app.logger.handlers = self._old_logging_handlers
#
# def _setup_logging(self):
# self._old_logging_handlers = self.flask_app.logger.handlers
# del self.flask_app.logger.handlers[:]
# new_handler = logging.StreamHandler()
# new_handler.setLevel(logging.CRITICAL)
# new_handler.setFormatter(logging.Formatter(self.flask_app.debug_log_format))
# self.flask_app.logger.addHandler(new_handler)
#
# def _flush_db(self):
# from mongoengine.connection import _get_db
# db = _get_db()
# #Truncate/wipe the test database
# names = [name for name in db.collection_names()
# if 'system.' not in name]
# [db.drop_collection(name) for name in names]
#
# def _get_target_url(self):
# raise NotImplementedError
#
# def _get_target_class(self):
# raise NotImplementedError
#
# def _make_one(self, *args, **kwargs):
# return self._get_target_class()(*args, **kwargs)
#
# def _get_card_class(self):
# from kardboard.models import Kard
# return Kard
#
# def _get_record_class(self):
# from kardboard.models import DailyRecord
# return DailyRecord
#
# def _get_person_class(self):
# from kardboard.models import Person
# return Person
#
# def _make_unique_key(self):
# key = random.randint(1, 10000)
# if key not in self.used_keys:
# self.used_keys.append(key)
# return key
# return self._make_unique_key()
#
# def _date(self, dtype, date=None, days=0):
# from kardboard.util import make_end_date, make_start_date
# from kardboard.util import now
#
# if not date:
# date = now()
#
# if dtype == 'start':
# date = make_start_date(date=date)
# elif dtype == 'end':
# date = make_end_date(date=date)
#
# date = date + relativedelta(days=days)
# return date
#
# def make_card(self, **kwargs):
# from kardboard.util import now
# key = self._make_unique_key()
# fields = {
# 'key': "CMSAD-%s" % key,
# 'title': "Theres always money in the banana stand",
# 'backlog_date': now()
# }
# fields.update(**kwargs)
# k = self._get_card_class()(**fields)
# return k
#
# def delete_all_cards(self):
# self._get_card_class().objects.all().delete()
#
# def make_record(self, date, **kwargs):
# fields = {
# 'date': date,
# 'backlog': 3,
# 'in_progress': 8,
# 'done': 10,
# 'completed': 1,
# 'moving_cycle_time': 12,
# 'moving_lead_time': 16,
# 'moving_std_dev': 69,
# 'moving_median_abs_dev': 30,
# }
# fields.update(**kwargs)
# r = self._get_record_class()(**fields)
# return r
#
# def make_person(self, **kwargs):
# key = self._make_unique_key()
# fields = {
# 'name': 'cheisel-%s' % key,
# }
# fields.update(**kwargs)
# p = self._get_person_class()(**fields)
# return p
#
# def assertEqualDateTimes(self, expected, actual):
# expected = (expected.year, expected.month, expected.day, expected.hour, expected.minute)
# actual = (actual.year, actual.month, actual.day, actual.hour, actual.minute)
# self.assertEqual(expected, actual)
. Output only the next line. | c.start_date = backlog_date.replace(day=31) |
Using the snippet: <|code_start|>
class State(object):
def __init__(self, name, buffer, is_buffer):
self.name = name
self.buffer = buffer
self.is_buffer = is_buffer
def __unicode__(self):
<|code_end|>
, determine the next line of code. You have imports:
from kardboard.app import app
from kardboard.util import slugify
and context (class names, function names, or code) available:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# def slugify(text, delim=u'-'):
# """Generates an ASCII-only slug."""
# result = []
# text = text.replace("'", "")
# for word in _punct_re.split(text.lower()):
# word = word.encode('translit/long')
# if word:
# result.append(word)
# return unicode(delim.join(result)).strip()
. Output only the next line. | return unicode(self.name) |
Continue the code snippet: <|code_start|>
class State(object):
def __init__(self, name, buffer, is_buffer):
self.name = name
self.buffer = buffer
self.is_buffer = is_buffer
def __unicode__(self):
return unicode(self.name)
<|code_end|>
. Use current file imports:
from kardboard.app import app
from kardboard.util import slugify
and context (classes, functions, or code) from other files:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# def slugify(text, delim=u'-'):
# """Generates an ASCII-only slug."""
# result = []
# text = text.replace("'", "")
# for word in _punct_re.split(text.lower()):
# word = word.encode('translit/long')
# if word:
# result.append(word)
# return unicode(delim.join(result)).strip()
. Output only the next line. | def __str__(self): |
Given the code snippet: <|code_start|> d[c] += 1
return dict(d)
def state_transition_counts(state, months, count_type="exit", raw=False):
end = make_end_date(date=datetime.datetime.now())
start = end - relativedelta(months=months)
start = make_start_date(date=start)
counts = []
data = []
current_date = start
while current_date <= end:
if current_date.weekday() == 5: # Saturday
current_date += relativedelta(days=2)
elif current_date.weekday() == 6: # Sunday
current_date += relativedelta(days=1)
range_start = make_start_date(date=current_date)
range_end = make_end_date(date=current_date)
if count_type == "exit":
kwargs = dict(
exited__gte=range_start,
exited__lte=range_end,
)
elif count_type == "enter":
kwargs = dict(
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import sys
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from kardboard.util import make_start_date, make_end_date, average, median
from kardboard.models.statelog import StateLog
and context (functions, classes, or occasionally code) from other files:
# Path: kardboard/util.py
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
#
# def median(values):
# try:
# return stats.median(values)
# except (ValueError, UnboundLocalError):
# return None
#
# Path: kardboard/models/statelog.py
# class StateLog(app.db.Document):
# card = app.db.ReferenceField(
# 'Kard',
# reverse_delete_rule=app.db.CASCADE,
# required=True,
# dbref=False,
# )
# # Card that this record is about
# state = app.db.StringField(required=True)
# # The state the card was in for this record
# entered = app.db.DateTimeField(required=True)
# # Datetime the card entered its state
# exited = app.db.DateTimeField(required=False)
# # Datetime the card exited this state
# _duration = app.db.IntField(required=False)
# # The duration the card was in this state
# service_class = app.db.StringField(required=False)
# # The service class the card was in while in this state
#
# created_at = app.db.DateTimeField(required=True)
# updated_at = app.db.DateTimeField(required=True)
#
# meta = {
# 'cascade': False,
# 'ordering': ['-created_at'],
# 'indexes': ['card', 'state', ['card', 'created_at']]
# }
#
# def save(self, *args, **kwargs):
# if self.id is None:
# self.created_at = now()
# if self.entered and self.exited:
# self._duration = self.duration
# self.updated_at = now()
# super(StateLog, self).save(*args, **kwargs)
#
# def __repr__(self):
# return "<StateLog: %s, %s, %s -- %s, %s hours>" % (
# self.card.key,
# self.state,
# self.entered,
# self.exited,
# self._duration
# )
#
# @classmethod
# def kard_pre_save(cls, sender, document, **kwargs):
# observed_card = document
#
# if observed_card.state_changing is False:
# # No need to worry about logging it, nothing's changing!
# return None
#
# try:
# observed_card.old_state
# except AttributeError:
# raise
#
# # If you're here it's because the observed_card's state is changing
# if observed_card.old_state is not None:
# try:
# slos = cls.objects.filter(
# card=observed_card,
# state=observed_card.old_state,
# service_class=observed_card.service_class.get('name'),
# exited__exists=False)
# for s in slos:
# s.exited = now()
# s.save() # Close the old state log
# except cls.DoesNotExist:
# # For some reason we didn't record the old state, this should only happen when first rolled out
# pass
#
# @classmethod
# def kard_post_save(cls, sender, document, **kwargs):
# observed_card = document
#
# # Is there a currently open state log
# logs = cls.objects.filter(
# card=observed_card,
# state=observed_card.state,
# exited__exists=False,
# ).order_by('-entered')
# if len(logs) == 0:
# sl = cls(
# card=observed_card,
# state=observed_card.state,
# entered=now()
# )
# else:
# sl = logs[0]
#
# sl.service_class = observed_card.service_class.get('name')
# sl.save()
#
# @property
# def duration(self):
# if self._duration is not None:
# return self._duration
#
# if self.exited is not None:
# exited = self.exited
# else:
# exited = now()
# delta = exited - self.entered
# return delta_in_hours(delta)
. Output only the next line. | entered__gte=range_start, |
Given the following code snippet before the placeholder: <|code_start|> exited__gte=range_start,
exited__lte=range_end,
)
elif count_type == "enter":
kwargs = dict(
entered__gte=range_start,
entered__lte=range_end,
)
count = StateLog.objects.filter(
state=state,
**kwargs
).count()
data.append((current_date, count))
counts.append(count)
current_date = current_date + relativedelta(days=1)
counts.sort()
print "%s\t%s" % (start, end)
print "Median\t%s" % median(counts)
print "Average\t%s" % average(counts)
print "Min\t%s" % counts[0]
print "Max\t%s" % counts[-1]
hist = histogram(counts)
keys = hist.keys()
keys.sort()
for k in keys:
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import sys
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from kardboard.util import make_start_date, make_end_date, average, median
from kardboard.models.statelog import StateLog
and context including class names, function names, and sometimes code from other files:
# Path: kardboard/util.py
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
#
# def median(values):
# try:
# return stats.median(values)
# except (ValueError, UnboundLocalError):
# return None
#
# Path: kardboard/models/statelog.py
# class StateLog(app.db.Document):
# card = app.db.ReferenceField(
# 'Kard',
# reverse_delete_rule=app.db.CASCADE,
# required=True,
# dbref=False,
# )
# # Card that this record is about
# state = app.db.StringField(required=True)
# # The state the card was in for this record
# entered = app.db.DateTimeField(required=True)
# # Datetime the card entered its state
# exited = app.db.DateTimeField(required=False)
# # Datetime the card exited this state
# _duration = app.db.IntField(required=False)
# # The duration the card was in this state
# service_class = app.db.StringField(required=False)
# # The service class the card was in while in this state
#
# created_at = app.db.DateTimeField(required=True)
# updated_at = app.db.DateTimeField(required=True)
#
# meta = {
# 'cascade': False,
# 'ordering': ['-created_at'],
# 'indexes': ['card', 'state', ['card', 'created_at']]
# }
#
# def save(self, *args, **kwargs):
# if self.id is None:
# self.created_at = now()
# if self.entered and self.exited:
# self._duration = self.duration
# self.updated_at = now()
# super(StateLog, self).save(*args, **kwargs)
#
# def __repr__(self):
# return "<StateLog: %s, %s, %s -- %s, %s hours>" % (
# self.card.key,
# self.state,
# self.entered,
# self.exited,
# self._duration
# )
#
# @classmethod
# def kard_pre_save(cls, sender, document, **kwargs):
# observed_card = document
#
# if observed_card.state_changing is False:
# # No need to worry about logging it, nothing's changing!
# return None
#
# try:
# observed_card.old_state
# except AttributeError:
# raise
#
# # If you're here it's because the observed_card's state is changing
# if observed_card.old_state is not None:
# try:
# slos = cls.objects.filter(
# card=observed_card,
# state=observed_card.old_state,
# service_class=observed_card.service_class.get('name'),
# exited__exists=False)
# for s in slos:
# s.exited = now()
# s.save() # Close the old state log
# except cls.DoesNotExist:
# # For some reason we didn't record the old state, this should only happen when first rolled out
# pass
#
# @classmethod
# def kard_post_save(cls, sender, document, **kwargs):
# observed_card = document
#
# # Is there a currently open state log
# logs = cls.objects.filter(
# card=observed_card,
# state=observed_card.state,
# exited__exists=False,
# ).order_by('-entered')
# if len(logs) == 0:
# sl = cls(
# card=observed_card,
# state=observed_card.state,
# entered=now()
# )
# else:
# sl = logs[0]
#
# sl.service_class = observed_card.service_class.get('name')
# sl.save()
#
# @property
# def duration(self):
# if self._duration is not None:
# return self._duration
#
# if self.exited is not None:
# exited = self.exited
# else:
# exited = now()
# delta = exited - self.entered
# return delta_in_hours(delta)
. Output only the next line. | print "%s\t%s" % (k, hist[k]) |
Using the snippet: <|code_start|> current_date = current_date + relativedelta(days=1)
counts.sort()
print "%s\t%s" % (start, end)
print "Median\t%s" % median(counts)
print "Average\t%s" % average(counts)
print "Min\t%s" % counts[0]
print "Max\t%s" % counts[-1]
hist = histogram(counts)
keys = hist.keys()
keys.sort()
for k in keys:
print "%s\t%s" % (k, hist[k])
if raw is True:
for date, count in data:
print "%s\t%s" % (date, count)
if __name__ == "__main__":
try:
raw = bool(sys.argv[4])
except IndexError:
raw = False
try:
state = sys.argv[1]
months = int(sys.argv[2])
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import sys
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from kardboard.util import make_start_date, make_end_date, average, median
from kardboard.models.statelog import StateLog
and context (class names, function names, or code) available:
# Path: kardboard/util.py
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
#
# def median(values):
# try:
# return stats.median(values)
# except (ValueError, UnboundLocalError):
# return None
#
# Path: kardboard/models/statelog.py
# class StateLog(app.db.Document):
# card = app.db.ReferenceField(
# 'Kard',
# reverse_delete_rule=app.db.CASCADE,
# required=True,
# dbref=False,
# )
# # Card that this record is about
# state = app.db.StringField(required=True)
# # The state the card was in for this record
# entered = app.db.DateTimeField(required=True)
# # Datetime the card entered its state
# exited = app.db.DateTimeField(required=False)
# # Datetime the card exited this state
# _duration = app.db.IntField(required=False)
# # The duration the card was in this state
# service_class = app.db.StringField(required=False)
# # The service class the card was in while in this state
#
# created_at = app.db.DateTimeField(required=True)
# updated_at = app.db.DateTimeField(required=True)
#
# meta = {
# 'cascade': False,
# 'ordering': ['-created_at'],
# 'indexes': ['card', 'state', ['card', 'created_at']]
# }
#
# def save(self, *args, **kwargs):
# if self.id is None:
# self.created_at = now()
# if self.entered and self.exited:
# self._duration = self.duration
# self.updated_at = now()
# super(StateLog, self).save(*args, **kwargs)
#
# def __repr__(self):
# return "<StateLog: %s, %s, %s -- %s, %s hours>" % (
# self.card.key,
# self.state,
# self.entered,
# self.exited,
# self._duration
# )
#
# @classmethod
# def kard_pre_save(cls, sender, document, **kwargs):
# observed_card = document
#
# if observed_card.state_changing is False:
# # No need to worry about logging it, nothing's changing!
# return None
#
# try:
# observed_card.old_state
# except AttributeError:
# raise
#
# # If you're here it's because the observed_card's state is changing
# if observed_card.old_state is not None:
# try:
# slos = cls.objects.filter(
# card=observed_card,
# state=observed_card.old_state,
# service_class=observed_card.service_class.get('name'),
# exited__exists=False)
# for s in slos:
# s.exited = now()
# s.save() # Close the old state log
# except cls.DoesNotExist:
# # For some reason we didn't record the old state, this should only happen when first rolled out
# pass
#
# @classmethod
# def kard_post_save(cls, sender, document, **kwargs):
# observed_card = document
#
# # Is there a currently open state log
# logs = cls.objects.filter(
# card=observed_card,
# state=observed_card.state,
# exited__exists=False,
# ).order_by('-entered')
# if len(logs) == 0:
# sl = cls(
# card=observed_card,
# state=observed_card.state,
# entered=now()
# )
# else:
# sl = logs[0]
#
# sl.service_class = observed_card.service_class.get('name')
# sl.save()
#
# @property
# def duration(self):
# if self._duration is not None:
# return self._duration
#
# if self.exited is not None:
# exited = self.exited
# else:
# exited = now()
# delta = exited - self.entered
# return delta_in_hours(delta)
. Output only the next line. | count_type = sys.argv[3] |
Given the following code snippet before the placeholder: <|code_start|>
def histogram(counts):
d = defaultdict(int)
for c in counts:
d[c] += 1
return dict(d)
def state_transition_counts(state, months, count_type="exit", raw=False):
end = make_end_date(date=datetime.datetime.now())
start = end - relativedelta(months=months)
start = make_start_date(date=start)
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import sys
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from kardboard.util import make_start_date, make_end_date, average, median
from kardboard.models.statelog import StateLog
and context including class names, function names, and sometimes code from other files:
# Path: kardboard/util.py
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
#
# def median(values):
# try:
# return stats.median(values)
# except (ValueError, UnboundLocalError):
# return None
#
# Path: kardboard/models/statelog.py
# class StateLog(app.db.Document):
# card = app.db.ReferenceField(
# 'Kard',
# reverse_delete_rule=app.db.CASCADE,
# required=True,
# dbref=False,
# )
# # Card that this record is about
# state = app.db.StringField(required=True)
# # The state the card was in for this record
# entered = app.db.DateTimeField(required=True)
# # Datetime the card entered its state
# exited = app.db.DateTimeField(required=False)
# # Datetime the card exited this state
# _duration = app.db.IntField(required=False)
# # The duration the card was in this state
# service_class = app.db.StringField(required=False)
# # The service class the card was in while in this state
#
# created_at = app.db.DateTimeField(required=True)
# updated_at = app.db.DateTimeField(required=True)
#
# meta = {
# 'cascade': False,
# 'ordering': ['-created_at'],
# 'indexes': ['card', 'state', ['card', 'created_at']]
# }
#
# def save(self, *args, **kwargs):
# if self.id is None:
# self.created_at = now()
# if self.entered and self.exited:
# self._duration = self.duration
# self.updated_at = now()
# super(StateLog, self).save(*args, **kwargs)
#
# def __repr__(self):
# return "<StateLog: %s, %s, %s -- %s, %s hours>" % (
# self.card.key,
# self.state,
# self.entered,
# self.exited,
# self._duration
# )
#
# @classmethod
# def kard_pre_save(cls, sender, document, **kwargs):
# observed_card = document
#
# if observed_card.state_changing is False:
# # No need to worry about logging it, nothing's changing!
# return None
#
# try:
# observed_card.old_state
# except AttributeError:
# raise
#
# # If you're here it's because the observed_card's state is changing
# if observed_card.old_state is not None:
# try:
# slos = cls.objects.filter(
# card=observed_card,
# state=observed_card.old_state,
# service_class=observed_card.service_class.get('name'),
# exited__exists=False)
# for s in slos:
# s.exited = now()
# s.save() # Close the old state log
# except cls.DoesNotExist:
# # For some reason we didn't record the old state, this should only happen when first rolled out
# pass
#
# @classmethod
# def kard_post_save(cls, sender, document, **kwargs):
# observed_card = document
#
# # Is there a currently open state log
# logs = cls.objects.filter(
# card=observed_card,
# state=observed_card.state,
# exited__exists=False,
# ).order_by('-entered')
# if len(logs) == 0:
# sl = cls(
# card=observed_card,
# state=observed_card.state,
# entered=now()
# )
# else:
# sl = logs[0]
#
# sl.service_class = observed_card.service_class.get('name')
# sl.save()
#
# @property
# def duration(self):
# if self._duration is not None:
# return self._duration
#
# if self.exited is not None:
# exited = self.exited
# else:
# exited = now()
# delta = exited - self.entered
# return delta_in_hours(delta)
. Output only the next line. | counts = [] |
Given snippet: <|code_start|> counts.sort()
print "%s\t%s" % (start, end)
print "Median\t%s" % median(counts)
print "Average\t%s" % average(counts)
print "Min\t%s" % counts[0]
print "Max\t%s" % counts[-1]
hist = histogram(counts)
keys = hist.keys()
keys.sort()
for k in keys:
print "%s\t%s" % (k, hist[k])
if raw is True:
for date, count in data:
print "%s\t%s" % (date, count)
if __name__ == "__main__":
try:
raw = bool(sys.argv[4])
except IndexError:
raw = False
try:
state = sys.argv[1]
months = int(sys.argv[2])
count_type = sys.argv[3]
except IndexError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import sys
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from kardboard.util import make_start_date, make_end_date, average, median
from kardboard.models.statelog import StateLog
and context:
# Path: kardboard/util.py
# def make_start_date(year=None, month=None, day=None, date=None):
# start_date = munge_date(year, month, day, date)
# start_date = start_date.replace(hour=23, minute=59, second=59)
# start_date = start_date.replace(hour=0, minute=0, second=0)
# return start_date
#
# def make_end_date(year=None, month=None, day=None, date=None):
# end_date = munge_date(year, month, day, date)
# end_date = end_date.replace(hour=23, minute=59, second=59)
# return end_date
#
# def average(values):
# """Computes the arithmetic mean of a list of numbers.
#
# >>> print average([20, 30, 70])
# 40.0
# """
# try:
# return stats.mean(values)
# except ZeroDivisionError:
# return None
#
# def median(values):
# try:
# return stats.median(values)
# except (ValueError, UnboundLocalError):
# return None
#
# Path: kardboard/models/statelog.py
# class StateLog(app.db.Document):
# card = app.db.ReferenceField(
# 'Kard',
# reverse_delete_rule=app.db.CASCADE,
# required=True,
# dbref=False,
# )
# # Card that this record is about
# state = app.db.StringField(required=True)
# # The state the card was in for this record
# entered = app.db.DateTimeField(required=True)
# # Datetime the card entered its state
# exited = app.db.DateTimeField(required=False)
# # Datetime the card exited this state
# _duration = app.db.IntField(required=False)
# # The duration the card was in this state
# service_class = app.db.StringField(required=False)
# # The service class the card was in while in this state
#
# created_at = app.db.DateTimeField(required=True)
# updated_at = app.db.DateTimeField(required=True)
#
# meta = {
# 'cascade': False,
# 'ordering': ['-created_at'],
# 'indexes': ['card', 'state', ['card', 'created_at']]
# }
#
# def save(self, *args, **kwargs):
# if self.id is None:
# self.created_at = now()
# if self.entered and self.exited:
# self._duration = self.duration
# self.updated_at = now()
# super(StateLog, self).save(*args, **kwargs)
#
# def __repr__(self):
# return "<StateLog: %s, %s, %s -- %s, %s hours>" % (
# self.card.key,
# self.state,
# self.entered,
# self.exited,
# self._duration
# )
#
# @classmethod
# def kard_pre_save(cls, sender, document, **kwargs):
# observed_card = document
#
# if observed_card.state_changing is False:
# # No need to worry about logging it, nothing's changing!
# return None
#
# try:
# observed_card.old_state
# except AttributeError:
# raise
#
# # If you're here it's because the observed_card's state is changing
# if observed_card.old_state is not None:
# try:
# slos = cls.objects.filter(
# card=observed_card,
# state=observed_card.old_state,
# service_class=observed_card.service_class.get('name'),
# exited__exists=False)
# for s in slos:
# s.exited = now()
# s.save() # Close the old state log
# except cls.DoesNotExist:
# # For some reason we didn't record the old state, this should only happen when first rolled out
# pass
#
# @classmethod
# def kard_post_save(cls, sender, document, **kwargs):
# observed_card = document
#
# # Is there a currently open state log
# logs = cls.objects.filter(
# card=observed_card,
# state=observed_card.state,
# exited__exists=False,
# ).order_by('-entered')
# if len(logs) == 0:
# sl = cls(
# card=observed_card,
# state=observed_card.state,
# entered=now()
# )
# else:
# sl = logs[0]
#
# sl.service_class = observed_card.service_class.get('name')
# sl.save()
#
# @property
# def duration(self):
# if self._duration is not None:
# return self._duration
#
# if self.exited is not None:
# exited = self.exited
# else:
# exited = now()
# delta = exited - self.entered
# return delta_in_hours(delta)
which might include code, classes, or functions. Output only the next line. | print "Usage: {{state}} {{months}} {{exit|enter}} {{raw data}}" |
Given snippet: <|code_start|> team2 = self.teams[1]
for team in (team1, team2):
for i in xrange(0, 1):
c = self.make_card(
backlog_date=backlog_date,
team=team,
state=self.states.backlog,
)
c.save()
c = self.make_card(
backlog_date=backlog_date,
start_date=start_date,
team=team,
state=self.states.start,
)
c.save()
c = self.make_card(
backlog_date=backlog_date,
start_date=start_date,
done_date=done_date,
team=team,
state=self.states.done,
)
c.save()
c = self.make_card(
backlog_date=backlog_date,
start_date=start_date,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from kardboard.tests.core import KardboardTestCase
from kardboard.models import States
from kardboard.models import FlowReport
and context:
# Path: kardboard/tests/core.py
# class KardboardTestCase(unittest2.TestCase):
# def setUp(self):
# if os.environ.get('KARDBOARD_SETTINGS'):
# os.environ['KARDBOARD_SETTINGS'] = ''
#
# from kardboard import default_settings
# default_settings.TEMPLATE_DEBUG = True
# from kardboard.views import app
# from flask.ext.mongoengine import MongoEngine
# from kardboard.util import now
#
# delattr(app, 'db')
# from mongoengine.connection import connect, disconnect
# disconnect()
#
# app.config.from_object('kardboard.default_settings')
# app.config['MONGODB_DB'] = 'kardboard_unittest'
# app.config['TESTING'] = True
# app.config['CELERY_ALWAYS_EAGER'] = True
# connect(app.config['MONGODB_DB'])
# app.db = MongoEngine(app)
#
# self.config = app.config
# self.app = app.test_client()
# self.flask_app = app
#
# self.used_keys = []
# self._setup_logging()
# self.now = now
#
# super(KardboardTestCase, self).setUp()
#
# def tearDown(self):
# if hasattr(self.config, 'TICKET_HELPER'):
# del self.config['TICKET_HELPER']
# self._flush_db()
# self.flask_app.logger.handlers = self._old_logging_handlers
#
# def _setup_logging(self):
# self._old_logging_handlers = self.flask_app.logger.handlers
# del self.flask_app.logger.handlers[:]
# new_handler = logging.StreamHandler()
# new_handler.setLevel(logging.CRITICAL)
# new_handler.setFormatter(logging.Formatter(self.flask_app.debug_log_format))
# self.flask_app.logger.addHandler(new_handler)
#
# def _flush_db(self):
# from mongoengine.connection import _get_db
# db = _get_db()
# #Truncate/wipe the test database
# names = [name for name in db.collection_names()
# if 'system.' not in name]
# [db.drop_collection(name) for name in names]
#
# def _get_target_url(self):
# raise NotImplementedError
#
# def _get_target_class(self):
# raise NotImplementedError
#
# def _make_one(self, *args, **kwargs):
# return self._get_target_class()(*args, **kwargs)
#
# def _get_card_class(self):
# from kardboard.models import Kard
# return Kard
#
# def _get_record_class(self):
# from kardboard.models import DailyRecord
# return DailyRecord
#
# def _get_person_class(self):
# from kardboard.models import Person
# return Person
#
# def _make_unique_key(self):
# key = random.randint(1, 10000)
# if key not in self.used_keys:
# self.used_keys.append(key)
# return key
# return self._make_unique_key()
#
# def _date(self, dtype, date=None, days=0):
# from kardboard.util import make_end_date, make_start_date
# from kardboard.util import now
#
# if not date:
# date = now()
#
# if dtype == 'start':
# date = make_start_date(date=date)
# elif dtype == 'end':
# date = make_end_date(date=date)
#
# date = date + relativedelta(days=days)
# return date
#
# def make_card(self, **kwargs):
# from kardboard.util import now
# key = self._make_unique_key()
# fields = {
# 'key': "CMSAD-%s" % key,
# 'title': "Theres always money in the banana stand",
# 'backlog_date': now()
# }
# fields.update(**kwargs)
# k = self._get_card_class()(**fields)
# return k
#
# def delete_all_cards(self):
# self._get_card_class().objects.all().delete()
#
# def make_record(self, date, **kwargs):
# fields = {
# 'date': date,
# 'backlog': 3,
# 'in_progress': 8,
# 'done': 10,
# 'completed': 1,
# 'moving_cycle_time': 12,
# 'moving_lead_time': 16,
# 'moving_std_dev': 69,
# 'moving_median_abs_dev': 30,
# }
# fields.update(**kwargs)
# r = self._get_record_class()(**fields)
# return r
#
# def make_person(self, **kwargs):
# key = self._make_unique_key()
# fields = {
# 'name': 'cheisel-%s' % key,
# }
# fields.update(**kwargs)
# p = self._get_person_class()(**fields)
# return p
#
# def assertEqualDateTimes(self, expected, actual):
# expected = (expected.year, expected.month, expected.day, expected.hour, expected.minute)
# actual = (actual.year, actual.month, actual.day, actual.hour, actual.minute)
# self.assertEqual(expected, actual)
which might include code, classes, or functions. Output only the next line. | done_date=done_date, |
Given the code snippet: <|code_start|>
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
<|code_end|>
, generate the next line using the imports in this file:
from kardboard.version import __version__, VERSION
and context (functions, classes, or occasionally code) from other files:
# Path: kardboard/version.py
# VERSION = version
. Output only the next line. | ('index', 'kardboard', u'kardboard Documentation', |
Continue the code snippet: <|code_start|>#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'kardboard'
copyright = u'2011, Chris Heisel'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = VERSION
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
<|code_end|>
. Use current file imports:
from kardboard.version import __version__, VERSION
and context (classes, functions, or code) from other files:
# Path: kardboard/version.py
# VERSION = version
. Output only the next line. | exclude_patterns = [] |
Using the snippet: <|code_start|>
def _get_target_class(self):
return Kard
def test_worked_on_returns_assingee_if_present(self):
k = self._get_target_class()()
k._assignee = "cheisel"
expected = ['cheisel', ]
assert k.worked_on == expected
def test_worked_on_returns_developers_present(self):
k = self._get_target_class()()
k._assignee = "cheisel"
k._ticket_system_data = {
'developers': [
'starbuck',
'apollo',
]
}
expected = ['cheisel', 'starbuck', 'apollo']
assert k.worked_on == expected
def test_worked_on_returns_testers_present(self):
k = self._get_target_class()()
k._assignee = "cheisel"
k._ticket_system_data = {
'qaers': [
'chief',
<|code_end|>
, determine the next line of code. You have imports:
from kardboard.tests.core import KardboardTestCase
from kardboard.models.kard import Kard
and context (class names, function names, or code) available:
# Path: kardboard/tests/core.py
# class KardboardTestCase(unittest2.TestCase):
# def setUp(self):
# if os.environ.get('KARDBOARD_SETTINGS'):
# os.environ['KARDBOARD_SETTINGS'] = ''
#
# from kardboard import default_settings
# default_settings.TEMPLATE_DEBUG = True
# from kardboard.views import app
# from flask.ext.mongoengine import MongoEngine
# from kardboard.util import now
#
# delattr(app, 'db')
# from mongoengine.connection import connect, disconnect
# disconnect()
#
# app.config.from_object('kardboard.default_settings')
# app.config['MONGODB_DB'] = 'kardboard_unittest'
# app.config['TESTING'] = True
# app.config['CELERY_ALWAYS_EAGER'] = True
# connect(app.config['MONGODB_DB'])
# app.db = MongoEngine(app)
#
# self.config = app.config
# self.app = app.test_client()
# self.flask_app = app
#
# self.used_keys = []
# self._setup_logging()
# self.now = now
#
# super(KardboardTestCase, self).setUp()
#
# def tearDown(self):
# if hasattr(self.config, 'TICKET_HELPER'):
# del self.config['TICKET_HELPER']
# self._flush_db()
# self.flask_app.logger.handlers = self._old_logging_handlers
#
# def _setup_logging(self):
# self._old_logging_handlers = self.flask_app.logger.handlers
# del self.flask_app.logger.handlers[:]
# new_handler = logging.StreamHandler()
# new_handler.setLevel(logging.CRITICAL)
# new_handler.setFormatter(logging.Formatter(self.flask_app.debug_log_format))
# self.flask_app.logger.addHandler(new_handler)
#
# def _flush_db(self):
# from mongoengine.connection import _get_db
# db = _get_db()
# #Truncate/wipe the test database
# names = [name for name in db.collection_names()
# if 'system.' not in name]
# [db.drop_collection(name) for name in names]
#
# def _get_target_url(self):
# raise NotImplementedError
#
# def _get_target_class(self):
# raise NotImplementedError
#
# def _make_one(self, *args, **kwargs):
# return self._get_target_class()(*args, **kwargs)
#
# def _get_card_class(self):
# from kardboard.models import Kard
# return Kard
#
# def _get_record_class(self):
# from kardboard.models import DailyRecord
# return DailyRecord
#
# def _get_person_class(self):
# from kardboard.models import Person
# return Person
#
# def _make_unique_key(self):
# key = random.randint(1, 10000)
# if key not in self.used_keys:
# self.used_keys.append(key)
# return key
# return self._make_unique_key()
#
# def _date(self, dtype, date=None, days=0):
# from kardboard.util import make_end_date, make_start_date
# from kardboard.util import now
#
# if not date:
# date = now()
#
# if dtype == 'start':
# date = make_start_date(date=date)
# elif dtype == 'end':
# date = make_end_date(date=date)
#
# date = date + relativedelta(days=days)
# return date
#
# def make_card(self, **kwargs):
# from kardboard.util import now
# key = self._make_unique_key()
# fields = {
# 'key': "CMSAD-%s" % key,
# 'title': "Theres always money in the banana stand",
# 'backlog_date': now()
# }
# fields.update(**kwargs)
# k = self._get_card_class()(**fields)
# return k
#
# def delete_all_cards(self):
# self._get_card_class().objects.all().delete()
#
# def make_record(self, date, **kwargs):
# fields = {
# 'date': date,
# 'backlog': 3,
# 'in_progress': 8,
# 'done': 10,
# 'completed': 1,
# 'moving_cycle_time': 12,
# 'moving_lead_time': 16,
# 'moving_std_dev': 69,
# 'moving_median_abs_dev': 30,
# }
# fields.update(**kwargs)
# r = self._get_record_class()(**fields)
# return r
#
# def make_person(self, **kwargs):
# key = self._make_unique_key()
# fields = {
# 'name': 'cheisel-%s' % key,
# }
# fields.update(**kwargs)
# p = self._get_person_class()(**fields)
# return p
#
# def assertEqualDateTimes(self, expected, actual):
# expected = (expected.year, expected.month, expected.day, expected.hour, expected.minute)
# actual = (actual.year, actual.month, actual.day, actual.hour, actual.minute)
# self.assertEqual(expected, actual)
. Output only the next line. | 'gaeda', |
Next line prediction: <|code_start|>
class TicketDataSyncTests(unittest2.TestCase):
def setUp(self):
super(TicketDataSyncTests, self).setUp()
self.service = ticketdatasync
def test_due_date_changes_from_some_to_none(self):
kard = Mock()
<|code_end|>
. Use current file imports:
(from datetime import datetime
from kardboard.tests.mocks import Mock
from kardboard.services import ticketdatasync
import unittest2)
and context including class names, function names, or small code snippets from other files:
# Path: kardboard/tests/mocks.py
# class MockRemoteCustomFieldValue(object):
# class MockFixVersion(object):
# class MockJIRAIssue(Mock):
# class MockJIRAIssueWithOnlyUIDevs(MockJIRAIssue):
# class MockJIRAObject(object):
# class MockJIRAService(Mock):
# class MockJIRAClient(Mock):
# def __init__(self, customfieldId, key, values):
# def __init__(self, **kwargs):
# def __init__(self, dic):
# def getIssue(self, auth, key):
# def login(self, user, password):
# def getIssueTypes(self):
# def getSubTaskIssueTypes(self):
# def getStatuses(self):
# def getResolutions(self):
. Output only the next line. | kard.due_date = datetime.now() |
Here is a snippet: <|code_start|>
class TicketHelper(object):
def __init__(self, config, kard):
self.app_config = config
<|code_end|>
. Write the next line using the current file imports:
import urlparse
import datetime
import cPickle as pickle
import statsd
import dateutil
from kardboard.app import cache
from kardboard.app import app
from kardboard.util import ImproperlyConfigured, log_exception
from kardboard.tasks import update_ticket
from suds.client import Client
and context from other files:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# class ImproperlyConfigured(Exception):
# pass
#
# def log_exception(exc, msg=""):
# tb = traceback.format_exc()
# log_msg = [msg, str(exc), tb]
# log_msg = '\n'.join(log_msg)
# app = get_current_app()
# app.logger.critical(log_msg)
#
# Path: kardboard/tasks.py
# @celery.task(name="tasks.update_ticket", ignore_result=True)
# def update_ticket(card_id):
# from kardboard.app import app
#
# statsd_conn = app.statsd.get_client('tasks.update_ticket')
# consider_counter = statsd_conn.get_client('consider', class_=statsd.Counter)
# update_counter = statsd_conn.get_client('update', class_=statsd.Counter)
# error_counter = statsd_conn.get_client('error', class_=statsd.Counter)
#
# timer = statsd_conn.get_client(class_=statsd.Timer)
# timer.start()
#
# consider_counter += 1
#
# logger = update_ticket.get_logger()
# try:
# # We want to update cards if their local update time
# # is less than their origin update time
# k = Kard.objects.with_id(card_id)
# i = k.ticket_system.get_issue(k.key)
# origin_updated = getattr(i, 'updated')
# local_updated = k.ticket_system_data.get('updated', None)
#
# should_update = False
# if not local_updated:
# # We've never sync'd before, time to do it right now
# should_update = True
# elif origin_updated:
# if local_updated < origin_updated:
# logger.info(
# "%s UPDATED on origin: Local: %s < Origin: %s" % (k.key, local_updated, origin_updated)
# )
# should_update = True
# else:
# k._ticket_system_updated_at = datetime.datetime.now()
# k.save()
# else:
# # Ok well something changed with the ticket system
# # so we need fall back to the have we updated
# # from origin in THRESHOLD seconds, regardless
# # of how long ago the origin was updated
# # less efficient, but it guarantees updates
# threshold = app.config.get('TICKET_UPDATE_THRESHOLD', 60 * 60)
# now = datetime.datetime.now()
# diff = now - local_updated
# if diff.seconds >= threshold:
# should_update = True
# logger.info(
# "%s FORCED UPDATE because no origin update date available")
#
# if should_update:
# logger.info("update_ticket running for %s" % (k.key, ))
# try:
# update_counter += 1
# k.ticket_system.actually_update()
# except AttributeError:
# error_counter += 1
# logger.warning('Updating kard: %s and we got an AttributeError' % k.key)
# raise
#
# except Kard.DoesNotExist:
# error_counter += 1
# logger.error(
# "update_ticket: Kard with id %s does not exist" % (card_id, ))
# except Exception, e:
# error_counter += 1
# message = "update_ticket: Couldn't update ticket %s from ticket system" % (card_id, )
# log_exception(e, message)
#
# timer.stop()
, which may include functions, classes, or code. Output only the next line. | self.card = kard |
Based on the snippet: <|code_start|>
class TicketHelper(object):
def __init__(self, config, kard):
self.app_config = config
<|code_end|>
, predict the immediate next line with the help of imports:
import urlparse
import datetime
import cPickle as pickle
import statsd
import dateutil
from kardboard.app import cache
from kardboard.app import app
from kardboard.util import ImproperlyConfigured, log_exception
from kardboard.tasks import update_ticket
from suds.client import Client
and context (classes, functions, sometimes code) from other files:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# class ImproperlyConfigured(Exception):
# pass
#
# def log_exception(exc, msg=""):
# tb = traceback.format_exc()
# log_msg = [msg, str(exc), tb]
# log_msg = '\n'.join(log_msg)
# app = get_current_app()
# app.logger.critical(log_msg)
#
# Path: kardboard/tasks.py
# @celery.task(name="tasks.update_ticket", ignore_result=True)
# def update_ticket(card_id):
# from kardboard.app import app
#
# statsd_conn = app.statsd.get_client('tasks.update_ticket')
# consider_counter = statsd_conn.get_client('consider', class_=statsd.Counter)
# update_counter = statsd_conn.get_client('update', class_=statsd.Counter)
# error_counter = statsd_conn.get_client('error', class_=statsd.Counter)
#
# timer = statsd_conn.get_client(class_=statsd.Timer)
# timer.start()
#
# consider_counter += 1
#
# logger = update_ticket.get_logger()
# try:
# # We want to update cards if their local update time
# # is less than their origin update time
# k = Kard.objects.with_id(card_id)
# i = k.ticket_system.get_issue(k.key)
# origin_updated = getattr(i, 'updated')
# local_updated = k.ticket_system_data.get('updated', None)
#
# should_update = False
# if not local_updated:
# # We've never sync'd before, time to do it right now
# should_update = True
# elif origin_updated:
# if local_updated < origin_updated:
# logger.info(
# "%s UPDATED on origin: Local: %s < Origin: %s" % (k.key, local_updated, origin_updated)
# )
# should_update = True
# else:
# k._ticket_system_updated_at = datetime.datetime.now()
# k.save()
# else:
# # Ok well something changed with the ticket system
# # so we need fall back to the have we updated
# # from origin in THRESHOLD seconds, regardless
# # of how long ago the origin was updated
# # less efficient, but it guarantees updates
# threshold = app.config.get('TICKET_UPDATE_THRESHOLD', 60 * 60)
# now = datetime.datetime.now()
# diff = now - local_updated
# if diff.seconds >= threshold:
# should_update = True
# logger.info(
# "%s FORCED UPDATE because no origin update date available")
#
# if should_update:
# logger.info("update_ticket running for %s" % (k.key, ))
# try:
# update_counter += 1
# k.ticket_system.actually_update()
# except AttributeError:
# error_counter += 1
# logger.warning('Updating kard: %s and we got an AttributeError' % k.key)
# raise
#
# except Kard.DoesNotExist:
# error_counter += 1
# logger.error(
# "update_ticket: Kard with id %s does not exist" % (card_id, ))
# except Exception, e:
# error_counter += 1
# message = "update_ticket: Couldn't update ticket %s from ticket system" % (card_id, )
# log_exception(e, message)
#
# timer.stop()
. Output only the next line. | self.card = kard |
Using the snippet: <|code_start|>
class TicketHelper(object):
def __init__(self, config, kard):
self.app_config = config
<|code_end|>
, determine the next line of code. You have imports:
import urlparse
import datetime
import cPickle as pickle
import statsd
import dateutil
from kardboard.app import cache
from kardboard.app import app
from kardboard.util import ImproperlyConfigured, log_exception
from kardboard.tasks import update_ticket
from suds.client import Client
and context (class names, function names, or code) available:
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/app.py
# DEBUG_TOOLBAR = True
# DEBUG_TOOLBAR = False
# SENTRY_SUPPORT = True
# SENTRY_SUPPORT = False
# def get_app():
#
# Path: kardboard/util.py
# class ImproperlyConfigured(Exception):
# pass
#
# def log_exception(exc, msg=""):
# tb = traceback.format_exc()
# log_msg = [msg, str(exc), tb]
# log_msg = '\n'.join(log_msg)
# app = get_current_app()
# app.logger.critical(log_msg)
#
# Path: kardboard/tasks.py
# @celery.task(name="tasks.update_ticket", ignore_result=True)
# def update_ticket(card_id):
# from kardboard.app import app
#
# statsd_conn = app.statsd.get_client('tasks.update_ticket')
# consider_counter = statsd_conn.get_client('consider', class_=statsd.Counter)
# update_counter = statsd_conn.get_client('update', class_=statsd.Counter)
# error_counter = statsd_conn.get_client('error', class_=statsd.Counter)
#
# timer = statsd_conn.get_client(class_=statsd.Timer)
# timer.start()
#
# consider_counter += 1
#
# logger = update_ticket.get_logger()
# try:
# # We want to update cards if their local update time
# # is less than their origin update time
# k = Kard.objects.with_id(card_id)
# i = k.ticket_system.get_issue(k.key)
# origin_updated = getattr(i, 'updated')
# local_updated = k.ticket_system_data.get('updated', None)
#
# should_update = False
# if not local_updated:
# # We've never sync'd before, time to do it right now
# should_update = True
# elif origin_updated:
# if local_updated < origin_updated:
# logger.info(
# "%s UPDATED on origin: Local: %s < Origin: %s" % (k.key, local_updated, origin_updated)
# )
# should_update = True
# else:
# k._ticket_system_updated_at = datetime.datetime.now()
# k.save()
# else:
# # Ok well something changed with the ticket system
# # so we need fall back to the have we updated
# # from origin in THRESHOLD seconds, regardless
# # of how long ago the origin was updated
# # less efficient, but it guarantees updates
# threshold = app.config.get('TICKET_UPDATE_THRESHOLD', 60 * 60)
# now = datetime.datetime.now()
# diff = now - local_updated
# if diff.seconds >= threshold:
# should_update = True
# logger.info(
# "%s FORCED UPDATE because no origin update date available")
#
# if should_update:
# logger.info("update_ticket running for %s" % (k.key, ))
# try:
# update_counter += 1
# k.ticket_system.actually_update()
# except AttributeError:
# error_counter += 1
# logger.warning('Updating kard: %s and we got an AttributeError' % k.key)
# raise
#
# except Kard.DoesNotExist:
# error_counter += 1
# logger.error(
# "update_ticket: Kard with id %s does not exist" % (card_id, ))
# except Exception, e:
# error_counter += 1
# message = "update_ticket: Couldn't update ticket %s from ticket system" % (card_id, )
# log_exception(e, message)
#
# timer.stop()
. Output only the next line. | self.card = kard |
Using the snippet: <|code_start|>
def test_webhook_sample():
url = 'http://localhost:0'
notify = WebHookNotify(value=url)
with mock.patch.object(notify.session, 'post') as fake_post:
notify('report')
<|code_end|>
, determine the next line of code. You have imports:
from kibitzr.notifier.webhook import WebHookNotify
from ...compat import mock
and context (class names, function names, or code) available:
# Path: kibitzr/notifier/webhook.py
# class WebHookNotify(object):
#
# CREDS_KEY = 'webhook'
# POST_KEY = 'message'
#
# def __init__(self, creds_key=None, conf=None, value=None, post_key=None):
# import requests
# self.session = requests.Session()
# self.url = self.load_url(creds_key or self.CREDS_KEY, value)
# self.post_key = post_key or self.POST_KEY
# self.configure_session()
#
# def load_url(self, creds_key, value):
# if value:
# return value
# else:
# webhook_creds = settings().creds[creds_key]
# return webhook_creds['url']
#
# def post(self, report):
# response = self.session.post(
# self.url,
# data=self.payload(report),
# )
# logger.debug(response.text)
# response.raise_for_status()
# return response
# __call__ = post
#
# def configure_session(self):
# pass
#
# def payload(self, report):
# return {self.post_key: report}
#
# Path: tests/compat.py
. Output only the next line. | fake_post.assert_called_once_with( |
Given the following code snippet before the placeholder: <|code_start|>
def test_bash_unicode_is_handled():
content = u"\U0001F4A9"
with tempfile.NamedTemporaryFile() as outfile:
bash_notify = bash_factory({}, 'tee %s' % outfile.name)
<|code_end|>
, predict the next line using imports from the current file:
import tempfile
from kibitzr.notifier.bash import notify_factory as bash_factory
and context including class names, function names, and sometimes code from other files:
# Path: kibitzr/notifier/bash.py
# def notify_factory(conf, value):
# return BashNotify(value)
. Output only the next line. | bash_notify(content) |
Using the snippet: <|code_start|>
def test_bash_transform_sample():
ok, content = bash_transform(
code="sed 's/A/B/g'",
content="ACTGA",
)
assert ok is True
assert content.strip() == "BCTGB"
def test_python_transform_sample():
ok, content = python_transform(
code="content = content.replace('A', 'B')",
content="ACTGA",
conf=None,
)
assert ok is True
assert content.strip() == "BCTGB"
<|code_end|>
, determine the next line of code. You have imports:
from kibitzr.transformer.plain_text import (
python_transform,
bash_transform,
)
and context (class names, function names, or code) available:
# Path: kibitzr/transformer/plain_text.py
# def python_transform(code, content, conf):
# logger.info("Python transform")
# logger.debug(code)
# assert 'content' in code, PYTHON_ERROR
# try:
# namespace = {'ok': True, 'content': content}
# context = {
# 'conf': conf,
# 'stash': LazyStash(),
# 'creds': settings().creds,
# }
# exec(code, context, namespace)
# return namespace['ok'], six.text_type(namespace['content'])
# except:
# logger.exception("Python transform raised an Exception")
# return False, traceback.format_exc()
#
# def bash_transform(code, content):
# return execute_bash(code, content)
. Output only the next line. | def test_bash_transform_error_is_captured(): |
Predict the next line after this snippet: <|code_start|> assert content.strip() == "BCTGB"
def test_python_transform_sample():
ok, content = python_transform(
code="content = content.replace('A', 'B')",
content="ACTGA",
conf=None,
)
assert ok is True
assert content.strip() == "BCTGB"
def test_bash_transform_error_is_captured():
ok, content = bash_transform(
code="ls /NO-SUCH-DIR",
content="?",
)
assert ok is False
assert "ls" in content
assert "/NO-SUCH-DIR" in content
assert "No such file or directory" in content
def test_python_exception_is_captured():
ok, content = python_transform(
code="content = 1 / 0",
content="?",
conf=None,
)
<|code_end|>
using the current file's imports:
from kibitzr.transformer.plain_text import (
python_transform,
bash_transform,
)
and any relevant context from other files:
# Path: kibitzr/transformer/plain_text.py
# def python_transform(code, content, conf):
# logger.info("Python transform")
# logger.debug(code)
# assert 'content' in code, PYTHON_ERROR
# try:
# namespace = {'ok': True, 'content': content}
# context = {
# 'conf': conf,
# 'stash': LazyStash(),
# 'creds': settings().creds,
# }
# exec(code, context, namespace)
# return namespace['ok'], six.text_type(namespace['content'])
# except:
# logger.exception("Python transform raised an Exception")
# return False, traceback.format_exc()
#
# def bash_transform(code, content):
# return execute_bash(code, content)
. Output only the next line. | assert ok is False |
Given snippet: <|code_start|> self.post_key = post_key or self.POST_KEY
self.configure_session()
def load_url(self, creds_key, value):
if value:
return value
else:
webhook_creds = settings().creds[creds_key]
return webhook_creds['url']
def post(self, report):
response = self.session.post(
self.url,
data=self.payload(report),
)
logger.debug(response.text)
response.raise_for_status()
return response
__call__ = post
def configure_session(self):
pass
def payload(self, report):
return {self.post_key: report}
def webhook_factory(klass):
def notify_factory(conf, value):
return klass(conf=conf, value=value)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import requests
from ..conf import settings
and context:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
which might include code, classes, or functions. Output only the next line. | return notify_factory |
Given the following code snippet before the placeholder: <|code_start|>
@contextlib.contextmanager
def patch_creds(data):
with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
yield fake_method
@contextlib.contextmanager
def patch_conf(data):
with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
yield fake_method
@contextlib.contextmanager
def patch_source(klass, method, data):
fake_file = mock.mock_open(read_data=data)
with mock.patch.object(klass,
method,
<|code_end|>
, predict the next line using imports from the current file:
import contextlib
from kibitzr.conf import (
ReloadableSettings,
PlainYamlCreds,
)
from ..compat import mock
and context including class names, function names, and sometimes code from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# _instance = None
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
#
# def __init__(self, config_dir):
# self.filename = os.path.join(config_dir, self.CONFIG_FILENAME)
# self.checks = None
# self.creds = CompositeCreds(config_dir)
# self.parser = SettingsParser()
# self.reread()
#
# @classmethod
# def detect_config_dir(cls):
# candidates = [
# (directory, os.path.join(directory, cls.CONFIG_FILENAME))
# for directory in map(os.path.expanduser, cls.CONFIG_DIRS)
# ]
# for directory, file_path in candidates:
# if os.path.exists(file_path):
# return directory
# raise ConfigurationError(
# "kibitzr.yml not found in following locations: %s"
# % ", ".join([x[1] for x in candidates])
# )
#
# @classmethod
# def instance(cls):
# if cls._instance is None:
# config_dir = cls.detect_config_dir()
# cls._instance = cls(config_dir)
# return cls._instance
#
# def reread(self):
# """
# Read configuration file and substitute references into checks conf
# """
# logger.debug("Loading settings from %s",
# os.path.abspath(self.filename))
# conf = self.read_conf()
# changed = self.creds.reread()
# checks = self.parser.parse_checks(conf)
# if self.checks != checks:
# self.checks = checks
# return True
# else:
# return changed
#
# def read_conf(self):
# """
# Read and parse configuration file
# """
# with self.open_conf() as fp:
# return yaml.safe_load(fp)
#
# @contextlib.contextmanager
# def open_conf(self):
# with open(self.filename) as fp:
# yield fp
#
# class PlainYamlCreds(object):
#
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
#
# def __init__(self, config_dir):
# super(PlainYamlCreds, self).__init__()
# self.creds = {}
# self.creds_filename = os.path.join(config_dir,
# self.CREDENTIALS_FILENAME)
# self.reread()
#
# def __contains__(self, key):
# return key in self.creds
#
# def __getitem__(self, key):
# return self.creds[key]
#
# def reread(self):
# """
# Read and parse credentials file.
# If something goes wrong, log exception and continue.
# """
# logger.debug("Loading credentials from %s",
# os.path.abspath(self.creds_filename))
# creds = {}
# try:
# with self.open_creds() as fp:
# creds = yaml.safe_load(fp)
# except IOError:
# logger.info("No credentials file found at %s",
# os.path.abspath(self.creds_filename))
# except:
# logger.exception("Error loading credentials file")
# if creds != self.creds:
# self.creds = creds
# return True
# return False
#
# @contextlib.contextmanager
# def open_creds(self):
# with open(self.creds_filename) as fp:
# yield fp
#
# Path: tests/compat.py
. Output only the next line. | fake_file, |
Next line prediction: <|code_start|>
@contextlib.contextmanager
def patch_creds(data):
with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
yield fake_method
@contextlib.contextmanager
def patch_conf(data):
with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
yield fake_method
@contextlib.contextmanager
def patch_source(klass, method, data):
fake_file = mock.mock_open(read_data=data)
with mock.patch.object(klass,
method,
fake_file,
create=True) as fake_method:
<|code_end|>
. Use current file imports:
(import contextlib
from kibitzr.conf import (
ReloadableSettings,
PlainYamlCreds,
)
from ..compat import mock)
and context including class names, function names, or small code snippets from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# _instance = None
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
#
# def __init__(self, config_dir):
# self.filename = os.path.join(config_dir, self.CONFIG_FILENAME)
# self.checks = None
# self.creds = CompositeCreds(config_dir)
# self.parser = SettingsParser()
# self.reread()
#
# @classmethod
# def detect_config_dir(cls):
# candidates = [
# (directory, os.path.join(directory, cls.CONFIG_FILENAME))
# for directory in map(os.path.expanduser, cls.CONFIG_DIRS)
# ]
# for directory, file_path in candidates:
# if os.path.exists(file_path):
# return directory
# raise ConfigurationError(
# "kibitzr.yml not found in following locations: %s"
# % ", ".join([x[1] for x in candidates])
# )
#
# @classmethod
# def instance(cls):
# if cls._instance is None:
# config_dir = cls.detect_config_dir()
# cls._instance = cls(config_dir)
# return cls._instance
#
# def reread(self):
# """
# Read configuration file and substitute references into checks conf
# """
# logger.debug("Loading settings from %s",
# os.path.abspath(self.filename))
# conf = self.read_conf()
# changed = self.creds.reread()
# checks = self.parser.parse_checks(conf)
# if self.checks != checks:
# self.checks = checks
# return True
# else:
# return changed
#
# def read_conf(self):
# """
# Read and parse configuration file
# """
# with self.open_conf() as fp:
# return yaml.safe_load(fp)
#
# @contextlib.contextmanager
# def open_conf(self):
# with open(self.filename) as fp:
# yield fp
#
# class PlainYamlCreds(object):
#
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
#
# def __init__(self, config_dir):
# super(PlainYamlCreds, self).__init__()
# self.creds = {}
# self.creds_filename = os.path.join(config_dir,
# self.CREDENTIALS_FILENAME)
# self.reread()
#
# def __contains__(self, key):
# return key in self.creds
#
# def __getitem__(self, key):
# return self.creds[key]
#
# def reread(self):
# """
# Read and parse credentials file.
# If something goes wrong, log exception and continue.
# """
# logger.debug("Loading credentials from %s",
# os.path.abspath(self.creds_filename))
# creds = {}
# try:
# with self.open_creds() as fp:
# creds = yaml.safe_load(fp)
# except IOError:
# logger.info("No credentials file found at %s",
# os.path.abspath(self.creds_filename))
# except:
# logger.exception("Error loading credentials file")
# if creds != self.creds:
# self.creds = creds
# return True
# return False
#
# @contextlib.contextmanager
# def open_creds(self):
# with open(self.creds_filename) as fp:
# yield fp
#
# Path: tests/compat.py
. Output only the next line. | yield fake_method |
Here is a snippet: <|code_start|>
def test_invalid_unit():
with pytest.raises(ConfigurationError):
Timeline.parse_check({
'name': 'x',
'schedule': {
'every': 2,
'unit': 'olympics'
},
})
def test_invalid_every():
with pytest.raises(ConfigurationError):
print(Timeline.parse_check({
'name': 'x',
'schedule': {
'every': 'single', # every must be integer
'unit': 'minute',
},
}))
def test_invalid_time():
with pytest.raises(ConfigurationError):
print(Timeline.parse_check({
'name': 'x',
'schedule': {
'every': 'day',
<|code_end|>
. Write the next line using the current file imports:
import pytest
from freezegun import freeze_time
from kibitzr.timeline import Timeline, TimelineRule
from kibitzr.exceptions import ConfigurationError
and context from other files:
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
, which may include functions, classes, or code. Output only the next line. | 'at': 'noon', |
Given the code snippet: <|code_start|>
def test_dummy_schedule(app, settings, check_noop):
check_noop.side_effect = interrupt_on_nth_call(app, 2)
settings.checks.append({
'name': 'A',
'script': {'python': 'ok, content = True, "ok"'},
'schedule': [TimelineRule(interval=0, unit='seconds', at=None)],
})
assert app.run() == 1
assert check_noop.call_count == 2
def interrupt_on_nth_call(app, n):
def interrupter():
if interrupter.n > 1:
interrupter.n -= 1
else:
app.on_interrupt()
return None
interrupter.n = n
return interrupter
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from freezegun import freeze_time
from kibitzr.timeline import Timeline, TimelineRule
from kibitzr.exceptions import ConfigurationError
and context (functions, classes, or occasionally code) from other files:
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
. Output only the next line. | def test_period_parse(): |
Continue the code snippet: <|code_start|> gotify_creds = settings().creds['gotify']
self.url = gotify_creds['url'].rstrip('/') + '/message'
self.token = gotify_creds['token']
self.verify = gotify_creds.get('verify', True)
if not self.verify:
# Since certificate validation was disabled, do not show the warning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
if value is None:
value = {}
self.title = value.get('title', 'kibitzr')
self.priority = value.get('priority', 4)
def post(self, report):
logger.info("Executing Gotify notifier")
response = self.session.post(
url=self.url,
json=self.json(report),
params=self.params(),
verify=self.verify
)
logger.debug(response.text)
response.raise_for_status()
return response
__call__ = post
def params(self):
return {
'token': self.token
}
<|code_end|>
. Use current file imports:
import logging
import urllib3
import requests
from ..conf import settings
and context (classes, functions, or code) from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
. Output only the next line. | def json(self, report): |
Given snippet: <|code_start|>from __future__ import absolute_import
logger = logging.getLogger(__name__)
class TelegramBot(object):
def __init__(self, chat_id=None, split_on=None):
telegram_creds = settings().creds['telegram']
token = telegram_creds['token']
if chat_id is not None:
self._chat_id = chat_id
else:
self._chat_id = telegram_creds.get('chat')
self.split_on = split_on
self.bot = Bot(token=token)
@property
def chat_id(self):
if self._chat_id is None:
chat = self.bot.getUpdates(limit=1)[0].message.chat
logger.debug("Imprinted chat id %d of type %s",
chat.id, chat.type)
self._chat_id = chat.id
return self._chat_id
def post(self, report, **kwargs):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from ..conf import settings
from telegram.bot import Bot
and context:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
which might include code, classes, or functions. Output only the next line. | if self.split_on: |
Continue the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
def pretty_json(text):
json_dump = json.dumps(
json.loads(text),
indent=2,
sort_keys=True,
ensure_ascii=False,
# encoding='utf-8',
)
return True, u'\n'.join([
<|code_end|>
. Use current file imports:
import json
import logging
from .utils import wrap_dummy, bake_parametrized
from kibitzr.compat import sh
and context (classes, functions, or code) from other files:
# Path: kibitzr/transformer/utils.py
# def wrap_dummy(transform_func):
# def transform_factory(value, conf):
# return transform_func
# return transform_factory
#
# def bake_parametrized(transform_func, pass_conf=False, **kwargs):
# def transform_factory(value, conf):
# if pass_conf:
# return functools.partial(
# transform_func,
# value,
# conf=conf,
# **kwargs
# )
# else:
# return functools.partial(
# transform_func,
# value,
# **kwargs
# )
# return transform_factory
. Output only the next line. | line.rstrip() |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
def pretty_json(text):
json_dump = json.dumps(
json.loads(text),
<|code_end|>
. Use current file imports:
(import json
import logging
from .utils import wrap_dummy, bake_parametrized
from kibitzr.compat import sh)
and context including class names, function names, or small code snippets from other files:
# Path: kibitzr/transformer/utils.py
# def wrap_dummy(transform_func):
# def transform_factory(value, conf):
# return transform_func
# return transform_factory
#
# def bake_parametrized(transform_func, pass_conf=False, **kwargs):
# def transform_factory(value, conf):
# if pass_conf:
# return functools.partial(
# transform_func,
# value,
# conf=conf,
# **kwargs
# )
# else:
# return functools.partial(
# transform_func,
# value,
# **kwargs
# )
# return transform_factory
. Output only the next line. | indent=2, |
Given the following code snippet before the placeholder: <|code_start|>
def test_loop_aborts_without_checks(app, settings):
assert app.run() == 1
def test_main_executes_all_checks_before_loop(app, settings):
with mock.patch.object(app, "check_forever", side_effect=app.on_interrupt) as the_loop:
settings.checks.append({
'name': 'A',
'script': {'python': 'ok, content = True, "ok"'}
})
assert app.run() == 1
assert the_loop.call_count == 1
assert the_loop.call_args[0][0][0].check.call_count == 1
<|code_end|>
, predict the next line using imports from the current file:
from ..compat import mock
and context including class names, function names, and sometimes code from other files:
# Path: tests/compat.py
. Output only the next line. | def test_main_filters_names(app, settings): |
Next line prediction: <|code_start|>
class MailgunNotify(WebHookNotify):
CREDS_KEY = 'mailgun'
def __init__(self, conf, value, **kwargs):
self.mailgun_creds = settings().creds.get('mailgun', {})
self.mailgun_creds.update(value or {})
domain = self.mailgun_creds['domain']
self.context = {
'subject': 'Kibitzr update for ' + conf['name'],
'from': 'Kibitzr <mailgun@{0}>'.format(domain),
<|code_end|>
. Use current file imports:
(from .webhook import WebHookNotify, webhook_factory
from ..conf import settings)
and context including class names, function names, or small code snippets from other files:
# Path: kibitzr/notifier/webhook.py
# class WebHookNotify(object):
#
# CREDS_KEY = 'webhook'
# POST_KEY = 'message'
#
# def __init__(self, creds_key=None, conf=None, value=None, post_key=None):
# import requests
# self.session = requests.Session()
# self.url = self.load_url(creds_key or self.CREDS_KEY, value)
# self.post_key = post_key or self.POST_KEY
# self.configure_session()
#
# def load_url(self, creds_key, value):
# if value:
# return value
# else:
# webhook_creds = settings().creds[creds_key]
# return webhook_creds['url']
#
# def post(self, report):
# response = self.session.post(
# self.url,
# data=self.payload(report),
# )
# logger.debug(response.text)
# response.raise_for_status()
# return response
# __call__ = post
#
# def configure_session(self):
# pass
#
# def payload(self, report):
# return {self.post_key: report}
#
# def webhook_factory(klass):
# def notify_factory(conf, value):
# return klass(conf=conf, value=value)
# return notify_factory
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
. Output only the next line. | 'to': [self.mailgun_creds['to']], |
Next line prediction: <|code_start|>
class MailgunNotify(WebHookNotify):
CREDS_KEY = 'mailgun'
def __init__(self, conf, value, **kwargs):
self.mailgun_creds = settings().creds.get('mailgun', {})
self.mailgun_creds.update(value or {})
domain = self.mailgun_creds['domain']
self.context = {
'subject': 'Kibitzr update for ' + conf['name'],
'from': 'Kibitzr <mailgun@{0}>'.format(domain),
'to': [self.mailgun_creds['to']],
}
super(MailgunNotify, self).__init__(conf=conf, value=value, **kwargs)
<|code_end|>
. Use current file imports:
(from .webhook import WebHookNotify, webhook_factory
from ..conf import settings)
and context including class names, function names, or small code snippets from other files:
# Path: kibitzr/notifier/webhook.py
# class WebHookNotify(object):
#
# CREDS_KEY = 'webhook'
# POST_KEY = 'message'
#
# def __init__(self, creds_key=None, conf=None, value=None, post_key=None):
# import requests
# self.session = requests.Session()
# self.url = self.load_url(creds_key or self.CREDS_KEY, value)
# self.post_key = post_key or self.POST_KEY
# self.configure_session()
#
# def load_url(self, creds_key, value):
# if value:
# return value
# else:
# webhook_creds = settings().creds[creds_key]
# return webhook_creds['url']
#
# def post(self, report):
# response = self.session.post(
# self.url,
# data=self.payload(report),
# )
# logger.debug(response.text)
# response.raise_for_status()
# return response
# __call__ = post
#
# def configure_session(self):
# pass
#
# def payload(self, report):
# return {self.post_key: report}
#
# def webhook_factory(klass):
# def notify_factory(conf, value):
# return klass(conf=conf, value=value)
# return notify_factory
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
. Output only the next line. | def load_url(self, creds_key, value): |
Predict the next line for this snippet: <|code_start|>
class MailgunNotify(WebHookNotify):
CREDS_KEY = 'mailgun'
def __init__(self, conf, value, **kwargs):
self.mailgun_creds = settings().creds.get('mailgun', {})
self.mailgun_creds.update(value or {})
domain = self.mailgun_creds['domain']
self.context = {
'subject': 'Kibitzr update for ' + conf['name'],
'from': 'Kibitzr <mailgun@{0}>'.format(domain),
'to': [self.mailgun_creds['to']],
}
super(MailgunNotify, self).__init__(conf=conf, value=value, **kwargs)
def load_url(self, creds_key, value):
return ('https://api.mailgun.net/v3/{0}/messages'
.format(self.mailgun_creds['domain']))
def configure_session(self):
self.session.auth = ('api', self.mailgun_creds['key'])
def payload(self, report):
return dict(
self.context,
<|code_end|>
with the help of current file imports:
from .webhook import WebHookNotify, webhook_factory
from ..conf import settings
and context from other files:
# Path: kibitzr/notifier/webhook.py
# class WebHookNotify(object):
#
# CREDS_KEY = 'webhook'
# POST_KEY = 'message'
#
# def __init__(self, creds_key=None, conf=None, value=None, post_key=None):
# import requests
# self.session = requests.Session()
# self.url = self.load_url(creds_key or self.CREDS_KEY, value)
# self.post_key = post_key or self.POST_KEY
# self.configure_session()
#
# def load_url(self, creds_key, value):
# if value:
# return value
# else:
# webhook_creds = settings().creds[creds_key]
# return webhook_creds['url']
#
# def post(self, report):
# response = self.session.post(
# self.url,
# data=self.payload(report),
# )
# logger.debug(response.text)
# response.raise_for_status()
# return response
# __call__ = post
#
# def configure_session(self):
# pass
#
# def payload(self, report):
# return {self.post_key: report}
#
# def webhook_factory(klass):
# def notify_factory(conf, value):
# return klass(conf=conf, value=value)
# return notify_factory
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
, which may contain function names, class names, or code. Output only the next line. | text=report, |
Using the snippet: <|code_start|>
PYTHON_ERROR = "transform.python must set global variables ok and content"
logger = logging.getLogger(__name__)
def changes_transform_factory(value, conf):
style = value.lower() if value else None
return PageHistory(conf, style=style).report_changes
def python_transform(code, content, conf):
logger.info("Python transform")
logger.debug(code)
assert 'content' in code, PYTHON_ERROR
try:
namespace = {'ok': True, 'content': content}
context = {
'conf': conf,
'stash': LazyStash(),
'creds': settings().creds,
}
exec(code, context, namespace)
return namespace['ok'], six.text_type(namespace['content'])
except:
logger.exception("Python transform raised an Exception")
<|code_end|>
, determine the next line of code. You have imports:
import logging
import traceback
import six
from kibitzr.stash import LazyStash
from kibitzr.conf import settings
from kibitzr.storage import PageHistory
from kibitzr.bash import execute_bash
from .utils import bake_parametrized
and context (class names, function names, or code) available:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/storage.py
# class PageHistory(object):
# """
# Single file changes history using git
# """
# STORAGE_DIR = "pages"
#
# def __init__(self, conf, storage_dir=None, style=None):
# self.storage_dir = storage_dir or self.STORAGE_DIR
# self.cwd = os.path.join(
# self.storage_dir,
# normalize_filename(conf['name']),
# )
# self.target = os.path.join(self.cwd, "content")
# self.git = sh.Command('git').bake(
# '--no-pager',
# _cwd=self.cwd,
# )
# self.ensure_repo_exists()
# if conf.get('url'):
# self.commit_msg = u"{name} at {url}".format(
# name=conf['name'],
# url=conf.get('url'),
# )
# else:
# self.commit_msg = conf['name']
# self.reporter = ChangesReporter(
# self.git,
# self.commit_msg,
# style,
# )
#
# def report_changes(self, content):
# """
# 1) Write changes in file,
# 2) Commit changes in git
# 3.1) If something changed, return tuple(True, changes)
# 3.2) If nothing changed, return tuple(False, None)
#
# If style is "verbose", return changes in human-friendly format,
# else use unified diff
# """
# self.write(content)
# if self.commit():
# return True, self.reporter.report()
# else:
# return False, None
#
# def write(self, content):
# """Save content on disk"""
# with io.open(self.target, 'w', encoding='utf-8') as fp:
# fp.write(content)
# if not content.endswith(u'\n'):
# fp.write(u'\n')
#
# def commit(self):
# """git commit and return whether there were changes"""
# self.git.add('-A', '.')
# try:
# self.git.commit('-m', self.commit_msg)
# return True
# except sh.ErrorReturnCode_1:
# return False
#
# def ensure_repo_exists(self):
# """Create git repo if one does not exist yet"""
# if not os.path.isdir(self.cwd):
# os.makedirs(self.cwd)
# if not os.path.isdir(os.path.join(self.cwd, ".git")):
# self.git.init()
# self.git.config("user.email", "you@example.com")
# self.git.config("user.name", "Your Name")
#
# @staticmethod
# def clean():
# """Remove storage dir (delete all git repos)"""
# shutil.rmtree(PageHistory.STORAGE_DIR)
#
# Path: kibitzr/bash.py
# def execute_bash(code, stdin=None):
# if os.name == 'nt':
# executor = WindowsExecutor
# else:
# executor = BashExecutor
# return executor(code).execute(stdin)
#
# Path: kibitzr/transformer/utils.py
# def bake_parametrized(transform_func, pass_conf=False, **kwargs):
# def transform_factory(value, conf):
# if pass_conf:
# return functools.partial(
# transform_func,
# value,
# conf=conf,
# **kwargs
# )
# else:
# return functools.partial(
# transform_func,
# value,
# **kwargs
# )
# return transform_factory
. Output only the next line. | return False, traceback.format_exc() |
Predict the next line for this snippet: <|code_start|>
PYTHON_ERROR = "transform.python must set global variables ok and content"
logger = logging.getLogger(__name__)
def changes_transform_factory(value, conf):
<|code_end|>
with the help of current file imports:
import logging
import traceback
import six
from kibitzr.stash import LazyStash
from kibitzr.conf import settings
from kibitzr.storage import PageHistory
from kibitzr.bash import execute_bash
from .utils import bake_parametrized
and context from other files:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/storage.py
# class PageHistory(object):
# """
# Single file changes history using git
# """
# STORAGE_DIR = "pages"
#
# def __init__(self, conf, storage_dir=None, style=None):
# self.storage_dir = storage_dir or self.STORAGE_DIR
# self.cwd = os.path.join(
# self.storage_dir,
# normalize_filename(conf['name']),
# )
# self.target = os.path.join(self.cwd, "content")
# self.git = sh.Command('git').bake(
# '--no-pager',
# _cwd=self.cwd,
# )
# self.ensure_repo_exists()
# if conf.get('url'):
# self.commit_msg = u"{name} at {url}".format(
# name=conf['name'],
# url=conf.get('url'),
# )
# else:
# self.commit_msg = conf['name']
# self.reporter = ChangesReporter(
# self.git,
# self.commit_msg,
# style,
# )
#
# def report_changes(self, content):
# """
# 1) Write changes in file,
# 2) Commit changes in git
# 3.1) If something changed, return tuple(True, changes)
# 3.2) If nothing changed, return tuple(False, None)
#
# If style is "verbose", return changes in human-friendly format,
# else use unified diff
# """
# self.write(content)
# if self.commit():
# return True, self.reporter.report()
# else:
# return False, None
#
# def write(self, content):
# """Save content on disk"""
# with io.open(self.target, 'w', encoding='utf-8') as fp:
# fp.write(content)
# if not content.endswith(u'\n'):
# fp.write(u'\n')
#
# def commit(self):
# """git commit and return whether there were changes"""
# self.git.add('-A', '.')
# try:
# self.git.commit('-m', self.commit_msg)
# return True
# except sh.ErrorReturnCode_1:
# return False
#
# def ensure_repo_exists(self):
# """Create git repo if one does not exist yet"""
# if not os.path.isdir(self.cwd):
# os.makedirs(self.cwd)
# if not os.path.isdir(os.path.join(self.cwd, ".git")):
# self.git.init()
# self.git.config("user.email", "you@example.com")
# self.git.config("user.name", "Your Name")
#
# @staticmethod
# def clean():
# """Remove storage dir (delete all git repos)"""
# shutil.rmtree(PageHistory.STORAGE_DIR)
#
# Path: kibitzr/bash.py
# def execute_bash(code, stdin=None):
# if os.name == 'nt':
# executor = WindowsExecutor
# else:
# executor = BashExecutor
# return executor(code).execute(stdin)
#
# Path: kibitzr/transformer/utils.py
# def bake_parametrized(transform_func, pass_conf=False, **kwargs):
# def transform_factory(value, conf):
# if pass_conf:
# return functools.partial(
# transform_func,
# value,
# conf=conf,
# **kwargs
# )
# else:
# return functools.partial(
# transform_func,
# value,
# **kwargs
# )
# return transform_factory
, which may contain function names, class names, or code. Output only the next line. | style = value.lower() if value else None |
Given the code snippet: <|code_start|>
PYTHON_ERROR = "transform.python must set global variables ok and content"
logger = logging.getLogger(__name__)
def changes_transform_factory(value, conf):
style = value.lower() if value else None
return PageHistory(conf, style=style).report_changes
def python_transform(code, content, conf):
logger.info("Python transform")
logger.debug(code)
assert 'content' in code, PYTHON_ERROR
try:
namespace = {'ok': True, 'content': content}
context = {
'conf': conf,
'stash': LazyStash(),
'creds': settings().creds,
}
exec(code, context, namespace)
return namespace['ok'], six.text_type(namespace['content'])
<|code_end|>
, generate the next line using the imports in this file:
import logging
import traceback
import six
from kibitzr.stash import LazyStash
from kibitzr.conf import settings
from kibitzr.storage import PageHistory
from kibitzr.bash import execute_bash
from .utils import bake_parametrized
and context (functions, classes, or occasionally code) from other files:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/storage.py
# class PageHistory(object):
# """
# Single file changes history using git
# """
# STORAGE_DIR = "pages"
#
# def __init__(self, conf, storage_dir=None, style=None):
# self.storage_dir = storage_dir or self.STORAGE_DIR
# self.cwd = os.path.join(
# self.storage_dir,
# normalize_filename(conf['name']),
# )
# self.target = os.path.join(self.cwd, "content")
# self.git = sh.Command('git').bake(
# '--no-pager',
# _cwd=self.cwd,
# )
# self.ensure_repo_exists()
# if conf.get('url'):
# self.commit_msg = u"{name} at {url}".format(
# name=conf['name'],
# url=conf.get('url'),
# )
# else:
# self.commit_msg = conf['name']
# self.reporter = ChangesReporter(
# self.git,
# self.commit_msg,
# style,
# )
#
# def report_changes(self, content):
# """
# 1) Write changes in file,
# 2) Commit changes in git
# 3.1) If something changed, return tuple(True, changes)
# 3.2) If nothing changed, return tuple(False, None)
#
# If style is "verbose", return changes in human-friendly format,
# else use unified diff
# """
# self.write(content)
# if self.commit():
# return True, self.reporter.report()
# else:
# return False, None
#
# def write(self, content):
# """Save content on disk"""
# with io.open(self.target, 'w', encoding='utf-8') as fp:
# fp.write(content)
# if not content.endswith(u'\n'):
# fp.write(u'\n')
#
# def commit(self):
# """git commit and return whether there were changes"""
# self.git.add('-A', '.')
# try:
# self.git.commit('-m', self.commit_msg)
# return True
# except sh.ErrorReturnCode_1:
# return False
#
# def ensure_repo_exists(self):
# """Create git repo if one does not exist yet"""
# if not os.path.isdir(self.cwd):
# os.makedirs(self.cwd)
# if not os.path.isdir(os.path.join(self.cwd, ".git")):
# self.git.init()
# self.git.config("user.email", "you@example.com")
# self.git.config("user.name", "Your Name")
#
# @staticmethod
# def clean():
# """Remove storage dir (delete all git repos)"""
# shutil.rmtree(PageHistory.STORAGE_DIR)
#
# Path: kibitzr/bash.py
# def execute_bash(code, stdin=None):
# if os.name == 'nt':
# executor = WindowsExecutor
# else:
# executor = BashExecutor
# return executor(code).execute(stdin)
#
# Path: kibitzr/transformer/utils.py
# def bake_parametrized(transform_func, pass_conf=False, **kwargs):
# def transform_factory(value, conf):
# if pass_conf:
# return functools.partial(
# transform_func,
# value,
# conf=conf,
# **kwargs
# )
# else:
# return functools.partial(
# transform_func,
# value,
# **kwargs
# )
# return transform_factory
. Output only the next line. | except: |
Given the code snippet: <|code_start|>
PYTHON_ERROR = "transform.python must set global variables ok and content"
logger = logging.getLogger(__name__)
def changes_transform_factory(value, conf):
style = value.lower() if value else None
return PageHistory(conf, style=style).report_changes
def python_transform(code, content, conf):
logger.info("Python transform")
logger.debug(code)
assert 'content' in code, PYTHON_ERROR
try:
namespace = {'ok': True, 'content': content}
context = {
'conf': conf,
'stash': LazyStash(),
'creds': settings().creds,
}
exec(code, context, namespace)
return namespace['ok'], six.text_type(namespace['content'])
<|code_end|>
, generate the next line using the imports in this file:
import logging
import traceback
import six
from kibitzr.stash import LazyStash
from kibitzr.conf import settings
from kibitzr.storage import PageHistory
from kibitzr.bash import execute_bash
from .utils import bake_parametrized
and context (functions, classes, or occasionally code) from other files:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/storage.py
# class PageHistory(object):
# """
# Single file changes history using git
# """
# STORAGE_DIR = "pages"
#
# def __init__(self, conf, storage_dir=None, style=None):
# self.storage_dir = storage_dir or self.STORAGE_DIR
# self.cwd = os.path.join(
# self.storage_dir,
# normalize_filename(conf['name']),
# )
# self.target = os.path.join(self.cwd, "content")
# self.git = sh.Command('git').bake(
# '--no-pager',
# _cwd=self.cwd,
# )
# self.ensure_repo_exists()
# if conf.get('url'):
# self.commit_msg = u"{name} at {url}".format(
# name=conf['name'],
# url=conf.get('url'),
# )
# else:
# self.commit_msg = conf['name']
# self.reporter = ChangesReporter(
# self.git,
# self.commit_msg,
# style,
# )
#
# def report_changes(self, content):
# """
# 1) Write changes in file,
# 2) Commit changes in git
# 3.1) If something changed, return tuple(True, changes)
# 3.2) If nothing changed, return tuple(False, None)
#
# If style is "verbose", return changes in human-friendly format,
# else use unified diff
# """
# self.write(content)
# if self.commit():
# return True, self.reporter.report()
# else:
# return False, None
#
# def write(self, content):
# """Save content on disk"""
# with io.open(self.target, 'w', encoding='utf-8') as fp:
# fp.write(content)
# if not content.endswith(u'\n'):
# fp.write(u'\n')
#
# def commit(self):
# """git commit and return whether there were changes"""
# self.git.add('-A', '.')
# try:
# self.git.commit('-m', self.commit_msg)
# return True
# except sh.ErrorReturnCode_1:
# return False
#
# def ensure_repo_exists(self):
# """Create git repo if one does not exist yet"""
# if not os.path.isdir(self.cwd):
# os.makedirs(self.cwd)
# if not os.path.isdir(os.path.join(self.cwd, ".git")):
# self.git.init()
# self.git.config("user.email", "you@example.com")
# self.git.config("user.name", "Your Name")
#
# @staticmethod
# def clean():
# """Remove storage dir (delete all git repos)"""
# shutil.rmtree(PageHistory.STORAGE_DIR)
#
# Path: kibitzr/bash.py
# def execute_bash(code, stdin=None):
# if os.name == 'nt':
# executor = WindowsExecutor
# else:
# executor = BashExecutor
# return executor(code).execute(stdin)
#
# Path: kibitzr/transformer/utils.py
# def bake_parametrized(transform_func, pass_conf=False, **kwargs):
# def transform_factory(value, conf):
# if pass_conf:
# return functools.partial(
# transform_func,
# value,
# conf=conf,
# **kwargs
# )
# else:
# return functools.partial(
# transform_func,
# value,
# **kwargs
# )
# return transform_factory
. Output only the next line. | except: |
Predict the next line after this snippet: <|code_start|>
PYTHON_ERROR = "transform.python must set global variables ok and content"
logger = logging.getLogger(__name__)
def changes_transform_factory(value, conf):
style = value.lower() if value else None
return PageHistory(conf, style=style).report_changes
<|code_end|>
using the current file's imports:
import logging
import traceback
import six
from kibitzr.stash import LazyStash
from kibitzr.conf import settings
from kibitzr.storage import PageHistory
from kibitzr.bash import execute_bash
from .utils import bake_parametrized
and any relevant context from other files:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/storage.py
# class PageHistory(object):
# """
# Single file changes history using git
# """
# STORAGE_DIR = "pages"
#
# def __init__(self, conf, storage_dir=None, style=None):
# self.storage_dir = storage_dir or self.STORAGE_DIR
# self.cwd = os.path.join(
# self.storage_dir,
# normalize_filename(conf['name']),
# )
# self.target = os.path.join(self.cwd, "content")
# self.git = sh.Command('git').bake(
# '--no-pager',
# _cwd=self.cwd,
# )
# self.ensure_repo_exists()
# if conf.get('url'):
# self.commit_msg = u"{name} at {url}".format(
# name=conf['name'],
# url=conf.get('url'),
# )
# else:
# self.commit_msg = conf['name']
# self.reporter = ChangesReporter(
# self.git,
# self.commit_msg,
# style,
# )
#
# def report_changes(self, content):
# """
# 1) Write changes in file,
# 2) Commit changes in git
# 3.1) If something changed, return tuple(True, changes)
# 3.2) If nothing changed, return tuple(False, None)
#
# If style is "verbose", return changes in human-friendly format,
# else use unified diff
# """
# self.write(content)
# if self.commit():
# return True, self.reporter.report()
# else:
# return False, None
#
# def write(self, content):
# """Save content on disk"""
# with io.open(self.target, 'w', encoding='utf-8') as fp:
# fp.write(content)
# if not content.endswith(u'\n'):
# fp.write(u'\n')
#
# def commit(self):
# """git commit and return whether there were changes"""
# self.git.add('-A', '.')
# try:
# self.git.commit('-m', self.commit_msg)
# return True
# except sh.ErrorReturnCode_1:
# return False
#
# def ensure_repo_exists(self):
# """Create git repo if one does not exist yet"""
# if not os.path.isdir(self.cwd):
# os.makedirs(self.cwd)
# if not os.path.isdir(os.path.join(self.cwd, ".git")):
# self.git.init()
# self.git.config("user.email", "you@example.com")
# self.git.config("user.name", "Your Name")
#
# @staticmethod
# def clean():
# """Remove storage dir (delete all git repos)"""
# shutil.rmtree(PageHistory.STORAGE_DIR)
#
# Path: kibitzr/bash.py
# def execute_bash(code, stdin=None):
# if os.name == 'nt':
# executor = WindowsExecutor
# else:
# executor = BashExecutor
# return executor(code).execute(stdin)
#
# Path: kibitzr/transformer/utils.py
# def bake_parametrized(transform_func, pass_conf=False, **kwargs):
# def transform_factory(value, conf):
# if pass_conf:
# return functools.partial(
# transform_func,
# value,
# conf=conf,
# **kwargs
# )
# else:
# return functools.partial(
# transform_func,
# value,
# **kwargs
# )
# return transform_factory
. Output only the next line. | def python_transform(code, content, conf): |
Predict the next line after this snippet: <|code_start|>
class ZapierNotify(WebHookNotify):
CREDS_KEY = "zapier"
POST_KEY = "text"
def configure_session(self):
self.session.headers.update({
"Content-Type": "application/x-www-form-urlencoded"
<|code_end|>
using the current file's imports:
from .webhook import WebHookNotify, webhook_factory
and any relevant context from other files:
# Path: kibitzr/notifier/webhook.py
# class WebHookNotify(object):
#
# CREDS_KEY = 'webhook'
# POST_KEY = 'message'
#
# def __init__(self, creds_key=None, conf=None, value=None, post_key=None):
# import requests
# self.session = requests.Session()
# self.url = self.load_url(creds_key or self.CREDS_KEY, value)
# self.post_key = post_key or self.POST_KEY
# self.configure_session()
#
# def load_url(self, creds_key, value):
# if value:
# return value
# else:
# webhook_creds = settings().creds[creds_key]
# return webhook_creds['url']
#
# def post(self, report):
# response = self.session.post(
# self.url,
# data=self.payload(report),
# )
# logger.debug(response.text)
# response.raise_for_status()
# return response
# __call__ = post
#
# def configure_session(self):
# pass
#
# def payload(self, report):
# return {self.post_key: report}
#
# def webhook_factory(klass):
# def notify_factory(conf, value):
# return klass(conf=conf, value=value)
# return notify_factory
. Output only the next line. | }) |
Next line prediction: <|code_start|>
class ZapierNotify(WebHookNotify):
CREDS_KEY = "zapier"
POST_KEY = "text"
def configure_session(self):
self.session.headers.update({
"Content-Type": "application/x-www-form-urlencoded"
<|code_end|>
. Use current file imports:
(from .webhook import WebHookNotify, webhook_factory)
and context including class names, function names, or small code snippets from other files:
# Path: kibitzr/notifier/webhook.py
# class WebHookNotify(object):
#
# CREDS_KEY = 'webhook'
# POST_KEY = 'message'
#
# def __init__(self, creds_key=None, conf=None, value=None, post_key=None):
# import requests
# self.session = requests.Session()
# self.url = self.load_url(creds_key or self.CREDS_KEY, value)
# self.post_key = post_key or self.POST_KEY
# self.configure_session()
#
# def load_url(self, creds_key, value):
# if value:
# return value
# else:
# webhook_creds = settings().creds[creds_key]
# return webhook_creds['url']
#
# def post(self, report):
# response = self.session.post(
# self.url,
# data=self.payload(report),
# )
# logger.debug(response.text)
# response.raise_for_status()
# return response
# __call__ = post
#
# def configure_session(self):
# pass
#
# def payload(self, report):
# return {self.post_key: report}
#
# def webhook_factory(klass):
# def notify_factory(conf, value):
# return klass(conf=conf, value=value)
# return notify_factory
. Output only the next line. | }) |
Predict the next line for this snippet: <|code_start|>
def jinja_transform(code, content, conf=None):
return JinjaTransform(code, conf or {})(content)
def test_content_is_passed():
ok, content = jinja_transform('hello {{ content }}!', 'world')
assert ok is True
<|code_end|>
with the help of current file imports:
from kibitzr.transformer.jinja_transform import JinjaTransform
from ...helpers import stash_mock
and context from other files:
# Path: kibitzr/transformer/jinja_transform.py
# class JinjaTransform(object):
#
# def __init__(self, code, conf):
# from jinja2 import Environment
# environment = Environment()
# environment.filters['text'] = text_filter
# environment.filters['int'] = int_filter
# environment.filters['float'] = float_filter
# environment.filters['dollars'] = dollars_filter
# self.template = environment.from_string(code)
# self.conf = conf
#
# def render(self, content, context=None):
# from jinja2 import TemplateError
# try:
# return True, self.template.render(context or self.context(content))
# except TemplateError:
# logger.warning("Jinja render failed", exc_info=True)
# return False, None
# __call__ = render
#
# def context(self, content):
# html = LazyHTML(content)
# xml = LazyXML(content)
# return {
# 'conf': self.conf,
# 'stash': LazyStash(),
# 'content': content,
# 'lines': content.splitlines(),
# 'json': LazyJSON(content),
# 'css': html.css,
# 'xpath': xml.xpath,
# 'env': os.environ,
# }
#
# Path: tests/helpers.py
# @contextlib.contextmanager
# def stash_mock():
# with tempfile.NamedTemporaryFile() as fp:
# fp.close()
# with mock.patch.object(Stash, 'FILENAME', fp.name):
# yield Stash()
, which may contain function names, class names, or code. Output only the next line. | assert content == "hello world!" |
Given the code snippet: <|code_start|>
def jinja_transform(code, content, conf=None):
return JinjaTransform(code, conf or {})(content)
def test_content_is_passed():
ok, content = jinja_transform('hello {{ content }}!', 'world')
assert ok is True
assert content == "hello world!"
def test_lines_are_passed():
ok, content = jinja_transform('{{ lines[1] }}', 'a\nb')
assert ok is True
<|code_end|>
, generate the next line using the imports in this file:
from kibitzr.transformer.jinja_transform import JinjaTransform
from ...helpers import stash_mock
and context (functions, classes, or occasionally code) from other files:
# Path: kibitzr/transformer/jinja_transform.py
# class JinjaTransform(object):
#
# def __init__(self, code, conf):
# from jinja2 import Environment
# environment = Environment()
# environment.filters['text'] = text_filter
# environment.filters['int'] = int_filter
# environment.filters['float'] = float_filter
# environment.filters['dollars'] = dollars_filter
# self.template = environment.from_string(code)
# self.conf = conf
#
# def render(self, content, context=None):
# from jinja2 import TemplateError
# try:
# return True, self.template.render(context or self.context(content))
# except TemplateError:
# logger.warning("Jinja render failed", exc_info=True)
# return False, None
# __call__ = render
#
# def context(self, content):
# html = LazyHTML(content)
# xml = LazyXML(content)
# return {
# 'conf': self.conf,
# 'stash': LazyStash(),
# 'content': content,
# 'lines': content.splitlines(),
# 'json': LazyJSON(content),
# 'css': html.css,
# 'xpath': xml.xpath,
# 'env': os.environ,
# }
#
# Path: tests/helpers.py
# @contextlib.contextmanager
# def stash_mock():
# with tempfile.NamedTemporaryFile() as fp:
# fp.close()
# with mock.patch.object(Stash, 'FILENAME', fp.name):
# yield Stash()
. Output only the next line. | assert content == "b" |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
HOME_PAGE = 'https://kibitzr.github.io/'
def persistent_firefox():
if not os.path.exists(PROFILE_DIR):
os.makedirs(PROFILE_DIR)
print("Kibitzr is running Firefox in persistent profile mode.")
with firefox(headless=False) as driver:
driver.get(HOME_PAGE)
while True:
prompt_return()
try:
# Property raises when browser is closed:
driver.title
except:
# All kinds of things happen when closing Firefox
break
else:
update_profile(driver)
print(
"Firefox profile is saved. "
"Close browser now to reuse profile in further runs."
<|code_end|>
. Use current file imports:
(import os
import time
import shutil
import logging
import traceback
import collections
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
)
from jinja2 import Template
from kibitzr.conf import settings
from .launcher import firefox, PROFILE_DIR
from .trigger import prompt_return)
and context including class names, function names, or small code snippets from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/fetcher/browser/launcher.py
# @contextmanager
# def firefox(headless=True):
# """
# Context manager returning Selenium webdriver.
# Instance is reused and must be cleaned up on exit.
# """
# from selenium import webdriver
# from selenium.webdriver.firefox.options import Options
# if headless:
# driver_key = 'headless'
# firefox_options = Options()
# firefox_options.add_argument('-headless')
# else:
# driver_key = 'headed'
# firefox_options = None
# # Load profile, if it exists:
# if os.path.isdir(PROFILE_DIR):
# firefox_profile = webdriver.FirefoxProfile(PROFILE_DIR)
# else:
# firefox_profile = None
# if FIREFOX_INSTANCE[driver_key] is None:
# FIREFOX_INSTANCE[driver_key] = webdriver.Firefox(
# firefox_profile=firefox_profile,
# firefox_options=firefox_options,
# )
# yield FIREFOX_INSTANCE[driver_key]
#
# PROFILE_DIR = 'firefox_profile'
#
# Path: kibitzr/fetcher/browser/trigger.py
# def prompt_return():
# compat_input(
# "Press Enter to save Firefox profile; "
# "or close Firefox to cancel: "
# )
. Output only the next line. | ) |
Next line prediction: <|code_start|> driver.get(HOME_PAGE)
while True:
prompt_return()
try:
# Property raises when browser is closed:
driver.title
except:
# All kinds of things happen when closing Firefox
break
else:
update_profile(driver)
print(
"Firefox profile is saved. "
"Close browser now to reuse profile in further runs."
)
print(
"Firefox is closed. "
"To delete saved profile remove following directory: {0}"
.format(os.path.abspath(PROFILE_DIR))
)
def update_profile(driver):
if os.path.exists(PROFILE_DIR):
shutil.rmtree(PROFILE_DIR)
shutil.copytree(
driver.capabilities['moz:profile'],
PROFILE_DIR,
ignore=shutil.ignore_patterns(
"parent.lock",
<|code_end|>
. Use current file imports:
(import os
import time
import shutil
import logging
import traceback
import collections
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
)
from jinja2 import Template
from kibitzr.conf import settings
from .launcher import firefox, PROFILE_DIR
from .trigger import prompt_return)
and context including class names, function names, or small code snippets from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/fetcher/browser/launcher.py
# @contextmanager
# def firefox(headless=True):
# """
# Context manager returning Selenium webdriver.
# Instance is reused and must be cleaned up on exit.
# """
# from selenium import webdriver
# from selenium.webdriver.firefox.options import Options
# if headless:
# driver_key = 'headless'
# firefox_options = Options()
# firefox_options.add_argument('-headless')
# else:
# driver_key = 'headed'
# firefox_options = None
# # Load profile, if it exists:
# if os.path.isdir(PROFILE_DIR):
# firefox_profile = webdriver.FirefoxProfile(PROFILE_DIR)
# else:
# firefox_profile = None
# if FIREFOX_INSTANCE[driver_key] is None:
# FIREFOX_INSTANCE[driver_key] = webdriver.Firefox(
# firefox_profile=firefox_profile,
# firefox_options=firefox_options,
# )
# yield FIREFOX_INSTANCE[driver_key]
#
# PROFILE_DIR = 'firefox_profile'
#
# Path: kibitzr/fetcher/browser/trigger.py
# def prompt_return():
# compat_input(
# "Press Enter to save Firefox profile; "
# "or close Firefox to cancel: "
# )
. Output only the next line. | "lock", |
Predict the next line for this snippet: <|code_start|> # Property raises when browser is closed:
driver.title
except:
# All kinds of things happen when closing Firefox
break
else:
update_profile(driver)
print(
"Firefox profile is saved. "
"Close browser now to reuse profile in further runs."
)
print(
"Firefox is closed. "
"To delete saved profile remove following directory: {0}"
.format(os.path.abspath(PROFILE_DIR))
)
def update_profile(driver):
if os.path.exists(PROFILE_DIR):
shutil.rmtree(PROFILE_DIR)
shutil.copytree(
driver.capabilities['moz:profile'],
PROFILE_DIR,
ignore=shutil.ignore_patterns(
"parent.lock",
"lock",
".parentlock",
"*.sqlite-shm",
"*.sqlite-wal",
<|code_end|>
with the help of current file imports:
import os
import time
import shutil
import logging
import traceback
import collections
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
)
from jinja2 import Template
from kibitzr.conf import settings
from .launcher import firefox, PROFILE_DIR
from .trigger import prompt_return
and context from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/fetcher/browser/launcher.py
# @contextmanager
# def firefox(headless=True):
# """
# Context manager returning Selenium webdriver.
# Instance is reused and must be cleaned up on exit.
# """
# from selenium import webdriver
# from selenium.webdriver.firefox.options import Options
# if headless:
# driver_key = 'headless'
# firefox_options = Options()
# firefox_options.add_argument('-headless')
# else:
# driver_key = 'headed'
# firefox_options = None
# # Load profile, if it exists:
# if os.path.isdir(PROFILE_DIR):
# firefox_profile = webdriver.FirefoxProfile(PROFILE_DIR)
# else:
# firefox_profile = None
# if FIREFOX_INSTANCE[driver_key] is None:
# FIREFOX_INSTANCE[driver_key] = webdriver.Firefox(
# firefox_profile=firefox_profile,
# firefox_options=firefox_options,
# )
# yield FIREFOX_INSTANCE[driver_key]
#
# PROFILE_DIR = 'firefox_profile'
#
# Path: kibitzr/fetcher/browser/trigger.py
# def prompt_return():
# compat_input(
# "Press Enter to save Firefox profile; "
# "or close Firefox to cancel: "
# )
, which may contain function names, class names, or code. Output only the next line. | ), |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger(__name__)
HOME_PAGE = 'https://kibitzr.github.io/'
def persistent_firefox():
if not os.path.exists(PROFILE_DIR):
os.makedirs(PROFILE_DIR)
print("Kibitzr is running Firefox in persistent profile mode.")
with firefox(headless=False) as driver:
driver.get(HOME_PAGE)
while True:
prompt_return()
try:
# Property raises when browser is closed:
driver.title
except:
# All kinds of things happen when closing Firefox
break
else:
update_profile(driver)
print(
"Firefox profile is saved. "
"Close browser now to reuse profile in further runs."
)
print(
"Firefox is closed. "
"To delete saved profile remove following directory: {0}"
.format(os.path.abspath(PROFILE_DIR))
<|code_end|>
with the help of current file imports:
import os
import time
import shutil
import logging
import traceback
import collections
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
)
from jinja2 import Template
from kibitzr.conf import settings
from .launcher import firefox, PROFILE_DIR
from .trigger import prompt_return
and context from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/fetcher/browser/launcher.py
# @contextmanager
# def firefox(headless=True):
# """
# Context manager returning Selenium webdriver.
# Instance is reused and must be cleaned up on exit.
# """
# from selenium import webdriver
# from selenium.webdriver.firefox.options import Options
# if headless:
# driver_key = 'headless'
# firefox_options = Options()
# firefox_options.add_argument('-headless')
# else:
# driver_key = 'headed'
# firefox_options = None
# # Load profile, if it exists:
# if os.path.isdir(PROFILE_DIR):
# firefox_profile = webdriver.FirefoxProfile(PROFILE_DIR)
# else:
# firefox_profile = None
# if FIREFOX_INSTANCE[driver_key] is None:
# FIREFOX_INSTANCE[driver_key] = webdriver.Firefox(
# firefox_profile=firefox_profile,
# firefox_options=firefox_options,
# )
# yield FIREFOX_INSTANCE[driver_key]
#
# PROFILE_DIR = 'firefox_profile'
#
# Path: kibitzr/fetcher/browser/trigger.py
# def prompt_return():
# compat_input(
# "Press Enter to save Firefox profile; "
# "or close Firefox to cancel: "
# )
, which may contain function names, class names, or code. Output only the next line. | ) |
Continue the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
def notify_factory(conf, value):
@functools.wraps(notify)
def baked_notify(report):
return notify(
conf=conf,
report=report,
notifier_conf=value,
)
return baked_notify
def notify(conf, report, notifier_conf):
logger.info("Executing SMTP notifier")
credentials = settings().creds.get('smtp', {})
<|code_end|>
. Use current file imports:
import logging
import functools
import six
from smtplib import SMTP
from ..conf import settings
from ..compat import SMTPNotSupportedError
and context (classes, functions, or code) from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/compat.py
. Output only the next line. | user = credentials.get('user', '') |
Based on the snippet: <|code_start|>
logger = logging.getLogger(__name__)
def notify_factory(conf, value):
@functools.wraps(notify)
def baked_notify(report):
return notify(
conf=conf,
report=report,
notifier_conf=value,
)
return baked_notify
def notify(conf, report, notifier_conf):
logger.info("Executing SMTP notifier")
credentials = settings().creds.get('smtp', {})
user = credentials.get('user', '')
password = credentials.get('password', '')
host = credentials.get('host', 'localhost')
port = credentials.get('port', 25)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import functools
import six
from smtplib import SMTP
from ..conf import settings
from ..compat import SMTPNotSupportedError
and context (classes, functions, sometimes code) from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/compat.py
. Output only the next line. | try: |
Here is a snippet: <|code_start|>
@pytest.mark.parametrize("selector,expected", [
pytest.param('boolean(//body/h2/a)', 'True', id='boolean'),
pytest.param("count(//div)", "2.0", id="float"),
pytest.param("string(//a)", "Page", id="string"),
pytest.param("//body/h2/a/@href", "page.html", id="attribute"),
pytest.param(
'//body/h2/a[@id="page-link"]',
'<a href="page.html" id="page-link">Page</a>',
id='element'
),
pytest.param(
'/html/namespace::*[name()]',
'xml="http://www.w3.org/XML/1998/namespace"',
id='namespace'
),
])
def test_xpath_selector(selector, expected):
ok, content = run_transform('xpath', selector, HTML)
assert ok is True
assert content == expected
def test_xpath_selector_all():
ok, content = run_transform('xpath-all', '//div', HTML)
assert ok is True
assert content == u'\n'.join([
u'<div id="content"> Привет, Мир! </div>',
<|code_end|>
. Write the next line using the current file imports:
import pytest
from .helpers import run_transform, HTML
and context from other files:
# Path: tests/unit/transforms/helpers.py
# def run_transform(key, value, content):
# pipeline = transform_factory({'transform': [{key: value}]})
# return pipeline(True, content)
#
# HTML = u"""<?xml version="1.0" encoding="utf-8"?>
# <html>
# <body>
# <h2 class="header nav">
# <a href="page.html" id="page-link">Page</a>
# </h2>
# <div id="content">
# Привет, Мир!
# </div>
# <div class="footer">
# Footer content
# </div>
# </body>
# </html>
# """
, which may include functions, classes, or code. Output only the next line. | u'<div class="footer"> Footer content </div>', |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.mark.parametrize("selector,expected", [
pytest.param('boolean(//body/h2/a)', 'True', id='boolean'),
pytest.param("count(//div)", "2.0", id="float"),
pytest.param("string(//a)", "Page", id="string"),
pytest.param("//body/h2/a/@href", "page.html", id="attribute"),
pytest.param(
'//body/h2/a[@id="page-link"]',
'<a href="page.html" id="page-link">Page</a>',
id='element'
),
pytest.param(
'/html/namespace::*[name()]',
'xml="http://www.w3.org/XML/1998/namespace"',
id='namespace'
),
])
def test_xpath_selector(selector, expected):
ok, content = run_transform('xpath', selector, HTML)
assert ok is True
assert content == expected
def test_xpath_selector_all():
ok, content = run_transform('xpath-all', '//div', HTML)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from .helpers import run_transform, HTML
and context:
# Path: tests/unit/transforms/helpers.py
# def run_transform(key, value, content):
# pipeline = transform_factory({'transform': [{key: value}]})
# return pipeline(True, content)
#
# HTML = u"""<?xml version="1.0" encoding="utf-8"?>
# <html>
# <body>
# <h2 class="header nav">
# <a href="page.html" id="page-link">Page</a>
# </h2>
# <div id="content">
# Привет, Мир!
# </div>
# <div class="footer">
# Footer content
# </div>
# </body>
# </html>
# """
which might include code, classes, or functions. Output only the next line. | assert ok is True |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
def test_tag_selector():
ok, content = run_transform('tag', 'a', HTML)
assert ok is True
assert content == '<a href="page.html" id="page-link">Page</a>'
def test_css_selector():
ok, content = run_transform('css', 'body h2.nav a#page-link', HTML)
assert ok is True
assert content == '<a href="page.html" id="page-link">Page</a>'
def test_css_selector_all():
ok, content = run_transform('css-all', 'div', HTML)
assert ok is True
assert prettify(content) == u'\n'.join([
u'<div id="content">',
u' Привет, Мир!',
u'</div>',
u'',
u'<div class="footer">',
<|code_end|>
with the help of current file imports:
from bs4 import BeautifulSoup
from .helpers import run_transform, HTML
and context from other files:
# Path: tests/unit/transforms/helpers.py
# def run_transform(key, value, content):
# pipeline = transform_factory({'transform': [{key: value}]})
# return pipeline(True, content)
#
# HTML = u"""<?xml version="1.0" encoding="utf-8"?>
# <html>
# <body>
# <h2 class="header nav">
# <a href="page.html" id="page-link">Page</a>
# </h2>
# <div id="content">
# Привет, Мир!
# </div>
# <div class="footer">
# Footer content
# </div>
# </body>
# </html>
# """
, which may contain function names, class names, or code. Output only the next line. | u' Footer content', |
Continue the code snippet: <|code_start|>
def test_tag_selector():
ok, content = run_transform('tag', 'a', HTML)
assert ok is True
assert content == '<a href="page.html" id="page-link">Page</a>'
def test_css_selector():
ok, content = run_transform('css', 'body h2.nav a#page-link', HTML)
assert ok is True
assert content == '<a href="page.html" id="page-link">Page</a>'
def test_css_selector_all():
ok, content = run_transform('css-all', 'div', HTML)
assert ok is True
assert prettify(content) == u'\n'.join([
u'<div id="content">',
u' Привет, Мир!',
u'</div>',
u'',
u'<div class="footer">',
u' Footer content',
u'</div>',
])
def test_extract_test():
ok, content = run_transform('text', None, HTML)
assert ok is True
<|code_end|>
. Use current file imports:
from bs4 import BeautifulSoup
from .helpers import run_transform, HTML
and context (classes, functions, or code) from other files:
# Path: tests/unit/transforms/helpers.py
# def run_transform(key, value, content):
# pipeline = transform_factory({'transform': [{key: value}]})
# return pipeline(True, content)
#
# HTML = u"""<?xml version="1.0" encoding="utf-8"?>
# <html>
# <body>
# <h2 class="header nav">
# <a href="page.html" id="page-link">Page</a>
# </h2>
# <div id="content">
# Привет, Мир!
# </div>
# <div class="footer">
# Footer content
# </div>
# </body>
# </html>
# """
. Output only the next line. | assert content.strip() == u"\n".join([ |
Predict the next line for this snippet: <|code_start|>
class BashNotify(object):
def __init__(self, value):
self.code = value
def __call__(self, report):
execute_bash(self.code, report)
<|code_end|>
with the help of current file imports:
from ..bash import execute_bash
and context from other files:
# Path: kibitzr/bash.py
# def execute_bash(code, stdin=None):
# if os.name == 'nt':
# executor = WindowsExecutor
# else:
# executor = BashExecutor
# return executor(code).execute(stdin)
, which may contain function names, class names, or code. Output only the next line. | def register(registry): |
Given snippet: <|code_start|> scenario = (
(u"hello", True, u"test at web\n@@ -0,0 +1 @@\n+hello"),
(u"world", True, u"test at web\n@@ -1 +1 @@\n-hello\n+world"),
(u"world", False, None),
)
for content, changed, report in scenario:
result = page_history.report_changes(content)
assert result == (changed, report)
def test_verbose_diff_sample():
with history('verbose') as page_history:
scenario = (
(u"hello", True, u"test at web\nhello"),
(u"world", True, u"test at web\n"
u"New value:\nworld\n"
u"Old value:\nhello\n"),
(u"world", False, None),
)
for content, changed, report in scenario:
result = page_history.report_changes(content)
assert result == (changed, report)
def test_word_diff_sample():
with history('word') as page_history:
scenario = (
(u"hello", True, u"hello"),
(u"world", True, u"[-hello-]{+world+}"),
(u"world", False, None),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import contextlib
import tempfile
import shutil
from kibitzr.storage import PageHistory
and context:
# Path: kibitzr/storage.py
# class PageHistory(object):
# """
# Single file changes history using git
# """
# STORAGE_DIR = "pages"
#
# def __init__(self, conf, storage_dir=None, style=None):
# self.storage_dir = storage_dir or self.STORAGE_DIR
# self.cwd = os.path.join(
# self.storage_dir,
# normalize_filename(conf['name']),
# )
# self.target = os.path.join(self.cwd, "content")
# self.git = sh.Command('git').bake(
# '--no-pager',
# _cwd=self.cwd,
# )
# self.ensure_repo_exists()
# if conf.get('url'):
# self.commit_msg = u"{name} at {url}".format(
# name=conf['name'],
# url=conf.get('url'),
# )
# else:
# self.commit_msg = conf['name']
# self.reporter = ChangesReporter(
# self.git,
# self.commit_msg,
# style,
# )
#
# def report_changes(self, content):
# """
# 1) Write changes in file,
# 2) Commit changes in git
# 3.1) If something changed, return tuple(True, changes)
# 3.2) If nothing changed, return tuple(False, None)
#
# If style is "verbose", return changes in human-friendly format,
# else use unified diff
# """
# self.write(content)
# if self.commit():
# return True, self.reporter.report()
# else:
# return False, None
#
# def write(self, content):
# """Save content on disk"""
# with io.open(self.target, 'w', encoding='utf-8') as fp:
# fp.write(content)
# if not content.endswith(u'\n'):
# fp.write(u'\n')
#
# def commit(self):
# """git commit and return whether there were changes"""
# self.git.add('-A', '.')
# try:
# self.git.commit('-m', self.commit_msg)
# return True
# except sh.ErrorReturnCode_1:
# return False
#
# def ensure_repo_exists(self):
# """Create git repo if one does not exist yet"""
# if not os.path.isdir(self.cwd):
# os.makedirs(self.cwd)
# if not os.path.isdir(os.path.join(self.cwd, ".git")):
# self.git.init()
# self.git.config("user.email", "you@example.com")
# self.git.config("user.name", "Your Name")
#
# @staticmethod
# def clean():
# """Remove storage dir (delete all git repos)"""
# shutil.rmtree(PageHistory.STORAGE_DIR)
which might include code, classes, or functions. Output only the next line. | ) |
Continue the code snippet: <|code_start|> url: https://www.worldtimeserver.com/current_time_in_US-NY.aspx
transform:
- css: "span#theTime"
- text
notify:
- python: print(content)
schedule:
every: 1
unit: day
at: "20:30"
- name: Crazy scheduling alarm
url: https://www.worldtimeserver.com/current_time_in_US-NY.aspx
transform:
- css: "span#theTime"
- text
notify:
- python: print(content)
schedule:
- every: 1
unit: days
at: "15:30"
- every: hour
- every: 4
unit: minutes
- every: saturday
at: "11:17"
"""
sample_creds = """
<|code_end|>
. Use current file imports:
import pytest
from kibitzr.conf import (
settings,
ReloadableSettings,
ConfigurationError,
)
from kibitzr.timeline import TimelineRule
from ..compat import mock
from .helpers import patch_conf, patch_creds
and context (classes, functions, or code) from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# class CompositeCreds(object):
# class PlainYamlCreds(object):
# class SettingsParser(object):
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# def __init__(self, config_dir):
# def detect_config_dir(cls):
# def instance(cls):
# def reread(self):
# def read_conf(self):
# def open_conf(self):
# def __init__(self, config_dir):
# def reread(self):
# def load_extensions(self):
# def get(self, key, default=None):
# def __getitem__(self, key):
# def __init__(self, config_dir):
# def __contains__(self, key):
# def __getitem__(self, key):
# def reread(self):
# def open_creds(self):
# def settings():
# def parse_checks(self, conf):
# def inject_notifiers(check, notifiers):
# def inject_scenarios(check, scenarios):
# def expand_schedule(check):
# def unpack_batches(checks):
# def inject_missing_names(cls, checks):
# def url_to_name(cls, url):
# def unpack_templates(checks, templates):
#
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
#
# Path: tests/compat.py
#
# Path: tests/unit/helpers.py
# @contextlib.contextmanager
# def patch_conf(data):
# with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
# yield fake_method
#
# @contextlib.contextmanager
# def patch_creds(data):
# with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
# yield fake_method
. Output only the next line. | mailgun: |
Given snippet: <|code_start|> url: https://www.worldtimeserver.com/current_time_in_US-NY.aspx
transform:
- css: "span#theTime"
- text
notify:
- python: print(content)
schedule:
every: day
at: "6:30"
- name: Noon alarm
url: https://www.worldtimeserver.com/current_time_in_US-NY.aspx
transform:
- css: "span#theTime"
- text
notify:
- python: print(content)
schedule:
every: 1
unit: day
at: "20:30"
- name: Crazy scheduling alarm
url: https://www.worldtimeserver.com/current_time_in_US-NY.aspx
transform:
- css: "span#theTime"
- text
notify:
- python: print(content)
schedule:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from kibitzr.conf import (
settings,
ReloadableSettings,
ConfigurationError,
)
from kibitzr.timeline import TimelineRule
from ..compat import mock
from .helpers import patch_conf, patch_creds
and context:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# class CompositeCreds(object):
# class PlainYamlCreds(object):
# class SettingsParser(object):
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# def __init__(self, config_dir):
# def detect_config_dir(cls):
# def instance(cls):
# def reread(self):
# def read_conf(self):
# def open_conf(self):
# def __init__(self, config_dir):
# def reread(self):
# def load_extensions(self):
# def get(self, key, default=None):
# def __getitem__(self, key):
# def __init__(self, config_dir):
# def __contains__(self, key):
# def __getitem__(self, key):
# def reread(self):
# def open_creds(self):
# def settings():
# def parse_checks(self, conf):
# def inject_notifiers(check, notifiers):
# def inject_scenarios(check, scenarios):
# def expand_schedule(check):
# def unpack_batches(checks):
# def inject_missing_names(cls, checks):
# def url_to_name(cls, url):
# def unpack_templates(checks, templates):
#
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
#
# Path: tests/compat.py
#
# Path: tests/unit/helpers.py
# @contextlib.contextmanager
# def patch_conf(data):
# with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
# yield fake_method
#
# @contextlib.contextmanager
# def patch_creds(data):
# with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
# yield fake_method
which might include code, classes, or functions. Output only the next line. | - every: 1 |
Next line prediction: <|code_start|>
sample_conf = """
notifiers:
slack:
url: XXX
templates:
teamcity:
transforms:
- text
- changes: verbose
<|code_end|>
. Use current file imports:
(import pytest
from kibitzr.conf import (
settings,
ReloadableSettings,
ConfigurationError,
)
from kibitzr.timeline import TimelineRule
from ..compat import mock
from .helpers import patch_conf, patch_creds)
and context including class names, function names, or small code snippets from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# class CompositeCreds(object):
# class PlainYamlCreds(object):
# class SettingsParser(object):
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# def __init__(self, config_dir):
# def detect_config_dir(cls):
# def instance(cls):
# def reread(self):
# def read_conf(self):
# def open_conf(self):
# def __init__(self, config_dir):
# def reread(self):
# def load_extensions(self):
# def get(self, key, default=None):
# def __getitem__(self, key):
# def __init__(self, config_dir):
# def __contains__(self, key):
# def __getitem__(self, key):
# def reread(self):
# def open_creds(self):
# def settings():
# def parse_checks(self, conf):
# def inject_notifiers(check, notifiers):
# def inject_scenarios(check, scenarios):
# def expand_schedule(check):
# def unpack_batches(checks):
# def inject_missing_names(cls, checks):
# def url_to_name(cls, url):
# def unpack_templates(checks, templates):
#
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
#
# Path: tests/compat.py
#
# Path: tests/unit/helpers.py
# @contextlib.contextmanager
# def patch_conf(data):
# with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
# yield fake_method
#
# @contextlib.contextmanager
# def patch_creds(data):
# with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
# yield fake_method
. Output only the next line. | scenario: |
Given the following code snippet before the placeholder: <|code_start|>
sample_conf = """
notifiers:
slack:
url: XXX
templates:
teamcity:
transforms:
- text
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from kibitzr.conf import (
settings,
ReloadableSettings,
ConfigurationError,
)
from kibitzr.timeline import TimelineRule
from ..compat import mock
from .helpers import patch_conf, patch_creds
and context including class names, function names, and sometimes code from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# class CompositeCreds(object):
# class PlainYamlCreds(object):
# class SettingsParser(object):
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# def __init__(self, config_dir):
# def detect_config_dir(cls):
# def instance(cls):
# def reread(self):
# def read_conf(self):
# def open_conf(self):
# def __init__(self, config_dir):
# def reread(self):
# def load_extensions(self):
# def get(self, key, default=None):
# def __getitem__(self, key):
# def __init__(self, config_dir):
# def __contains__(self, key):
# def __getitem__(self, key):
# def reread(self):
# def open_creds(self):
# def settings():
# def parse_checks(self, conf):
# def inject_notifiers(check, notifiers):
# def inject_scenarios(check, scenarios):
# def expand_schedule(check):
# def unpack_batches(checks):
# def inject_missing_names(cls, checks):
# def url_to_name(cls, url):
# def unpack_templates(checks, templates):
#
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
#
# Path: tests/compat.py
#
# Path: tests/unit/helpers.py
# @contextlib.contextmanager
# def patch_conf(data):
# with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
# yield fake_method
#
# @contextlib.contextmanager
# def patch_creds(data):
# with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
# yield fake_method
. Output only the next line. | - changes: verbose |
Continue the code snippet: <|code_start|>templates:
teamcity:
transforms:
- text
- changes: verbose
scenario:
login
notify:
- smtp: kibitzrrr@gmail.com
period: 3600
scenarios:
login: |
driver.find_element_by_css_selector(".login").click()
checks:
- name: Project Build Status
url: http://teamcity/build/id
template: teamcity
period: 60
- batch: WordPress {0} Plugin
url-pattern: "http://wordpress/{0}"
notify:
- mailgun
items:
- A
- B
- name: Alarm clock
<|code_end|>
. Use current file imports:
import pytest
from kibitzr.conf import (
settings,
ReloadableSettings,
ConfigurationError,
)
from kibitzr.timeline import TimelineRule
from ..compat import mock
from .helpers import patch_conf, patch_creds
and context (classes, functions, or code) from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# class CompositeCreds(object):
# class PlainYamlCreds(object):
# class SettingsParser(object):
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# def __init__(self, config_dir):
# def detect_config_dir(cls):
# def instance(cls):
# def reread(self):
# def read_conf(self):
# def open_conf(self):
# def __init__(self, config_dir):
# def reread(self):
# def load_extensions(self):
# def get(self, key, default=None):
# def __getitem__(self, key):
# def __init__(self, config_dir):
# def __contains__(self, key):
# def __getitem__(self, key):
# def reread(self):
# def open_creds(self):
# def settings():
# def parse_checks(self, conf):
# def inject_notifiers(check, notifiers):
# def inject_scenarios(check, scenarios):
# def expand_schedule(check):
# def unpack_batches(checks):
# def inject_missing_names(cls, checks):
# def url_to_name(cls, url):
# def unpack_templates(checks, templates):
#
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
#
# Path: tests/compat.py
#
# Path: tests/unit/helpers.py
# @contextlib.contextmanager
# def patch_conf(data):
# with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
# yield fake_method
#
# @contextlib.contextmanager
# def patch_creds(data):
# with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
# yield fake_method
. Output only the next line. | url: https://www.worldtimeserver.com/current_time_in_US-NY.aspx |
Continue the code snippet: <|code_start|>
sample_conf = """
notifiers:
slack:
<|code_end|>
. Use current file imports:
import pytest
from kibitzr.conf import (
settings,
ReloadableSettings,
ConfigurationError,
)
from kibitzr.timeline import TimelineRule
from ..compat import mock
from .helpers import patch_conf, patch_creds
and context (classes, functions, or code) from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# class CompositeCreds(object):
# class PlainYamlCreds(object):
# class SettingsParser(object):
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# def __init__(self, config_dir):
# def detect_config_dir(cls):
# def instance(cls):
# def reread(self):
# def read_conf(self):
# def open_conf(self):
# def __init__(self, config_dir):
# def reread(self):
# def load_extensions(self):
# def get(self, key, default=None):
# def __getitem__(self, key):
# def __init__(self, config_dir):
# def __contains__(self, key):
# def __getitem__(self, key):
# def reread(self):
# def open_creds(self):
# def settings():
# def parse_checks(self, conf):
# def inject_notifiers(check, notifiers):
# def inject_scenarios(check, scenarios):
# def expand_schedule(check):
# def unpack_batches(checks):
# def inject_missing_names(cls, checks):
# def url_to_name(cls, url):
# def unpack_templates(checks, templates):
#
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
#
# Path: tests/compat.py
#
# Path: tests/unit/helpers.py
# @contextlib.contextmanager
# def patch_conf(data):
# with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
# yield fake_method
#
# @contextlib.contextmanager
# def patch_creds(data):
# with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
# yield fake_method
. Output only the next line. | url: XXX |
Given snippet: <|code_start|>
sample_conf = """
notifiers:
slack:
url: XXX
templates:
teamcity:
transforms:
- text
- changes: verbose
scenario:
login
notify:
- smtp: kibitzrrr@gmail.com
period: 3600
scenarios:
login: |
driver.find_element_by_css_selector(".login").click()
checks:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from kibitzr.conf import (
settings,
ReloadableSettings,
ConfigurationError,
)
from kibitzr.timeline import TimelineRule
from ..compat import mock
from .helpers import patch_conf, patch_creds
and context:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# class CompositeCreds(object):
# class PlainYamlCreds(object):
# class SettingsParser(object):
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# CREDENTIALS_FILENAME = 'kibitzr-creds.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
# def __init__(self, config_dir):
# def detect_config_dir(cls):
# def instance(cls):
# def reread(self):
# def read_conf(self):
# def open_conf(self):
# def __init__(self, config_dir):
# def reread(self):
# def load_extensions(self):
# def get(self, key, default=None):
# def __getitem__(self, key):
# def __init__(self, config_dir):
# def __contains__(self, key):
# def __getitem__(self, key):
# def reread(self):
# def open_creds(self):
# def settings():
# def parse_checks(self, conf):
# def inject_notifiers(check, notifiers):
# def inject_scenarios(check, scenarios):
# def expand_schedule(check):
# def unpack_batches(checks):
# def inject_missing_names(cls, checks):
# def url_to_name(cls, url):
# def unpack_templates(checks, templates):
#
# Path: kibitzr/timeline.py
# class Timeline(object):
# RE_TIME = re.compile(r'\d?\d:\d\d')
# def __init__(self, scheduler=None):
# def parse_check(cls, check):
# def _clean_single_schedule(cls, check, schedule_dict):
# def _clean_unit(check, unit):
# def _clean_at(cls, check, at):
# def schedule_checks(self, checkers):
# def parse_check(check):
# def run_pending():
# def schedule_checks(checkers):
#
# Path: tests/compat.py
#
# Path: tests/unit/helpers.py
# @contextlib.contextmanager
# def patch_conf(data):
# with patch_source(ReloadableSettings, 'open_conf', data) as fake_method:
# yield fake_method
#
# @contextlib.contextmanager
# def patch_creds(data):
# with patch_source(PlainYamlCreds, 'open_creds', data) as fake_method:
# yield fake_method
which might include code, classes, or functions. Output only the next line. | - name: Project Build Status |
Using the snippet: <|code_start|> 'json': LazyJSON(content),
'css': html.css,
'xpath': xml.xpath,
'env': os.environ,
}
RE_NOT_FLOAT = re.compile(r'[^0-9\.]')
def ignore_cast_error(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except (TypeError, ValueError):
logger.warning("Invalid value passed in Jinja transform",
exc_info=True)
return None
return wrapper
@ignore_cast_error
def dollars_filter(number):
sign = '-' if number < 0 else ''
return '{0}${1:,}'.format(sign, abs(number))
@ignore_cast_error
def int_filter(text):
<|code_end|>
, determine the next line of code. You have imports:
import re
import os
import logging
import json
import functools
import six
from kibitzr.stash import LazyStash
from .html import deep_recursion, SoupOps
from .xpath import parse_html, serialize_xpath_results
from jinja2 import Environment
from jinja2 import TemplateError
from bs4 import BeautifulSoup
and context (class names, function names, or code) available:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/transformer/html.py
# @contextlib.contextmanager
# def deep_recursion():
# old_limit = sys.getrecursionlimit()
# try:
# sys.setrecursionlimit(100000)
# yield
# finally:
# sys.setrecursionlimit(old_limit)
#
# class SoupOps(object):
# def __init__(self, selector=None, select_all=False):
# self.selector = selector
# self.select_all = select_all
#
# def tag_selector(self, html):
# with soup(html) as doc:
# element = doc.find(self.selector)
# if element:
# return True, six.text_type(element)
# else:
# logger.warning('Tag not found: %r', self.selector)
# return False, html
#
# def css_selector(self, html):
# with soup(html) as doc:
# try:
# elements = doc.select(self.selector)
# if self.select_all:
# result = u"".join(six.text_type(x)
# for x in elements)
# else:
# result = six.text_type(elements[0])
# return True, result
# except IndexError:
# logger.warning('CSS selector not found: %r', self.selector)
# return False, html
#
# @staticmethod
# def extract_text(html):
# with soup(html) as doc:
# strings = doc.stripped_strings
# return True, u'\n'.join([
# line
# for line in strings
# if line
# ])
#
# @classmethod
# def factory(cls, key, value, conf):
# def transform(content):
# instance = cls(selector=value, select_all=select_all)
# method = handler.__get__(instance, cls)
# return method(content)
# action, _, all_flag = key.partition('-')
# select_all = (all_flag == 'all')
# handler = cls.SHORTCUTS[action]
# return transform
#
# SHORTCUTS = {
# 'tag': tag_selector,
# 'css': css_selector,
# 'text': extract_text,
# }
#
# Path: kibitzr/transformer/xpath.py
# def parse_html(html):
# """
# Returns `html` parsed with lxml.
#
# :param html: Unicode content
# """
# from defusedxml import lxml as dlxml
# from lxml import etree
#
# # lxml requires argument to be bytes
# # see https://github.com/kibitzr/kibitzr/issues/47
# encoded = html.encode('utf-8')
# return dlxml.fromstring(encoded, parser=etree.HTMLParser())
#
# def serialize_xpath_results(xpath_results, select_all):
# """
# Serializes results of xpath evaluation.
#
# :param xpath_results: Results of xpath evaluation.
# See: https://lxml.de/xpathxslt.html#xpath-return-values
#
# :param select_all: True to get all matches
# """
# from defusedxml import lxml as dlxml
# import re
#
# if isinstance(xpath_results, list):
# if select_all is False:
# xpath_results = xpath_results[0:1]
# else:
# xpath_results = [xpath_results]
#
# results = []
# for r in xpath_results:
# # namespace declarations
# if isinstance(r, tuple):
# results.append("%s=\"%s\"" % (r[0], r[1]))
# # an element
# elif hasattr(r, 'tag'):
# results.append(
# re.sub(r'\s+', ' ',
# dlxml.tostring(r, method='html', encoding='unicode'))
# )
# else:
# results.append(r)
#
# return u"\n".join(six.text_type(x).strip() for x in results)
. Output only the next line. | return int(text) |
Based on the snippet: <|code_start|> 'content': content,
'lines': content.splitlines(),
'json': LazyJSON(content),
'css': html.css,
'xpath': xml.xpath,
'env': os.environ,
}
RE_NOT_FLOAT = re.compile(r'[^0-9\.]')
def ignore_cast_error(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except (TypeError, ValueError):
logger.warning("Invalid value passed in Jinja transform",
exc_info=True)
return None
return wrapper
@ignore_cast_error
def dollars_filter(number):
sign = '-' if number < 0 else ''
return '{0}${1:,}'.format(sign, abs(number))
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import os
import logging
import json
import functools
import six
from kibitzr.stash import LazyStash
from .html import deep_recursion, SoupOps
from .xpath import parse_html, serialize_xpath_results
from jinja2 import Environment
from jinja2 import TemplateError
from bs4 import BeautifulSoup
and context (classes, functions, sometimes code) from other files:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/transformer/html.py
# @contextlib.contextmanager
# def deep_recursion():
# old_limit = sys.getrecursionlimit()
# try:
# sys.setrecursionlimit(100000)
# yield
# finally:
# sys.setrecursionlimit(old_limit)
#
# class SoupOps(object):
# def __init__(self, selector=None, select_all=False):
# self.selector = selector
# self.select_all = select_all
#
# def tag_selector(self, html):
# with soup(html) as doc:
# element = doc.find(self.selector)
# if element:
# return True, six.text_type(element)
# else:
# logger.warning('Tag not found: %r', self.selector)
# return False, html
#
# def css_selector(self, html):
# with soup(html) as doc:
# try:
# elements = doc.select(self.selector)
# if self.select_all:
# result = u"".join(six.text_type(x)
# for x in elements)
# else:
# result = six.text_type(elements[0])
# return True, result
# except IndexError:
# logger.warning('CSS selector not found: %r', self.selector)
# return False, html
#
# @staticmethod
# def extract_text(html):
# with soup(html) as doc:
# strings = doc.stripped_strings
# return True, u'\n'.join([
# line
# for line in strings
# if line
# ])
#
# @classmethod
# def factory(cls, key, value, conf):
# def transform(content):
# instance = cls(selector=value, select_all=select_all)
# method = handler.__get__(instance, cls)
# return method(content)
# action, _, all_flag = key.partition('-')
# select_all = (all_flag == 'all')
# handler = cls.SHORTCUTS[action]
# return transform
#
# SHORTCUTS = {
# 'tag': tag_selector,
# 'css': css_selector,
# 'text': extract_text,
# }
#
# Path: kibitzr/transformer/xpath.py
# def parse_html(html):
# """
# Returns `html` parsed with lxml.
#
# :param html: Unicode content
# """
# from defusedxml import lxml as dlxml
# from lxml import etree
#
# # lxml requires argument to be bytes
# # see https://github.com/kibitzr/kibitzr/issues/47
# encoded = html.encode('utf-8')
# return dlxml.fromstring(encoded, parser=etree.HTMLParser())
#
# def serialize_xpath_results(xpath_results, select_all):
# """
# Serializes results of xpath evaluation.
#
# :param xpath_results: Results of xpath evaluation.
# See: https://lxml.de/xpathxslt.html#xpath-return-values
#
# :param select_all: True to get all matches
# """
# from defusedxml import lxml as dlxml
# import re
#
# if isinstance(xpath_results, list):
# if select_all is False:
# xpath_results = xpath_results[0:1]
# else:
# xpath_results = [xpath_results]
#
# results = []
# for r in xpath_results:
# # namespace declarations
# if isinstance(r, tuple):
# results.append("%s=\"%s\"" % (r[0], r[1]))
# # an element
# elif hasattr(r, 'tag'):
# results.append(
# re.sub(r'\s+', ' ',
# dlxml.tostring(r, method='html', encoding='unicode'))
# )
# else:
# results.append(r)
#
# return u"\n".join(six.text_type(x).strip() for x in results)
. Output only the next line. | @ignore_cast_error |
Given the code snippet: <|code_start|>
@ignore_cast_error
def dollars_filter(number):
sign = '-' if number < 0 else ''
return '{0}${1:,}'.format(sign, abs(number))
@ignore_cast_error
def int_filter(text):
return int(text)
@ignore_cast_error
def float_filter(text):
return float(RE_NOT_FLOAT.sub('', text))
def text_filter(html):
if isinstance(html, list):
html = "".join(html)
ok, content = SoupOps.extract_text(html)
if ok:
return content
else:
raise RuntimeError("Extract text failed")
class LazyJSON(object):
def __init__(self, content):
<|code_end|>
, generate the next line using the imports in this file:
import re
import os
import logging
import json
import functools
import six
from kibitzr.stash import LazyStash
from .html import deep_recursion, SoupOps
from .xpath import parse_html, serialize_xpath_results
from jinja2 import Environment
from jinja2 import TemplateError
from bs4 import BeautifulSoup
and context (functions, classes, or occasionally code) from other files:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/transformer/html.py
# @contextlib.contextmanager
# def deep_recursion():
# old_limit = sys.getrecursionlimit()
# try:
# sys.setrecursionlimit(100000)
# yield
# finally:
# sys.setrecursionlimit(old_limit)
#
# class SoupOps(object):
# def __init__(self, selector=None, select_all=False):
# self.selector = selector
# self.select_all = select_all
#
# def tag_selector(self, html):
# with soup(html) as doc:
# element = doc.find(self.selector)
# if element:
# return True, six.text_type(element)
# else:
# logger.warning('Tag not found: %r', self.selector)
# return False, html
#
# def css_selector(self, html):
# with soup(html) as doc:
# try:
# elements = doc.select(self.selector)
# if self.select_all:
# result = u"".join(six.text_type(x)
# for x in elements)
# else:
# result = six.text_type(elements[0])
# return True, result
# except IndexError:
# logger.warning('CSS selector not found: %r', self.selector)
# return False, html
#
# @staticmethod
# def extract_text(html):
# with soup(html) as doc:
# strings = doc.stripped_strings
# return True, u'\n'.join([
# line
# for line in strings
# if line
# ])
#
# @classmethod
# def factory(cls, key, value, conf):
# def transform(content):
# instance = cls(selector=value, select_all=select_all)
# method = handler.__get__(instance, cls)
# return method(content)
# action, _, all_flag = key.partition('-')
# select_all = (all_flag == 'all')
# handler = cls.SHORTCUTS[action]
# return transform
#
# SHORTCUTS = {
# 'tag': tag_selector,
# 'css': css_selector,
# 'text': extract_text,
# }
#
# Path: kibitzr/transformer/xpath.py
# def parse_html(html):
# """
# Returns `html` parsed with lxml.
#
# :param html: Unicode content
# """
# from defusedxml import lxml as dlxml
# from lxml import etree
#
# # lxml requires argument to be bytes
# # see https://github.com/kibitzr/kibitzr/issues/47
# encoded = html.encode('utf-8')
# return dlxml.fromstring(encoded, parser=etree.HTMLParser())
#
# def serialize_xpath_results(xpath_results, select_all):
# """
# Serializes results of xpath evaluation.
#
# :param xpath_results: Results of xpath evaluation.
# See: https://lxml.de/xpathxslt.html#xpath-return-values
#
# :param select_all: True to get all matches
# """
# from defusedxml import lxml as dlxml
# import re
#
# if isinstance(xpath_results, list):
# if select_all is False:
# xpath_results = xpath_results[0:1]
# else:
# xpath_results = [xpath_results]
#
# results = []
# for r in xpath_results:
# # namespace declarations
# if isinstance(r, tuple):
# results.append("%s=\"%s\"" % (r[0], r[1]))
# # an element
# elif hasattr(r, 'tag'):
# results.append(
# re.sub(r'\s+', ' ',
# dlxml.tostring(r, method='html', encoding='unicode'))
# )
# else:
# results.append(r)
#
# return u"\n".join(six.text_type(x).strip() for x in results)
. Output only the next line. | self.text = content |
Using the snippet: <|code_start|>
RE_NOT_FLOAT = re.compile(r'[^0-9\.]')
def ignore_cast_error(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except (TypeError, ValueError):
logger.warning("Invalid value passed in Jinja transform",
exc_info=True)
return None
return wrapper
@ignore_cast_error
def dollars_filter(number):
sign = '-' if number < 0 else ''
return '{0}${1:,}'.format(sign, abs(number))
@ignore_cast_error
def int_filter(text):
return int(text)
@ignore_cast_error
def float_filter(text):
<|code_end|>
, determine the next line of code. You have imports:
import re
import os
import logging
import json
import functools
import six
from kibitzr.stash import LazyStash
from .html import deep_recursion, SoupOps
from .xpath import parse_html, serialize_xpath_results
from jinja2 import Environment
from jinja2 import TemplateError
from bs4 import BeautifulSoup
and context (class names, function names, or code) available:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/transformer/html.py
# @contextlib.contextmanager
# def deep_recursion():
# old_limit = sys.getrecursionlimit()
# try:
# sys.setrecursionlimit(100000)
# yield
# finally:
# sys.setrecursionlimit(old_limit)
#
# class SoupOps(object):
# def __init__(self, selector=None, select_all=False):
# self.selector = selector
# self.select_all = select_all
#
# def tag_selector(self, html):
# with soup(html) as doc:
# element = doc.find(self.selector)
# if element:
# return True, six.text_type(element)
# else:
# logger.warning('Tag not found: %r', self.selector)
# return False, html
#
# def css_selector(self, html):
# with soup(html) as doc:
# try:
# elements = doc.select(self.selector)
# if self.select_all:
# result = u"".join(six.text_type(x)
# for x in elements)
# else:
# result = six.text_type(elements[0])
# return True, result
# except IndexError:
# logger.warning('CSS selector not found: %r', self.selector)
# return False, html
#
# @staticmethod
# def extract_text(html):
# with soup(html) as doc:
# strings = doc.stripped_strings
# return True, u'\n'.join([
# line
# for line in strings
# if line
# ])
#
# @classmethod
# def factory(cls, key, value, conf):
# def transform(content):
# instance = cls(selector=value, select_all=select_all)
# method = handler.__get__(instance, cls)
# return method(content)
# action, _, all_flag = key.partition('-')
# select_all = (all_flag == 'all')
# handler = cls.SHORTCUTS[action]
# return transform
#
# SHORTCUTS = {
# 'tag': tag_selector,
# 'css': css_selector,
# 'text': extract_text,
# }
#
# Path: kibitzr/transformer/xpath.py
# def parse_html(html):
# """
# Returns `html` parsed with lxml.
#
# :param html: Unicode content
# """
# from defusedxml import lxml as dlxml
# from lxml import etree
#
# # lxml requires argument to be bytes
# # see https://github.com/kibitzr/kibitzr/issues/47
# encoded = html.encode('utf-8')
# return dlxml.fromstring(encoded, parser=etree.HTMLParser())
#
# def serialize_xpath_results(xpath_results, select_all):
# """
# Serializes results of xpath evaluation.
#
# :param xpath_results: Results of xpath evaluation.
# See: https://lxml.de/xpathxslt.html#xpath-return-values
#
# :param select_all: True to get all matches
# """
# from defusedxml import lxml as dlxml
# import re
#
# if isinstance(xpath_results, list):
# if select_all is False:
# xpath_results = xpath_results[0:1]
# else:
# xpath_results = [xpath_results]
#
# results = []
# for r in xpath_results:
# # namespace declarations
# if isinstance(r, tuple):
# results.append("%s=\"%s\"" % (r[0], r[1]))
# # an element
# elif hasattr(r, 'tag'):
# results.append(
# re.sub(r'\s+', ' ',
# dlxml.tostring(r, method='html', encoding='unicode'))
# )
# else:
# results.append(r)
#
# return u"\n".join(six.text_type(x).strip() for x in results)
. Output only the next line. | return float(RE_NOT_FLOAT.sub('', text)) |
Given the following code snippet before the placeholder: <|code_start|>
logger = logging.getLogger(__name__)
class JinjaTransform(object):
def __init__(self, code, conf):
environment = Environment()
environment.filters['text'] = text_filter
environment.filters['int'] = int_filter
environment.filters['float'] = float_filter
environment.filters['dollars'] = dollars_filter
self.template = environment.from_string(code)
self.conf = conf
def render(self, content, context=None):
try:
return True, self.template.render(context or self.context(content))
except TemplateError:
logger.warning("Jinja render failed", exc_info=True)
<|code_end|>
, predict the next line using imports from the current file:
import re
import os
import logging
import json
import functools
import six
from kibitzr.stash import LazyStash
from .html import deep_recursion, SoupOps
from .xpath import parse_html, serialize_xpath_results
from jinja2 import Environment
from jinja2 import TemplateError
from bs4 import BeautifulSoup
and context including class names, function names, and sometimes code from other files:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/transformer/html.py
# @contextlib.contextmanager
# def deep_recursion():
# old_limit = sys.getrecursionlimit()
# try:
# sys.setrecursionlimit(100000)
# yield
# finally:
# sys.setrecursionlimit(old_limit)
#
# class SoupOps(object):
# def __init__(self, selector=None, select_all=False):
# self.selector = selector
# self.select_all = select_all
#
# def tag_selector(self, html):
# with soup(html) as doc:
# element = doc.find(self.selector)
# if element:
# return True, six.text_type(element)
# else:
# logger.warning('Tag not found: %r', self.selector)
# return False, html
#
# def css_selector(self, html):
# with soup(html) as doc:
# try:
# elements = doc.select(self.selector)
# if self.select_all:
# result = u"".join(six.text_type(x)
# for x in elements)
# else:
# result = six.text_type(elements[0])
# return True, result
# except IndexError:
# logger.warning('CSS selector not found: %r', self.selector)
# return False, html
#
# @staticmethod
# def extract_text(html):
# with soup(html) as doc:
# strings = doc.stripped_strings
# return True, u'\n'.join([
# line
# for line in strings
# if line
# ])
#
# @classmethod
# def factory(cls, key, value, conf):
# def transform(content):
# instance = cls(selector=value, select_all=select_all)
# method = handler.__get__(instance, cls)
# return method(content)
# action, _, all_flag = key.partition('-')
# select_all = (all_flag == 'all')
# handler = cls.SHORTCUTS[action]
# return transform
#
# SHORTCUTS = {
# 'tag': tag_selector,
# 'css': css_selector,
# 'text': extract_text,
# }
#
# Path: kibitzr/transformer/xpath.py
# def parse_html(html):
# """
# Returns `html` parsed with lxml.
#
# :param html: Unicode content
# """
# from defusedxml import lxml as dlxml
# from lxml import etree
#
# # lxml requires argument to be bytes
# # see https://github.com/kibitzr/kibitzr/issues/47
# encoded = html.encode('utf-8')
# return dlxml.fromstring(encoded, parser=etree.HTMLParser())
#
# def serialize_xpath_results(xpath_results, select_all):
# """
# Serializes results of xpath evaluation.
#
# :param xpath_results: Results of xpath evaluation.
# See: https://lxml.de/xpathxslt.html#xpath-return-values
#
# :param select_all: True to get all matches
# """
# from defusedxml import lxml as dlxml
# import re
#
# if isinstance(xpath_results, list):
# if select_all is False:
# xpath_results = xpath_results[0:1]
# else:
# xpath_results = [xpath_results]
#
# results = []
# for r in xpath_results:
# # namespace declarations
# if isinstance(r, tuple):
# results.append("%s=\"%s\"" % (r[0], r[1]))
# # an element
# elif hasattr(r, 'tag'):
# results.append(
# re.sub(r'\s+', ' ',
# dlxml.tostring(r, method='html', encoding='unicode'))
# )
# else:
# results.append(r)
#
# return u"\n".join(six.text_type(x).strip() for x in results)
. Output only the next line. | return False, None |
Given the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
NAME = 'python'
class PythonNotify(object):
def __init__(self, conf, value):
<|code_end|>
, generate the next line using the imports in this file:
import logging
from kibitzr.stash import LazyStash
from ..conf import settings
and context (functions, classes, or occasionally code) from other files:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
. Output only the next line. | self.code = value |
Given snippet: <|code_start|>
logger = logging.getLogger(__name__)
NAME = 'python'
class PythonNotify(object):
def __init__(self, conf, value):
self.code = value
self.context = {
'conf': conf,
'creds': settings().creds,
}
def __call__(self, report):
context = dict(
self.context,
text=report, # legacy
content=report,
stash=LazyStash(),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from kibitzr.stash import LazyStash
from ..conf import settings
and context:
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
#
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
which might include code, classes, or functions. Output only the next line. | ) |
Given the code snippet: <|code_start|>
class StashNotify(Stash):
def __init__(self, conf, value):
super(StashNotify, self).__init__()
self.conf = conf
self.data = value
def render(self, report):
context = None
new_values = {}
for key, code in self.data.items():
transform = JinjaTransform(code, self.conf)
if context is None:
context = transform.context(report)
<|code_end|>
, generate the next line using the imports in this file:
from kibitzr.stash import Stash
from kibitzr.transformer.jinja_transform import JinjaTransform
and context (functions, classes, or occasionally code) from other files:
# Path: kibitzr/stash.py
# class Stash(object):
#
# FILENAME = 'stash.db'
#
# @contextlib.contextmanager
# def open(self):
# import shelve
# with contextlib.closing(shelve.open(self.FILENAME)) as db:
# yield db
#
# def read(self):
# with self.open() as db:
# return dict(db)
#
# def write(self, data):
# with self.open() as db:
# for key, value in data.items():
# db[key] = value
#
# @classmethod
# def print_content(cls):
# for key, value in cls().read().items():
# print("{0}: {1}".format(key, value))
#
# Path: kibitzr/transformer/jinja_transform.py
# class JinjaTransform(object):
#
# def __init__(self, code, conf):
# from jinja2 import Environment
# environment = Environment()
# environment.filters['text'] = text_filter
# environment.filters['int'] = int_filter
# environment.filters['float'] = float_filter
# environment.filters['dollars'] = dollars_filter
# self.template = environment.from_string(code)
# self.conf = conf
#
# def render(self, content, context=None):
# from jinja2 import TemplateError
# try:
# return True, self.template.render(context or self.context(content))
# except TemplateError:
# logger.warning("Jinja render failed", exc_info=True)
# return False, None
# __call__ = render
#
# def context(self, content):
# html = LazyHTML(content)
# xml = LazyXML(content)
# return {
# 'conf': self.conf,
# 'stash': LazyStash(),
# 'content': content,
# 'lines': content.splitlines(),
# 'json': LazyJSON(content),
# 'css': html.css,
# 'xpath': xml.xpath,
# 'env': os.environ,
# }
. Output only the next line. | ok, value = transform.render(report, context) |
Here is a snippet: <|code_start|>
class StashNotify(Stash):
def __init__(self, conf, value):
super(StashNotify, self).__init__()
self.conf = conf
self.data = value
def render(self, report):
context = None
new_values = {}
for key, code in self.data.items():
transform = JinjaTransform(code, self.conf)
if context is None:
context = transform.context(report)
ok, value = transform.render(report, context)
if ok:
new_values[key] = value
else:
return False, {}
return True, new_values
def save_report(self, report):
ok, new_values = self.render(report)
if ok:
<|code_end|>
. Write the next line using the current file imports:
from kibitzr.stash import Stash
from kibitzr.transformer.jinja_transform import JinjaTransform
and context from other files:
# Path: kibitzr/stash.py
# class Stash(object):
#
# FILENAME = 'stash.db'
#
# @contextlib.contextmanager
# def open(self):
# import shelve
# with contextlib.closing(shelve.open(self.FILENAME)) as db:
# yield db
#
# def read(self):
# with self.open() as db:
# return dict(db)
#
# def write(self, data):
# with self.open() as db:
# for key, value in data.items():
# db[key] = value
#
# @classmethod
# def print_content(cls):
# for key, value in cls().read().items():
# print("{0}: {1}".format(key, value))
#
# Path: kibitzr/transformer/jinja_transform.py
# class JinjaTransform(object):
#
# def __init__(self, code, conf):
# from jinja2 import Environment
# environment = Environment()
# environment.filters['text'] = text_filter
# environment.filters['int'] = int_filter
# environment.filters['float'] = float_filter
# environment.filters['dollars'] = dollars_filter
# self.template = environment.from_string(code)
# self.conf = conf
#
# def render(self, content, context=None):
# from jinja2 import TemplateError
# try:
# return True, self.template.render(context or self.context(content))
# except TemplateError:
# logger.warning("Jinja render failed", exc_info=True)
# return False, None
# __call__ = render
#
# def context(self, content):
# html = LazyHTML(content)
# xml = LazyXML(content)
# return {
# 'conf': self.conf,
# 'stash': LazyStash(),
# 'content': content,
# 'lines': content.splitlines(),
# 'json': LazyJSON(content),
# 'css': html.css,
# 'xpath': xml.xpath,
# 'env': os.environ,
# }
, which may include functions, classes, or code. Output only the next line. | self.write(new_values) |
Continue the code snippet: <|code_start|>
def test_fill_form_sample(target):
conf = {
'name': 'Test page',
'url': "http://{0}:{1}/form.html".format(*target),
'form': [
{'id': 'name', 'value': '{{ "name" | sort | join("") }}'},
<|code_end|>
. Use current file imports:
from kibitzr.checker import Checker
and context (classes, functions, or code) from other files:
# Path: kibitzr/checker.py
# class Checker(object):
# def __init__(self, conf):
# self.conf = conf
# self.fetch = fetcher_factory(conf)
# self.transform = transform_factory(self.conf)
# self.notify = notify_factory(self.conf)
#
# @classmethod
# def create_from_settings(cls, checks, names=None):
# if names:
# selected_checks = [
# conf
# for conf in checks
# if conf['name'] in names
# ]
# selected_names = [conf['name'] for conf in selected_checks]
# if len(selected_checks) < len(checks):
# logger.info("Filtered list of checks to: %r",
# ", ".join(sorted(selected_names)))
# checks = selected_checks
# if len(selected_names) < len(names):
# logger.error(
# "Following check(s) were not found: %r",
# ", ".join(sorted(set(names).difference(selected_names)))
# )
# return [cls(conf)
# for conf in checks]
#
# def check(self):
# ok, content = self.fetch()
# ok, report = self.transform(ok, content)
# self.notify(report=report)
# return ok, report
. Output only the next line. | {'css': '#pass', 'creds': 'pass'} |
Given the following code snippet before the placeholder: <|code_start|>
class SettingsMock(ReloadableSettings):
def __init__(self):
self.checks = []
self.notifiers = {}
self.creds = {'pass': 'password'}
@classmethod
def instance(cls):
ReloadableSettings._instance = cls()
return ReloadableSettings._instance
@staticmethod
def dispose():
ReloadableSettings._instance = None
@contextlib.contextmanager
<|code_end|>
, predict the next line using imports from the current file:
import contextlib
import tempfile
from kibitzr.conf import ReloadableSettings
from kibitzr.stash import Stash
from .compat import mock
and context including class names, function names, and sometimes code from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# _instance = None
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
#
# def __init__(self, config_dir):
# self.filename = os.path.join(config_dir, self.CONFIG_FILENAME)
# self.checks = None
# self.creds = CompositeCreds(config_dir)
# self.parser = SettingsParser()
# self.reread()
#
# @classmethod
# def detect_config_dir(cls):
# candidates = [
# (directory, os.path.join(directory, cls.CONFIG_FILENAME))
# for directory in map(os.path.expanduser, cls.CONFIG_DIRS)
# ]
# for directory, file_path in candidates:
# if os.path.exists(file_path):
# return directory
# raise ConfigurationError(
# "kibitzr.yml not found in following locations: %s"
# % ", ".join([x[1] for x in candidates])
# )
#
# @classmethod
# def instance(cls):
# if cls._instance is None:
# config_dir = cls.detect_config_dir()
# cls._instance = cls(config_dir)
# return cls._instance
#
# def reread(self):
# """
# Read configuration file and substitute references into checks conf
# """
# logger.debug("Loading settings from %s",
# os.path.abspath(self.filename))
# conf = self.read_conf()
# changed = self.creds.reread()
# checks = self.parser.parse_checks(conf)
# if self.checks != checks:
# self.checks = checks
# return True
# else:
# return changed
#
# def read_conf(self):
# """
# Read and parse configuration file
# """
# with self.open_conf() as fp:
# return yaml.safe_load(fp)
#
# @contextlib.contextmanager
# def open_conf(self):
# with open(self.filename) as fp:
# yield fp
#
# Path: kibitzr/stash.py
# class Stash(object):
#
# FILENAME = 'stash.db'
#
# @contextlib.contextmanager
# def open(self):
# import shelve
# with contextlib.closing(shelve.open(self.FILENAME)) as db:
# yield db
#
# def read(self):
# with self.open() as db:
# return dict(db)
#
# def write(self, data):
# with self.open() as db:
# for key, value in data.items():
# db[key] = value
#
# @classmethod
# def print_content(cls):
# for key, value in cls().read().items():
# print("{0}: {1}".format(key, value))
#
# Path: tests/compat.py
. Output only the next line. | def stash_mock(): |
Continue the code snippet: <|code_start|>
class SettingsMock(ReloadableSettings):
def __init__(self):
self.checks = []
<|code_end|>
. Use current file imports:
import contextlib
import tempfile
from kibitzr.conf import ReloadableSettings
from kibitzr.stash import Stash
from .compat import mock
and context (classes, functions, or code) from other files:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# _instance = None
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
#
# def __init__(self, config_dir):
# self.filename = os.path.join(config_dir, self.CONFIG_FILENAME)
# self.checks = None
# self.creds = CompositeCreds(config_dir)
# self.parser = SettingsParser()
# self.reread()
#
# @classmethod
# def detect_config_dir(cls):
# candidates = [
# (directory, os.path.join(directory, cls.CONFIG_FILENAME))
# for directory in map(os.path.expanduser, cls.CONFIG_DIRS)
# ]
# for directory, file_path in candidates:
# if os.path.exists(file_path):
# return directory
# raise ConfigurationError(
# "kibitzr.yml not found in following locations: %s"
# % ", ".join([x[1] for x in candidates])
# )
#
# @classmethod
# def instance(cls):
# if cls._instance is None:
# config_dir = cls.detect_config_dir()
# cls._instance = cls(config_dir)
# return cls._instance
#
# def reread(self):
# """
# Read configuration file and substitute references into checks conf
# """
# logger.debug("Loading settings from %s",
# os.path.abspath(self.filename))
# conf = self.read_conf()
# changed = self.creds.reread()
# checks = self.parser.parse_checks(conf)
# if self.checks != checks:
# self.checks = checks
# return True
# else:
# return changed
#
# def read_conf(self):
# """
# Read and parse configuration file
# """
# with self.open_conf() as fp:
# return yaml.safe_load(fp)
#
# @contextlib.contextmanager
# def open_conf(self):
# with open(self.filename) as fp:
# yield fp
#
# Path: kibitzr/stash.py
# class Stash(object):
#
# FILENAME = 'stash.db'
#
# @contextlib.contextmanager
# def open(self):
# import shelve
# with contextlib.closing(shelve.open(self.FILENAME)) as db:
# yield db
#
# def read(self):
# with self.open() as db:
# return dict(db)
#
# def write(self, data):
# with self.open() as db:
# for key, value in data.items():
# db[key] = value
#
# @classmethod
# def print_content(cls):
# for key, value in cls().read().items():
# print("{0}: {1}".format(key, value))
#
# Path: tests/compat.py
. Output only the next line. | self.notifiers = {} |
Given snippet: <|code_start|>
class SettingsMock(ReloadableSettings):
def __init__(self):
self.checks = []
self.notifiers = {}
self.creds = {'pass': 'password'}
@classmethod
def instance(cls):
ReloadableSettings._instance = cls()
return ReloadableSettings._instance
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import contextlib
import tempfile
from kibitzr.conf import ReloadableSettings
from kibitzr.stash import Stash
from .compat import mock
and context:
# Path: kibitzr/conf.py
# class ReloadableSettings(object):
# _instance = None
# CONFIG_DIRS = (
# '',
# '~/.config/kibitzr/',
# '~/',
# )
# CONFIG_FILENAME = 'kibitzr.yml'
# RE_PUNCTUATION = re.compile(r'\W+')
# UNNAMED_PATTERN = 'Unnamed check {0}'
#
# def __init__(self, config_dir):
# self.filename = os.path.join(config_dir, self.CONFIG_FILENAME)
# self.checks = None
# self.creds = CompositeCreds(config_dir)
# self.parser = SettingsParser()
# self.reread()
#
# @classmethod
# def detect_config_dir(cls):
# candidates = [
# (directory, os.path.join(directory, cls.CONFIG_FILENAME))
# for directory in map(os.path.expanduser, cls.CONFIG_DIRS)
# ]
# for directory, file_path in candidates:
# if os.path.exists(file_path):
# return directory
# raise ConfigurationError(
# "kibitzr.yml not found in following locations: %s"
# % ", ".join([x[1] for x in candidates])
# )
#
# @classmethod
# def instance(cls):
# if cls._instance is None:
# config_dir = cls.detect_config_dir()
# cls._instance = cls(config_dir)
# return cls._instance
#
# def reread(self):
# """
# Read configuration file and substitute references into checks conf
# """
# logger.debug("Loading settings from %s",
# os.path.abspath(self.filename))
# conf = self.read_conf()
# changed = self.creds.reread()
# checks = self.parser.parse_checks(conf)
# if self.checks != checks:
# self.checks = checks
# return True
# else:
# return changed
#
# def read_conf(self):
# """
# Read and parse configuration file
# """
# with self.open_conf() as fp:
# return yaml.safe_load(fp)
#
# @contextlib.contextmanager
# def open_conf(self):
# with open(self.filename) as fp:
# yield fp
#
# Path: kibitzr/stash.py
# class Stash(object):
#
# FILENAME = 'stash.db'
#
# @contextlib.contextmanager
# def open(self):
# import shelve
# with contextlib.closing(shelve.open(self.FILENAME)) as db:
# yield db
#
# def read(self):
# with self.open() as db:
# return dict(db)
#
# def write(self, data):
# with self.open() as db:
# for key, value in data.items():
# db[key] = value
#
# @classmethod
# def print_content(cls):
# for key, value in cls().read().items():
# print("{0}: {1}".format(key, value))
#
# Path: tests/compat.py
which might include code, classes, or functions. Output only the next line. | @staticmethod |
Continue the code snippet: <|code_start|>
def test_fetch_by_python_script():
ok, content = run_script({'python': 'ok, content = True, "hello"'})
assert ok is True
assert content == "hello"
def test_python_script_must_define_content():
with pytest.raises(AssertionError):
run_script({'python': 'dummy'})
def test_python_script_exception_is_reported():
ok, content = run_script({'python': 'content = 1 / 0'})
assert ok is False
assert content.splitlines()[-1].startswith("ZeroDivisionError")
def test_ok_is_optional_in_python_script():
ok, content = run_script({'python': 'content = "dummy"'})
assert ok is True
assert content == "dummy"
def test_bash_error_is_returned():
ok, content = run_script('no command not found')
assert ok is False
assert content.split(':', 1)[1].strip() == "line 1: no: command not found"
<|code_end|>
. Use current file imports:
import pytest
from kibitzr.fetcher.script import fetch_by_script
from ...helpers import stash_mock
and context (classes, functions, or code) from other files:
# Path: kibitzr/fetcher/script.py
# def fetch_by_script(conf):
# code = conf['script']
# try:
# python_code = code['python']
# except (KeyError, TypeError):
# # Not a python script
# pass
# else:
# return fetch_by_python(python_code, conf)
# try:
# # Explicit notation:
# bash_script = code['bash']
# except (KeyError, TypeError):
# bash_script = code
# # Pass something to stdin to disable sanity check:
# return execute_bash(
# bash_script,
# conf.get('name', 'dummy'),
# )
#
# Path: tests/helpers.py
# @contextlib.contextmanager
# def stash_mock():
# with tempfile.NamedTemporaryFile() as fp:
# fp.close()
# with mock.patch.object(Stash, 'FILENAME', fp.name):
# yield Stash()
. Output only the next line. | def test_python_script_has_stash(): |
Predict the next line for this snippet: <|code_start|>
def run_script(script):
return fetch_by_script({'script': script})
def test_fetch_by_script_default_is_bash():
ok, content = run_script('echo hello')
assert ok is True
assert content.strip() == "hello"
def test_fetch_by_explicit_bash_script():
ok, content = run_script({'bash': 'echo "hello"'})
assert ok is True
assert content == "hello\n"
def test_fetch_by_python_script():
ok, content = run_script({'python': 'ok, content = True, "hello"'})
assert ok is True
assert content == "hello"
def test_python_script_must_define_content():
with pytest.raises(AssertionError):
<|code_end|>
with the help of current file imports:
import pytest
from kibitzr.fetcher.script import fetch_by_script
from ...helpers import stash_mock
and context from other files:
# Path: kibitzr/fetcher/script.py
# def fetch_by_script(conf):
# code = conf['script']
# try:
# python_code = code['python']
# except (KeyError, TypeError):
# # Not a python script
# pass
# else:
# return fetch_by_python(python_code, conf)
# try:
# # Explicit notation:
# bash_script = code['bash']
# except (KeyError, TypeError):
# bash_script = code
# # Pass something to stdin to disable sanity check:
# return execute_bash(
# bash_script,
# conf.get('name', 'dummy'),
# )
#
# Path: tests/helpers.py
# @contextlib.contextmanager
# def stash_mock():
# with tempfile.NamedTemporaryFile() as fp:
# fp.close()
# with mock.patch.object(Stash, 'FILENAME', fp.name):
# yield Stash()
, which may contain function names, class names, or code. Output only the next line. | run_script({'python': 'dummy'}) |
Given the following code snippet before the placeholder: <|code_start|>
logger = logging.getLogger(__name__)
PYTHON_ERROR = "script.python must set global variables ok and content"
def fetch_by_script(conf):
code = conf['script']
try:
python_code = code['python']
except (KeyError, TypeError):
# Not a python script
pass
else:
return fetch_by_python(python_code, conf)
try:
# Explicit notation:
bash_script = code['bash']
except (KeyError, TypeError):
bash_script = code
# Pass something to stdin to disable sanity check:
return execute_bash(
bash_script,
conf.get('name', 'dummy'),
)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import traceback
from ..conf import settings
from ..bash import execute_bash
from ..stash import LazyStash
and context including class names, function names, and sometimes code from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/bash.py
# def execute_bash(code, stdin=None):
# if os.name == 'nt':
# executor = WindowsExecutor
# else:
# executor = BashExecutor
# return executor(code).execute(stdin)
#
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
. Output only the next line. | def fetch_by_python(code, conf): |
Here is a snippet: <|code_start|>
logger = logging.getLogger(__name__)
PYTHON_ERROR = "script.python must set global variables ok and content"
def fetch_by_script(conf):
code = conf['script']
try:
python_code = code['python']
except (KeyError, TypeError):
# Not a python script
pass
else:
return fetch_by_python(python_code, conf)
try:
# Explicit notation:
bash_script = code['bash']
except (KeyError, TypeError):
bash_script = code
# Pass something to stdin to disable sanity check:
return execute_bash(
bash_script,
conf.get('name', 'dummy'),
)
def fetch_by_python(code, conf):
logger.info("Fetch using Python script")
logger.debug(code)
<|code_end|>
. Write the next line using the current file imports:
import logging
import traceback
from ..conf import settings
from ..bash import execute_bash
from ..stash import LazyStash
and context from other files:
# Path: kibitzr/conf.py
# def settings():
# """
# Returns singleton instance of settings
# """
# return ReloadableSettings.instance()
#
# Path: kibitzr/bash.py
# def execute_bash(code, stdin=None):
# if os.name == 'nt':
# executor = WindowsExecutor
# else:
# executor = BashExecutor
# return executor(code).execute(stdin)
#
# Path: kibitzr/stash.py
# class LazyStash(Stash):
# def __init__(self):
# self._stashobj = None
#
# @property
# def _stash(self):
# if self._stashobj is None:
# self._stashobj = self.read()
# return self._stashobj
#
# def __getitem__(self, key):
# return self._stash[key]
#
# def get(self, key, default=None):
# try:
# return self._stash[key]
# except KeyError:
# return default
, which may include functions, classes, or code. Output only the next line. | assert 'content' in code, PYTHON_ERROR |
Given the following code snippet before the placeholder: <|code_start|>
## Config
CONFIG_OPTIONS = utilities.load_config()
## Logging
logger = utilities.initialize_logging(logging.getLogger(__name__))
class ModuleEntry:
def __init__(self, cls: Module, *init_args, **init_kwargs):
self.module = sys.modules[cls.__module__]
self.cls = cls
self.name = cls.__name__
self.is_cog = issubclass(cls, commands.Cog)
self.args = init_args
self.kwargs = init_kwargs
self.dependencies = init_kwargs.get('dependencies', [])
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import logging
import importlib
from collections import OrderedDict
from pathlib import Path
from functools import reduce
from common import utilities
from common.exceptions import ModuleLoadException
from common.module.module import Module
from .dependency_graph import DependencyGraph
from .module_initialization_container import ModuleInitializationContainer
from discord.ext import commands
and context including class names, function names, and sometimes code from other files:
# Path: code/common/module/dependency_graph.py
# class DependencyGraph:
# def __init__(self):
# self.roots: list = [] # list of (1 or more) root DependencyNodes that form a dependency chain
# self._node_map: dict = {} # dictionary of class names to nodes that've been inserted into the graph
# self._orphaned_node_map: dict = {} # dictionary of class names (that haven't been inserted into the graph) to list of nodes that require that non-existant class
#
# ## Methods
#
# def insert(self, cls, dependencies = List[Module]) -> DependencyNode:
# class_name = cls.__name__
#
# ## Don't insert duplicates
# if (class_name in self._node_map):
# logger.warn('Unable to insert {}, as it\'s already been added.'.format(class_name))
# return
#
# ## Build initial node & update mappings
# node = DependencyNode(cls)
# self._node_map[class_name] = node
#
# ## Handle any orphaned children that depend on this class
# if (class_name in self._orphaned_node_map):
# orphaned_children = self._orphaned_node_map[class_name]
#
# for child in orphaned_children:
# node.children.append(child)
# child.parents.append(node)
#
# del self._orphaned_node_map[class_name]
#
# ## Process the dependencies by searching for existing nodes, otherwise populate the orphaned child map
# dependency: Module
# for dependency in dependencies:
# dependency_name = dependency.__name__
#
# if (dependency_name in self._node_map):
# dependency_node = self._node_map[dependency_name]
#
# node.parents.append(dependency_node)
# dependency_node.children.append(node)
# else:
# if (dependency_name in self._orphaned_node_map):
# self._orphaned_node_map[dependency_name].append(node)
# else:
# self._orphaned_node_map[dependency_name] = [node]
#
# ## Add it to the list of root nodes
# if (len(node.parents) == 0 and len(dependencies) == 0):
# self.roots.append(node)
#
# return node
#
#
# def set_graph_loaded_state(self, state: bool):
# for node in self._node_map.values():
# node.loaded = state
#
# Path: code/common/module/module_initialization_container.py
# class ModuleInitializationContainer:
# def __init__(self, cls, *init_args, **init_kwargs):
# if(not isclass(cls)):
# raise RuntimeError("Provided class parameter '{}' isn't actually a class.".format(cls))
#
# self.cls = cls
# self.is_cog = issubclass(cls, commands.Cog)
# self.init_args = init_args
# self.init_kwargs = init_kwargs
. Output only the next line. | if ('dependencies' in init_kwargs): |
Predict the next line for this snippet: <|code_start|>
## Config
CONFIG_OPTIONS = utilities.load_config()
## Logging
logger = utilities.initialize_logging(logging.getLogger(__name__))
class ModuleEntry:
def __init__(self, cls: Module, *init_args, **init_kwargs):
self.module = sys.modules[cls.__module__]
self.cls = cls
<|code_end|>
with the help of current file imports:
import os
import sys
import logging
import importlib
from collections import OrderedDict
from pathlib import Path
from functools import reduce
from common import utilities
from common.exceptions import ModuleLoadException
from common.module.module import Module
from .dependency_graph import DependencyGraph
from .module_initialization_container import ModuleInitializationContainer
from discord.ext import commands
and context from other files:
# Path: code/common/module/dependency_graph.py
# class DependencyGraph:
# def __init__(self):
# self.roots: list = [] # list of (1 or more) root DependencyNodes that form a dependency chain
# self._node_map: dict = {} # dictionary of class names to nodes that've been inserted into the graph
# self._orphaned_node_map: dict = {} # dictionary of class names (that haven't been inserted into the graph) to list of nodes that require that non-existant class
#
# ## Methods
#
# def insert(self, cls, dependencies = List[Module]) -> DependencyNode:
# class_name = cls.__name__
#
# ## Don't insert duplicates
# if (class_name in self._node_map):
# logger.warn('Unable to insert {}, as it\'s already been added.'.format(class_name))
# return
#
# ## Build initial node & update mappings
# node = DependencyNode(cls)
# self._node_map[class_name] = node
#
# ## Handle any orphaned children that depend on this class
# if (class_name in self._orphaned_node_map):
# orphaned_children = self._orphaned_node_map[class_name]
#
# for child in orphaned_children:
# node.children.append(child)
# child.parents.append(node)
#
# del self._orphaned_node_map[class_name]
#
# ## Process the dependencies by searching for existing nodes, otherwise populate the orphaned child map
# dependency: Module
# for dependency in dependencies:
# dependency_name = dependency.__name__
#
# if (dependency_name in self._node_map):
# dependency_node = self._node_map[dependency_name]
#
# node.parents.append(dependency_node)
# dependency_node.children.append(node)
# else:
# if (dependency_name in self._orphaned_node_map):
# self._orphaned_node_map[dependency_name].append(node)
# else:
# self._orphaned_node_map[dependency_name] = [node]
#
# ## Add it to the list of root nodes
# if (len(node.parents) == 0 and len(dependencies) == 0):
# self.roots.append(node)
#
# return node
#
#
# def set_graph_loaded_state(self, state: bool):
# for node in self._node_map.values():
# node.loaded = state
#
# Path: code/common/module/module_initialization_container.py
# class ModuleInitializationContainer:
# def __init__(self, cls, *init_args, **init_kwargs):
# if(not isclass(cls)):
# raise RuntimeError("Provided class parameter '{}' isn't actually a class.".format(cls))
#
# self.cls = cls
# self.is_cog = issubclass(cls, commands.Cog)
# self.init_args = init_args
# self.init_kwargs = init_kwargs
, which may contain function names, class names, or code. Output only the next line. | self.name = cls.__name__ |
Based on the snippet: <|code_start|>
## Config
CONFIG_OPTIONS = utilities.load_config()
## Logging
logger = utilities.initialize_logging(logging.getLogger(__name__))
class DetailedItem(CommandItem):
def __init__(self, discord_context, query, command, is_valid):
self.discord_context = discord_context
author = self.discord_context.message.author
channel = self.discord_context.message.channel
guild = self.discord_context.message.guild
self.user_id = int(author.id)
self.user_name = "{}#{}".format(author.name, author.discriminator)
self.timestamp = int(self.discord_context.message.created_at.timestamp() * 1000) # float to milliseconds timestamp
<|code_end|>
, predict the immediate next line with the help of imports:
import base64
import logging
from typing import Dict
from .anonymous_item import AnonymousItem
from .command_item import CommandItem
from common import utilities
and context (classes, functions, sometimes code) from other files:
# Path: code/common/database/anonymous_item.py
# class AnonymousItem(CommandItem):
# def __init__(self, discord_context, command, query, is_valid):
# self.timestamp = int(discord_context.message.created_at.timestamp() * 1000)
# self.command = command
# self.query = query
# self.is_valid = is_valid
#
# self.primary_key_name = CONFIG_OPTIONS.get("boto_primary_key", "QueryId")
# self.primary_key = self.build_primary_key()
#
# ## Methods
#
# def to_json(self) -> Dict:
# return {
# 'timestamp': int(self.timestamp),
# 'command': str(self.command),
# 'query': str(self.query),
# 'is_valid': str(self.is_valid),
# self.primary_key_name: str(self.primary_key),
# }
#
#
# def build_primary_key(self) -> str:
# ## Use a UUID because we can't really guarantee that there won't be collisions with the existing data
# return str(uuid.uuid4())
#
# Path: code/common/database/command_item.py
# class CommandItem(metaclass=ABCMeta):
# @abstractmethod
# def to_json(self) -> Dict:
# return
#
#
# @abstractmethod
# def build_primary_key(self) -> str:
# return
. Output only the next line. | self.channel_id = channel.id |
Given the following code snippet before the placeholder: <|code_start|> self.user_id = int(author.id)
self.user_name = "{}#{}".format(author.name, author.discriminator)
self.timestamp = int(self.discord_context.message.created_at.timestamp() * 1000) # float to milliseconds timestamp
self.channel_id = channel.id
self.channel_name = channel.name
self.server_id = guild.id
self.server_name = guild.name
self.query = query
self.command = command
self.is_valid = is_valid
## Milliseconds timestamp to seconds, as AWS TTL only works in seconds increments. Defaults to a year from the timestamp
self.expires_on = (self.timestamp / 1000) + CONFIG_OPTIONS.get("database_detailed_table_ttl_seconds", 31536000)
self.primary_key_name = CONFIG_OPTIONS.get("boto_primary_key", "QueryId")
self.primary_key = self.build_primary_key()
## Methods
def to_json(self) -> Dict:
return {
'user_id': int(self.user_id),
'user_name': str(self.user_name),
'timestamp': int(self.timestamp),
'channel_id': int(self.channel_id),
'channel_name': str(self.channel_name),
'server_id': int(self.server_id),
'server_name': str(self.server_name),
'query': str(self.query),
'command': str(self.command),
<|code_end|>
, predict the next line using imports from the current file:
import base64
import logging
from typing import Dict
from .anonymous_item import AnonymousItem
from .command_item import CommandItem
from common import utilities
and context including class names, function names, and sometimes code from other files:
# Path: code/common/database/anonymous_item.py
# class AnonymousItem(CommandItem):
# def __init__(self, discord_context, command, query, is_valid):
# self.timestamp = int(discord_context.message.created_at.timestamp() * 1000)
# self.command = command
# self.query = query
# self.is_valid = is_valid
#
# self.primary_key_name = CONFIG_OPTIONS.get("boto_primary_key", "QueryId")
# self.primary_key = self.build_primary_key()
#
# ## Methods
#
# def to_json(self) -> Dict:
# return {
# 'timestamp': int(self.timestamp),
# 'command': str(self.command),
# 'query': str(self.query),
# 'is_valid': str(self.is_valid),
# self.primary_key_name: str(self.primary_key),
# }
#
#
# def build_primary_key(self) -> str:
# ## Use a UUID because we can't really guarantee that there won't be collisions with the existing data
# return str(uuid.uuid4())
#
# Path: code/common/database/command_item.py
# class CommandItem(metaclass=ABCMeta):
# @abstractmethod
# def to_json(self) -> Dict:
# return
#
#
# @abstractmethod
# def build_primary_key(self) -> str:
# return
. Output only the next line. | 'is_valid': bool(self.is_valid), |
Given the following code snippet before the placeholder: <|code_start|>
## Config
CONFIG_OPTIONS = utilities.load_config()
## Logging
logger = utilities.initialize_logging(logging.getLogger(__name__))
class AnonymousItem(CommandItem):
def __init__(self, discord_context, command, query, is_valid):
self.timestamp = int(discord_context.message.created_at.timestamp() * 1000)
self.command = command
<|code_end|>
, predict the next line using imports from the current file:
import logging
import uuid
from typing import Dict
from .command_item import CommandItem
from common import utilities
and context including class names, function names, and sometimes code from other files:
# Path: code/common/database/command_item.py
# class CommandItem(metaclass=ABCMeta):
# @abstractmethod
# def to_json(self) -> Dict:
# return
#
#
# @abstractmethod
# def build_primary_key(self) -> str:
# return
. Output only the next line. | self.query = query |
Given the code snippet: <|code_start|>
## Config
CONFIG_OPTIONS = utilities.load_config()
## Logging
logger = utilities.initialize_logging(logging.getLogger(__name__))
class DynamoManager:
def __init__(self):
self.enabled = CONFIG_OPTIONS.get('database_enable', False)
self.credentials_path = CONFIG_OPTIONS.get('database_credentials_file_path')
self.resource = CONFIG_OPTIONS.get('database_resource', 'dynamodb')
<|code_end|>
, generate the next line using the imports in this file:
import os
import logging
import inspect
import boto3
from boto3.dynamodb.conditions import Key
from common import utilities
from .detailed_item import DetailedItem
and context (functions, classes, or occasionally code) from other files:
# Path: code/common/database/detailed_item.py
# class DetailedItem(CommandItem):
# def __init__(self, discord_context, query, command, is_valid):
# self.discord_context = discord_context
# author = self.discord_context.message.author
# channel = self.discord_context.message.channel
# guild = self.discord_context.message.guild
#
# self.user_id = int(author.id)
# self.user_name = "{}#{}".format(author.name, author.discriminator)
# self.timestamp = int(self.discord_context.message.created_at.timestamp() * 1000) # float to milliseconds timestamp
# self.channel_id = channel.id
# self.channel_name = channel.name
# self.server_id = guild.id
# self.server_name = guild.name
#
# self.query = query
# self.command = command
# self.is_valid = is_valid
# ## Milliseconds timestamp to seconds, as AWS TTL only works in seconds increments. Defaults to a year from the timestamp
# self.expires_on = (self.timestamp / 1000) + CONFIG_OPTIONS.get("database_detailed_table_ttl_seconds", 31536000)
#
# self.primary_key_name = CONFIG_OPTIONS.get("boto_primary_key", "QueryId")
# self.primary_key = self.build_primary_key()
#
# ## Methods
#
# def to_json(self) -> Dict:
# return {
# 'user_id': int(self.user_id),
# 'user_name': str(self.user_name),
# 'timestamp': int(self.timestamp),
# 'channel_id': int(self.channel_id),
# 'channel_name': str(self.channel_name),
# 'server_id': int(self.server_id),
# 'server_name': str(self.server_name),
# 'query': str(self.query),
# 'command': str(self.command),
# 'is_valid': bool(self.is_valid),
# 'expires_on': int(self.expires_on),
# self.primary_key_name: str(self.primary_key),
# }
#
#
# def build_primary_key(self) -> str:
# concatenated = "{}{}".format(self.user_id, self.timestamp)
#
# return base64.b64encode(bytes(concatenated, "utf-8")).decode("utf-8")
#
#
# def to_anonymous_item(self) -> AnonymousItem:
# return AnonymousItem(self.discord_context, self.command, self.query, self.is_valid)
. Output only the next line. | self.region_name = CONFIG_OPTIONS.get('database_region_name', 'us-east-2') |
Given the code snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Additional permission under GNU GPL version 3 section 7
#
# If you modify this program, or any covered work, by linking or
# combining it with the OpenSSL project's OpenSSL library (or a
# modified version of that library), containing parts covered by the
# terms of the OpenSSL or SSLeay licenses, We grant you additional
# permission to convey the resulting work. Corresponding Source for a
# non-source form of such a combination shall include the source code
# for the parts of OpenSSL used as well as that of the covered work.
def get_keystore():
return Keystore(_get_keystore())
class Keystore(object):
def __init__(self, store):
self._store = store
self._data = {}
def get(self, id):
return self._data.get(id) or self._store.get(id)
<|code_end|>
, generate the next line using the imports in this file:
from ..cli.keystore import get_keystore as _get_keystore
and context (functions, classes, or occasionally code) from other files:
# Path: yubioath/cli/keystore.py
# def get_keystore():
# return Keystore(KEY_FILE)
. Output only the next line. | def put(self, id, key, remember=False): |
Predict the next line for this snippet: <|code_start|> if not passphrase:
return None
return PBKDF2(passphrase, salt, 16, 1000)
def der_pack(*values):
return b''.join([int2byte(t) + int2byte(len(v)) + v for t, v in zip(
values[0::2], values[1::2])])
def der_read(der_data, expected_t=None):
t = byte2int(der_data[0])
if expected_t is not None and expected_t != t:
raise ValueError('Wrong tag. Expected: %x, got: %x' % (expected_t, t))
l = byte2int(der_data[1])
offs = 2
if l > 0x80:
n_bytes = l - 0x80
l = b2len(der_data[offs:offs + n_bytes])
offs = offs + n_bytes
v = der_data[offs:offs + l]
rest = der_data[offs + l:]
if expected_t is None:
return t, v, rest
return v, rest
def b2len(bs):
l = 0
for b in bs:
<|code_end|>
with the help of current file imports:
from yubioath.yubicommon.compat import int2byte, byte2int
from Crypto.Hash import HMAC, SHA
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes
from urlparse import urlparse, parse_qs
from urllib import unquote
from urllib.parse import unquote, urlparse, parse_qs
from win32com.client import GetObject
from win32api import OpenProcess, CloseHandle, TerminateProcess
import subprocess
import struct
import time
import sys
import re
and context from other files:
# Path: yubioath/yubicommon/compat.py
# def int2byte(i):
# if _PY2:
# return chr(i)
# return bytes((i,))
#
# def byte2int(i):
# if _PY2:
# return ord(i)
# return i
, which may contain function names, class names, or code. Output only the next line. | l *= 256 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.