Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|>
class TasksGithubTestCase(TestCase):
@mock.patch('gitmostwanted.tasks.github.user_starred')
def test_star_repository_with_invalid_starred(self, fake):
fake.return_value = None, 404
self.assertFalse(repo_starred_star(1, 'token'))
fake.assert_called_once_with('token')
@mock.patch('gitmostwanted.tasks.github.user_starred_star')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from gitmostwanted.tasks.github import repo_starred_star
from unittest import TestCase, mock
and context:
# Path: gitmostwanted/tasks/github.py
# @celery.task()
# def repo_starred_star(user_id: int, access_token: str):
# starred, code = user_starred(access_token)
# if not starred:
# return False
#
# attitudes = UserAttitude.list_liked_by_user(user_id)
#
# lst_in = [repo_like(s['full_name'], user_id) for s in starred
# if not [a for a in attitudes if s['full_name'] == a.repo.full_name]]
#
# lst_out = [user_starred_star(r.repo.full_name, access_token) for r in attitudes
# if not [x for x in starred if x['full_name'] == r.repo.full_name]]
#
# return len(lst_out), len(list(filter(None, lst_in)))
which might include code, classes, or functions. Output only the next line. | @mock.patch('gitmostwanted.tasks.github.user_starred') |
Continue the code snippet: <|code_start|>class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True)
username = db.Column(db.String(80))
github_id = db.Column(db.BigInteger, unique=True)
class UserAttitude(db.Model):
__tablename__ = 'users_attitude'
user = db.relationship(User)
user_id = db.Column(
db.Integer,
db.ForeignKey('users.id', name='fk_users_id', ondelete='CASCADE'),
primary_key=True
)
repo = db.relationship(Repo, lazy=False)
repo_id = db.Column(
db.BigInteger,
db.ForeignKey('repos.id', name='fk_repos_id', ondelete='CASCADE'),
primary_key=True, index=True
)
attitude = db.Column(db.Enum('like', 'dislike', 'neutral'), nullable=False)
@classmethod
def join_by_user_and_repo(cls, query, user_id: int, repo_id: int):
return query.outerjoin(cls, (cls.user_id == user_id) & (cls.repo_id == repo_id))
<|code_end|>
. Use current file imports:
from gitmostwanted.models.repo import Repo
from gitmostwanted.app import db
and context (classes, functions, or code) from other files:
# Path: gitmostwanted/models/repo.py
# class Repo(db.Model):
# __tablename__ = 'repos'
#
# id = db.Column(db.BigInteger, primary_key=True)
# checked_at = db.Column(db.DateTime, index=True)
# created_at = db.Column(db.DateTime, nullable=False, index=True)
# description = db.Column(db.String(250))
# forks_count = db.Column(INTEGER(unsigned=True), nullable=False, server_default='0', index=True)
# full_name = db.Column(db.String(120), nullable=False)
# homepage = db.Column(db.String(150))
# html_url = db.Column(db.String(150), nullable=False)
# language = db.Column(db.String(25))
# license = db.Column(db.String(20), index=True)
# last_reset_at = db.Column(db.DateTime, index=True)
# mature = db.Column(db.Boolean, nullable=False, server_default=expression.false(), index=True)
# name = db.Column(db.String(80), nullable=False)
# open_issues_count = db.Column(INTEGER(unsigned=True), nullable=False, server_default='0')
# size = db.Column(INTEGER(unsigned=True), nullable=False, server_default='0')
# stargazers_count = db.Column(
# INTEGER(unsigned=True), nullable=False, server_default='0', index=True
# )
# status = db.Column(
# db.Enum('promising', 'new', 'unknown', 'deleted', 'hopeless'),
# server_default='new', nullable=False, index=True
# )
# status_updated_at = db.Column(db.DateTime)
# subscribers_count = db.Column(
# INTEGER(unsigned=True), nullable=False, server_default='0', index=True
# )
# topics = db.relationship(RepoTopics, cascade='all, delete-orphan')
# worth = db.Column(
# SMALLINT(display_width=2), index=True, nullable=False,
# server_default=str(app.config['REPOSITORY_WORTH_DEFAULT'])
# )
# worth_max = db.Column(SMALLINT(display_width=2), nullable=False, server_default='0')
#
# def __setattr__(self, key, value):
# if key == 'status' and self.status != value:
# value = str(Status(value))
# self.status_updated_at = datetime.now()
#
# if key == 'homepage':
# value = str(Url(value[:150])) if value else None
#
# if key == 'description':
# value = str(TextWithoutSmilies(str(TextNormalized(value[:250])))) if value else None
#
# if key == 'worth' and self.worth_max < value:
# self.worth_max = value
#
# super().__setattr__(key, value)
#
# @classmethod
# def filter_by_args(cls, q, args: ImmutableMultiDict):
# lang = args.get('lang')
# if lang != 'All' and (lang,) in cls.language_distinct():
# q = q.filter(cls.language == lang)
#
# status = args.get('status')
# if status in ('promising', 'hopeless'):
# q = q.filter(cls.status == status)
#
# if bool(args.get('mature')):
# q = q.filter(cls.mature.is_(True))
#
# try:
# q = q.filter(cls.full_name.like(str(SearchTerm(args.get('term', '')))))
# except ValueError:
# pass
#
# return q
#
# @staticmethod
# def language_distinct():
# if not hasattr(Repo.language_distinct, 'memoize'):
# q = db.session.query(Repo.language).distinct().filter(Repo.language.isnot(None))
# setattr(Repo.language_distinct, 'memoize', sorted(q.all()))
# return getattr(Repo.language_distinct, 'memoize')
#
# @classmethod
# def get_one_by_full_name(cls, name):
# return cls.query.filter(cls.full_name == name).first()
#
# Path: gitmostwanted/app.py
. Output only the next line. | @classmethod |
Here is a snippet: <|code_start|>
def test_mapkeys():
eq_(mapkeys(str, {1: 'this', 2: 'that'}),
{'1': 'this', '2': 'that'})
def test_mapvalues():
eq_(mapvalues(tuple, {1: 'this', 2: 'that'}),
<|code_end|>
. Write the next line using the current file imports:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
, which may include functions, classes, or code. Output only the next line. | {1: ('t', 'h', 'i', 's',), 2: ('t', 'h', 'a', 't',)}) |
Given the code snippet: <|code_start|>
def test_mapkeys():
eq_(mapkeys(str, {1: 'this', 2: 'that'}),
{'1': 'this', '2': 'that'})
def test_mapvalues():
eq_(mapvalues(tuple, {1: 'this', 2: 'that'}),
{1: ('t', 'h', 'i', 's',), 2: ('t', 'h', 'a', 't',)})
def test_group():
for i, n, o in (
('', 2, ()),
('A', 2, (('A',),)),
('AB', 2, (('A', 'B'),)),
('ABCDE', 2, (('A', 'B'), ('C', 'D'), ('E',))),
):
yield check_group, i, n, o
def check_group(i, n, o):
eq_(tuple(group(i, n)), tuple(o))
def test_listxxx():
data = dict(a='a', b='x', c='123')
keys = listkeys(data)
values = listvalues(data)
items = listitems(data)
<|code_end|>
, generate the next line using the imports in this file:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context (functions, classes, or occasionally code) from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
. Output only the next line. | types = map(type, (keys, values, items)) |
Next line prediction: <|code_start|> {1: ('t', 'h', 'i', 's',), 2: ('t', 'h', 'a', 't',)})
def test_group():
for i, n, o in (
('', 2, ()),
('A', 2, (('A',),)),
('AB', 2, (('A', 'B'),)),
('ABCDE', 2, (('A', 'B'), ('C', 'D'), ('E',))),
):
yield check_group, i, n, o
def check_group(i, n, o):
eq_(tuple(group(i, n)), tuple(o))
def test_listxxx():
data = dict(a='a', b='x', c='123')
keys = listkeys(data)
values = listvalues(data)
items = listitems(data)
types = map(type, (keys, values, items))
eq_(set(types), set([list]))
eq_(sorted(keys), ['a', 'b', 'c'])
eq_(sorted(values), ['123', 'a', 'x'])
eq_(sorted(items), [('a', 'a'), ('b', 'x'), ('c', '123')])
<|code_end|>
. Use current file imports:
(from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
))
and context including class names, function names, or small code snippets from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
. Output only the next line. | def test_inverse_mapping_works(): |
Based on the snippet: <|code_start|>
def test_mapkeys():
eq_(mapkeys(str, {1: 'this', 2: 'that'}),
{'1': 'this', '2': 'that'})
def test_mapvalues():
eq_(mapvalues(tuple, {1: 'this', 2: 'that'}),
{1: ('t', 'h', 'i', 's',), 2: ('t', 'h', 'a', 't',)})
def test_group():
for i, n, o in (
('', 2, ()),
('A', 2, (('A',),)),
('AB', 2, (('A', 'B'),)),
('ABCDE', 2, (('A', 'B'), ('C', 'D'), ('E',))),
):
yield check_group, i, n, o
def check_group(i, n, o):
eq_(tuple(group(i, n)), tuple(o))
def test_listxxx():
<|code_end|>
, predict the immediate next line with the help of imports:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context (classes, functions, sometimes code) from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
. Output only the next line. | data = dict(a='a', b='x', c='123') |
Here is a snippet: <|code_start|>
def test_inverse_mapping_works():
eq_(inverse_mapping({'a': 123, 'x': 'x'}), {123: 'a', 'x': 'x'})
@raises(ValueError)
def test_inverse_mapping_raises_exception_when_values_arent_unique():
inverse_mapping({'a': 1, 'b': 1})
def test_is_sorted():
for sequence, kwargs, result in (
((1, 2, 3), {}, True),
([1, 2, 3], {}, True),
([2, 1], {}, False),
([1, 1], {}, True),
((), {}, True),
([], {}, True),
((3, 2, 1), {'reverse': True}, True),
((3, 2, 1), {'key': lambda e: -e}, True),
((1, 2, 3), {'reverse': True, 'key': lambda e: -e}, True),
):
yield check_is_sorted, sequence, kwargs, result
def check_is_sorted(sequence, kwargs, result):
eq_(is_sorted(sequence, **kwargs), result)
<|code_end|>
. Write the next line using the current file imports:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
, which may include functions, classes, or code. Output only the next line. | @raises(TypeError) |
Based on the snippet: <|code_start|> eq_(tuple(group(i, n)), tuple(o))
def test_listxxx():
data = dict(a='a', b='x', c='123')
keys = listkeys(data)
values = listvalues(data)
items = listitems(data)
types = map(type, (keys, values, items))
eq_(set(types), set([list]))
eq_(sorted(keys), ['a', 'b', 'c'])
eq_(sorted(values), ['123', 'a', 'x'])
eq_(sorted(items), [('a', 'a'), ('b', 'x'), ('c', '123')])
def test_inverse_mapping_works():
eq_(inverse_mapping({'a': 123, 'x': 'x'}), {123: 'a', 'x': 'x'})
@raises(ValueError)
def test_inverse_mapping_raises_exception_when_values_arent_unique():
inverse_mapping({'a': 1, 'b': 1})
def test_is_sorted():
for sequence, kwargs, result in (
((1, 2, 3), {}, True),
([1, 2, 3], {}, True),
([2, 1], {}, False),
<|code_end|>
, predict the immediate next line with the help of imports:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context (classes, functions, sometimes code) from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
. Output only the next line. | ([1, 1], {}, True), |
Using the snippet: <|code_start|> items = listitems(data)
types = map(type, (keys, values, items))
eq_(set(types), set([list]))
eq_(sorted(keys), ['a', 'b', 'c'])
eq_(sorted(values), ['123', 'a', 'x'])
eq_(sorted(items), [('a', 'a'), ('b', 'x'), ('c', '123')])
def test_inverse_mapping_works():
eq_(inverse_mapping({'a': 123, 'x': 'x'}), {123: 'a', 'x': 'x'})
@raises(ValueError)
def test_inverse_mapping_raises_exception_when_values_arent_unique():
inverse_mapping({'a': 1, 'b': 1})
def test_is_sorted():
for sequence, kwargs, result in (
((1, 2, 3), {}, True),
([1, 2, 3], {}, True),
([2, 1], {}, False),
([1, 1], {}, True),
((), {}, True),
([], {}, True),
((3, 2, 1), {'reverse': True}, True),
((3, 2, 1), {'key': lambda e: -e}, True),
((1, 2, 3), {'reverse': True, 'key': lambda e: -e}, True),
):
<|code_end|>
, determine the next line of code. You have imports:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context (class names, function names, or code) available:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
. Output only the next line. | yield check_is_sorted, sequence, kwargs, result |
Based on the snippet: <|code_start|>
def test_mapkeys():
eq_(mapkeys(str, {1: 'this', 2: 'that'}),
{'1': 'this', '2': 'that'})
def test_mapvalues():
eq_(mapvalues(tuple, {1: 'this', 2: 'that'}),
{1: ('t', 'h', 'i', 's',), 2: ('t', 'h', 'a', 't',)})
def test_group():
<|code_end|>
, predict the immediate next line with the help of imports:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context (classes, functions, sometimes code) from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
. Output only the next line. | for i, n, o in ( |
Continue the code snippet: <|code_start|> eq_(is_sorted(sequence, **kwargs), result)
@raises(TypeError)
def test_is_sorted_fails_on_sets():
is_sorted(set())
@raises(TypeError)
def test_is_sorted_fails_on_dictionaries():
is_sorted({})
def test_has_unique_elements():
eq_(has_unique_elements([1, 2, 3]), True)
eq_(has_unique_elements([1, 2, 1]), False)
def test_copy_keys_if_present():
destination = {'a': 'old val a'}
copy_keys_if_present(
{'a': 'new val a', 'b': 'val b'},
destination,
['a', 'b', 'c']
)
eq_(destination, {'a': 'new val a', 'b': 'val b'})
def test_listmap_works_and_returns_a_list():
result = listmap(str, [1, 2])
<|code_end|>
. Use current file imports:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context (classes, functions, or code) from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
. Output only the next line. | eq_((result, type(result)), (['1', '2'], list)) |
Given the following code snippet before the placeholder: <|code_start|>
@raises(ValueError)
def test_inverse_mapping_raises_exception_when_values_arent_unique():
inverse_mapping({'a': 1, 'b': 1})
def test_is_sorted():
for sequence, kwargs, result in (
((1, 2, 3), {}, True),
([1, 2, 3], {}, True),
([2, 1], {}, False),
([1, 1], {}, True),
((), {}, True),
([], {}, True),
((3, 2, 1), {'reverse': True}, True),
((3, 2, 1), {'key': lambda e: -e}, True),
((1, 2, 3), {'reverse': True, 'key': lambda e: -e}, True),
):
yield check_is_sorted, sequence, kwargs, result
def check_is_sorted(sequence, kwargs, result):
eq_(is_sorted(sequence, **kwargs), result)
@raises(TypeError)
def test_is_sorted_fails_on_sets():
is_sorted(set())
<|code_end|>
, predict the next line using imports from the current file:
from nose.tools import eq_, raises
from smarkets.itertools import (
copy_keys_if_present,
group,
has_unique_elements,
inverse_mapping,
is_sorted,
listitems,
listkeys,
listmap,
listvalues,
mapkeys,
mapvalues,
)
and context including class names, function names, and sometimes code from other files:
# Path: smarkets/itertools.py
# def copy_keys_if_present(source, destination, keys):
# """Copy keys from source mapping to destination mapping while skipping nonexistent keys."""
# for key in keys:
# try:
# value = source[key]
# except KeyError:
# pass
# else:
# destination[key] = value
#
# def group(iterable, n):
# iterator = iter(iterable)
# chunk = True
# while chunk:
# chunk = tuple(islice(iterator, n))
# if chunk:
# yield chunk
#
# def has_unique_elements(sequence):
# return len(set(sequence)) == len(sequence)
#
# def inverse_mapping(d):
# """Return a dictionary with input mapping keys as values and values as keys.
#
# :raises:
# :ValueError: Input mapping values aren't uniqe.
# """
#
# new_mapping = {v: k for k, v in iteritems(d)}
# if len(new_mapping) != len(d):
# raise ValueError("Input mapping values aren't unique")
# return new_mapping
#
# def is_sorted(sequence, **kwargs):
# """
# :type sequence: tuple or list
# :param kwargs: :func:`sorted` kwargs
# """
# if not isinstance(sequence, (tuple, list)):
# raise TypeError('Sequence needs to be a tuple or a list')
#
# if not isinstance(sequence, list):
# sequence = list(sequence)
#
# return sorted(sequence, **kwargs) == sequence
#
# def listitems(d):
# """Return `d` item list"""
# return list(iteritems(d))
#
# def listkeys(d):
# """Return `d` key list"""
# return list(iterkeys(d))
#
# def listmap(*args):
# return list(map(*args))
#
# def listvalues(d):
# """Return `d` value list"""
# return list(itervalues(d))
#
# def mapkeys(function, mapping):
# return dict((function(k), v) for (k, v) in iteritems(mapping))
#
# def mapvalues(function, mapping):
# return dict((k, function(v)) for (k, v) in iteritems(mapping))
. Output only the next line. | @raises(TypeError) |
Given snippet: <|code_start|> self.callback -= handler
self.assertEquals(len(real_handlers), len(self.callback))
self.callback(message=sentinel.message)
for handler in to_unhandle:
self.assertFalse(handler.called)
for handler in real_handlers:
handler.assert_called_once_with(message=sentinel.message)
def test_handle_exception(self):
"Test that an exception is raised by the callback method"
handler = Mock(side_effect=self._always_raise)
self.callback += handler
self.assertRaises(Exception, self.callback, message=sentinel.message)
def test_2_handle_exception(self):
"Test that an exception is raised by the callback method"
handler1 = Mock(side_effect=self._always_raise)
handler2 = Mock()
self.callback += handler1
self.callback += handler2
self.assertRaises(Exception, self.callback, message=sentinel.message)
# Because the collection of handlers in the `Signal` is a
# `set` the 'firing' order is undefined. However, if handler2
# is called, we assert that it is called correctly here.
if handler2.called:
handler2.assert_called_once_with(message=sentinel.message)
@staticmethod
def _always_raise(*args, **kwargs):
"Always raise `Exception` with no arguments"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from itertools import chain
from mock import Mock, sentinel
from nose.tools import eq_, raises
from six.moves import xrange
from smarkets.signal import Signal
and context:
# Path: smarkets/signal.py
# class Signal(object):
#
# """
# All instance methods of this class are thread safe.
# """
#
# def __init__(self):
# self._handlers = set()
#
# def add(self, handler):
# """
# Add signal handler. You can also do::
#
# signal = Signal()
# signal += handler
# """
# self._handlers.add(handler)
#
# return self
#
# __iadd__ = add
# handle = add
#
# def remove(self, handler):
# """
# Remove signal handler. You can also do::
#
# signal = Signal()
# # add a handler "handler"
# signal -= handler
# """
# self._handlers.remove(handler)
#
# return self
#
# __isub__ = remove
# __unhandle__ = remove
#
# def fire(self, **kwargs):
# """Execute all handlers associated with this Signal.
#
# You can also call signal object to get the same result::
#
# signal = Signal()
# signal() # calls the signal handler
# """
# for handler in copy(self._handlers):
# handler(**kwargs)
#
# __call__ = fire
#
# def __len__(self):
# return len(self._handlers)
#
# def __iter__(self):
# return iter(self._handlers)
which might include code, classes, or functions. Output only the next line. | raise Exception() |
Given the code snippet: <|code_start|>"Smarkets API client"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
def _get_payload_types(module):
module_name = module.__name__.split('.')[-1]
return dict((
(getattr(module, x),
'%s.%s' % (module_name.replace('_pb2', ''), x.replace('PAYLOAD_', '').lower()))
<|code_end|>
, generate the next line using the imports in this file:
import logging
import sys
from smarkets.signal import Signal
from smarkets.streaming_api import eto
from smarkets.streaming_api import seto
from smarkets.streaming_api.exceptions import InvalidCallbackError, LoginError, LoginTimeout
from smarkets.streaming_api.utils import set_payload_message
and context (functions, classes, or occasionally code) from other files:
# Path: smarkets/signal.py
# class Signal(object):
#
# """
# All instance methods of this class are thread safe.
# """
#
# def __init__(self):
# self._handlers = set()
#
# def add(self, handler):
# """
# Add signal handler. You can also do::
#
# signal = Signal()
# signal += handler
# """
# self._handlers.add(handler)
#
# return self
#
# __iadd__ = add
# handle = add
#
# def remove(self, handler):
# """
# Remove signal handler. You can also do::
#
# signal = Signal()
# # add a handler "handler"
# signal -= handler
# """
# self._handlers.remove(handler)
#
# return self
#
# __isub__ = remove
# __unhandle__ = remove
#
# def fire(self, **kwargs):
# """Execute all handlers associated with this Signal.
#
# You can also call signal object to get the same result::
#
# signal = Signal()
# signal() # calls the signal handler
# """
# for handler in copy(self._handlers):
# handler(**kwargs)
#
# __call__ = fire
#
# def __len__(self):
# return len(self._handlers)
#
# def __iter__(self):
# return iter(self._handlers)
#
# Path: smarkets/streaming_api/eto.py
#
# Path: smarkets/streaming_api/seto.py
#
# Path: smarkets/streaming_api/exceptions.py
# class InvalidCallbackError(_Error):
#
# "Invalid callback was specified"
# pass
#
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/utils.py
# def set_payload_message(payload, message):
# underscore_form = camel_case_to_underscores(type(message).__name__)
# payload_type = getattr(seto, 'PAYLOAD_' + underscore_form.upper())
# payload.type = payload_type
# getattr(payload, underscore_form).CopyFrom(message)
. Output only the next line. | for x in dir(module) if x.startswith('PAYLOAD_') |
Based on the snippet: <|code_start|>"Smarkets API client"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
def _get_payload_types(module):
module_name = module.__name__.split('.')[-1]
return dict((
(getattr(module, x),
'%s.%s' % (module_name.replace('_pb2', ''), x.replace('PAYLOAD_', '').lower()))
for x in dir(module) if x.startswith('PAYLOAD_')
))
_ETO_PAYLOAD_TYPES = _get_payload_types(eto)
_SETO_PAYLOAD_TYPES = _get_payload_types(seto)
READ_MODE_BUFFER_FROM_SOCKET = 1
READ_MODE_DISPATCH_FROM_BUFFER = 2
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import sys
from smarkets.signal import Signal
from smarkets.streaming_api import eto
from smarkets.streaming_api import seto
from smarkets.streaming_api.exceptions import InvalidCallbackError, LoginError, LoginTimeout
from smarkets.streaming_api.utils import set_payload_message
and context (classes, functions, sometimes code) from other files:
# Path: smarkets/signal.py
# class Signal(object):
#
# """
# All instance methods of this class are thread safe.
# """
#
# def __init__(self):
# self._handlers = set()
#
# def add(self, handler):
# """
# Add signal handler. You can also do::
#
# signal = Signal()
# signal += handler
# """
# self._handlers.add(handler)
#
# return self
#
# __iadd__ = add
# handle = add
#
# def remove(self, handler):
# """
# Remove signal handler. You can also do::
#
# signal = Signal()
# # add a handler "handler"
# signal -= handler
# """
# self._handlers.remove(handler)
#
# return self
#
# __isub__ = remove
# __unhandle__ = remove
#
# def fire(self, **kwargs):
# """Execute all handlers associated with this Signal.
#
# You can also call signal object to get the same result::
#
# signal = Signal()
# signal() # calls the signal handler
# """
# for handler in copy(self._handlers):
# handler(**kwargs)
#
# __call__ = fire
#
# def __len__(self):
# return len(self._handlers)
#
# def __iter__(self):
# return iter(self._handlers)
#
# Path: smarkets/streaming_api/eto.py
#
# Path: smarkets/streaming_api/seto.py
#
# Path: smarkets/streaming_api/exceptions.py
# class InvalidCallbackError(_Error):
#
# "Invalid callback was specified"
# pass
#
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/utils.py
# def set_payload_message(payload, message):
# underscore_form = camel_case_to_underscores(type(message).__name__)
# payload_type = getattr(seto, 'PAYLOAD_' + underscore_form.upper())
# payload.type = payload_type
# getattr(payload, underscore_form).CopyFrom(message)
. Output only the next line. | READ_MODE_BUFFER_AND_DISPATCH = READ_MODE_BUFFER_FROM_SOCKET | READ_MODE_DISPATCH_FROM_BUFFER |
Predict the next line after this snippet: <|code_start|>"Smarkets API client"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
def _get_payload_types(module):
module_name = module.__name__.split('.')[-1]
return dict((
(getattr(module, x),
'%s.%s' % (module_name.replace('_pb2', ''), x.replace('PAYLOAD_', '').lower()))
for x in dir(module) if x.startswith('PAYLOAD_')
))
_ETO_PAYLOAD_TYPES = _get_payload_types(eto)
_SETO_PAYLOAD_TYPES = _get_payload_types(seto)
READ_MODE_BUFFER_FROM_SOCKET = 1
<|code_end|>
using the current file's imports:
import logging
import sys
from smarkets.signal import Signal
from smarkets.streaming_api import eto
from smarkets.streaming_api import seto
from smarkets.streaming_api.exceptions import InvalidCallbackError, LoginError, LoginTimeout
from smarkets.streaming_api.utils import set_payload_message
and any relevant context from other files:
# Path: smarkets/signal.py
# class Signal(object):
#
# """
# All instance methods of this class are thread safe.
# """
#
# def __init__(self):
# self._handlers = set()
#
# def add(self, handler):
# """
# Add signal handler. You can also do::
#
# signal = Signal()
# signal += handler
# """
# self._handlers.add(handler)
#
# return self
#
# __iadd__ = add
# handle = add
#
# def remove(self, handler):
# """
# Remove signal handler. You can also do::
#
# signal = Signal()
# # add a handler "handler"
# signal -= handler
# """
# self._handlers.remove(handler)
#
# return self
#
# __isub__ = remove
# __unhandle__ = remove
#
# def fire(self, **kwargs):
# """Execute all handlers associated with this Signal.
#
# You can also call signal object to get the same result::
#
# signal = Signal()
# signal() # calls the signal handler
# """
# for handler in copy(self._handlers):
# handler(**kwargs)
#
# __call__ = fire
#
# def __len__(self):
# return len(self._handlers)
#
# def __iter__(self):
# return iter(self._handlers)
#
# Path: smarkets/streaming_api/eto.py
#
# Path: smarkets/streaming_api/seto.py
#
# Path: smarkets/streaming_api/exceptions.py
# class InvalidCallbackError(_Error):
#
# "Invalid callback was specified"
# pass
#
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/utils.py
# def set_payload_message(payload, message):
# underscore_form = camel_case_to_underscores(type(message).__name__)
# payload_type = getattr(seto, 'PAYLOAD_' + underscore_form.upper())
# payload.type = payload_type
# getattr(payload, underscore_form).CopyFrom(message)
. Output only the next line. | READ_MODE_DISPATCH_FROM_BUFFER = 2 |
Given snippet: <|code_start|>"Smarkets API client"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
def _get_payload_types(module):
module_name = module.__name__.split('.')[-1]
return dict((
(getattr(module, x),
'%s.%s' % (module_name.replace('_pb2', ''), x.replace('PAYLOAD_', '').lower()))
for x in dir(module) if x.startswith('PAYLOAD_')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import sys
from smarkets.signal import Signal
from smarkets.streaming_api import eto
from smarkets.streaming_api import seto
from smarkets.streaming_api.exceptions import InvalidCallbackError, LoginError, LoginTimeout
from smarkets.streaming_api.utils import set_payload_message
and context:
# Path: smarkets/signal.py
# class Signal(object):
#
# """
# All instance methods of this class are thread safe.
# """
#
# def __init__(self):
# self._handlers = set()
#
# def add(self, handler):
# """
# Add signal handler. You can also do::
#
# signal = Signal()
# signal += handler
# """
# self._handlers.add(handler)
#
# return self
#
# __iadd__ = add
# handle = add
#
# def remove(self, handler):
# """
# Remove signal handler. You can also do::
#
# signal = Signal()
# # add a handler "handler"
# signal -= handler
# """
# self._handlers.remove(handler)
#
# return self
#
# __isub__ = remove
# __unhandle__ = remove
#
# def fire(self, **kwargs):
# """Execute all handlers associated with this Signal.
#
# You can also call signal object to get the same result::
#
# signal = Signal()
# signal() # calls the signal handler
# """
# for handler in copy(self._handlers):
# handler(**kwargs)
#
# __call__ = fire
#
# def __len__(self):
# return len(self._handlers)
#
# def __iter__(self):
# return iter(self._handlers)
#
# Path: smarkets/streaming_api/eto.py
#
# Path: smarkets/streaming_api/seto.py
#
# Path: smarkets/streaming_api/exceptions.py
# class InvalidCallbackError(_Error):
#
# "Invalid callback was specified"
# pass
#
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/utils.py
# def set_payload_message(payload, message):
# underscore_form = camel_case_to_underscores(type(message).__name__)
# payload_type = getattr(seto, 'PAYLOAD_' + underscore_form.upper())
# payload.type = payload_type
# getattr(payload, underscore_form).CopyFrom(message)
which might include code, classes, or functions. Output only the next line. | )) |
Given the following code snippet before the placeholder: <|code_start|>"Smarkets API client"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
def _get_payload_types(module):
module_name = module.__name__.split('.')[-1]
return dict((
(getattr(module, x),
'%s.%s' % (module_name.replace('_pb2', ''), x.replace('PAYLOAD_', '').lower()))
<|code_end|>
, predict the next line using imports from the current file:
import logging
import sys
from smarkets.signal import Signal
from smarkets.streaming_api import eto
from smarkets.streaming_api import seto
from smarkets.streaming_api.exceptions import InvalidCallbackError, LoginError, LoginTimeout
from smarkets.streaming_api.utils import set_payload_message
and context including class names, function names, and sometimes code from other files:
# Path: smarkets/signal.py
# class Signal(object):
#
# """
# All instance methods of this class are thread safe.
# """
#
# def __init__(self):
# self._handlers = set()
#
# def add(self, handler):
# """
# Add signal handler. You can also do::
#
# signal = Signal()
# signal += handler
# """
# self._handlers.add(handler)
#
# return self
#
# __iadd__ = add
# handle = add
#
# def remove(self, handler):
# """
# Remove signal handler. You can also do::
#
# signal = Signal()
# # add a handler "handler"
# signal -= handler
# """
# self._handlers.remove(handler)
#
# return self
#
# __isub__ = remove
# __unhandle__ = remove
#
# def fire(self, **kwargs):
# """Execute all handlers associated with this Signal.
#
# You can also call signal object to get the same result::
#
# signal = Signal()
# signal() # calls the signal handler
# """
# for handler in copy(self._handlers):
# handler(**kwargs)
#
# __call__ = fire
#
# def __len__(self):
# return len(self._handlers)
#
# def __iter__(self):
# return iter(self._handlers)
#
# Path: smarkets/streaming_api/eto.py
#
# Path: smarkets/streaming_api/seto.py
#
# Path: smarkets/streaming_api/exceptions.py
# class InvalidCallbackError(_Error):
#
# "Invalid callback was specified"
# pass
#
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/utils.py
# def set_payload_message(payload, message):
# underscore_form = camel_case_to_underscores(type(message).__name__)
# payload_type = getattr(seto, 'PAYLOAD_' + underscore_form.upper())
# payload.type = payload_type
# getattr(payload, underscore_form).CopyFrom(message)
. Output only the next line. | for x in dir(module) if x.startswith('PAYLOAD_') |
Given the code snippet: <|code_start|>"Smarkets API client"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
def _get_payload_types(module):
module_name = module.__name__.split('.')[-1]
<|code_end|>
, generate the next line using the imports in this file:
import logging
import sys
from smarkets.signal import Signal
from smarkets.streaming_api import eto
from smarkets.streaming_api import seto
from smarkets.streaming_api.exceptions import InvalidCallbackError, LoginError, LoginTimeout
from smarkets.streaming_api.utils import set_payload_message
and context (functions, classes, or occasionally code) from other files:
# Path: smarkets/signal.py
# class Signal(object):
#
# """
# All instance methods of this class are thread safe.
# """
#
# def __init__(self):
# self._handlers = set()
#
# def add(self, handler):
# """
# Add signal handler. You can also do::
#
# signal = Signal()
# signal += handler
# """
# self._handlers.add(handler)
#
# return self
#
# __iadd__ = add
# handle = add
#
# def remove(self, handler):
# """
# Remove signal handler. You can also do::
#
# signal = Signal()
# # add a handler "handler"
# signal -= handler
# """
# self._handlers.remove(handler)
#
# return self
#
# __isub__ = remove
# __unhandle__ = remove
#
# def fire(self, **kwargs):
# """Execute all handlers associated with this Signal.
#
# You can also call signal object to get the same result::
#
# signal = Signal()
# signal() # calls the signal handler
# """
# for handler in copy(self._handlers):
# handler(**kwargs)
#
# __call__ = fire
#
# def __len__(self):
# return len(self._handlers)
#
# def __iter__(self):
# return iter(self._handlers)
#
# Path: smarkets/streaming_api/eto.py
#
# Path: smarkets/streaming_api/seto.py
#
# Path: smarkets/streaming_api/exceptions.py
# class InvalidCallbackError(_Error):
#
# "Invalid callback was specified"
# pass
#
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/utils.py
# def set_payload_message(payload, message):
# underscore_form = camel_case_to_underscores(type(message).__name__)
# payload_type = getattr(seto, 'PAYLOAD_' + underscore_form.upper())
# payload.type = payload_type
# getattr(payload, underscore_form).CopyFrom(message)
. Output only the next line. | return dict(( |
Predict the next line after this snippet: <|code_start|>"Smarkets API client"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
def _get_payload_types(module):
module_name = module.__name__.split('.')[-1]
return dict((
(getattr(module, x),
'%s.%s' % (module_name.replace('_pb2', ''), x.replace('PAYLOAD_', '').lower()))
<|code_end|>
using the current file's imports:
import logging
import sys
from smarkets.signal import Signal
from smarkets.streaming_api import eto
from smarkets.streaming_api import seto
from smarkets.streaming_api.exceptions import InvalidCallbackError, LoginError, LoginTimeout
from smarkets.streaming_api.utils import set_payload_message
and any relevant context from other files:
# Path: smarkets/signal.py
# class Signal(object):
#
# """
# All instance methods of this class are thread safe.
# """
#
# def __init__(self):
# self._handlers = set()
#
# def add(self, handler):
# """
# Add signal handler. You can also do::
#
# signal = Signal()
# signal += handler
# """
# self._handlers.add(handler)
#
# return self
#
# __iadd__ = add
# handle = add
#
# def remove(self, handler):
# """
# Remove signal handler. You can also do::
#
# signal = Signal()
# # add a handler "handler"
# signal -= handler
# """
# self._handlers.remove(handler)
#
# return self
#
# __isub__ = remove
# __unhandle__ = remove
#
# def fire(self, **kwargs):
# """Execute all handlers associated with this Signal.
#
# You can also call signal object to get the same result::
#
# signal = Signal()
# signal() # calls the signal handler
# """
# for handler in copy(self._handlers):
# handler(**kwargs)
#
# __call__ = fire
#
# def __len__(self):
# return len(self._handlers)
#
# def __iter__(self):
# return iter(self._handlers)
#
# Path: smarkets/streaming_api/eto.py
#
# Path: smarkets/streaming_api/seto.py
#
# Path: smarkets/streaming_api/exceptions.py
# class InvalidCallbackError(_Error):
#
# "Invalid callback was specified"
# pass
#
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/utils.py
# def set_payload_message(payload, message):
# underscore_form = camel_case_to_underscores(type(message).__name__)
# payload_type = getattr(seto, 'PAYLOAD_' + underscore_form.upper())
# payload.type = payload_type
# getattr(payload, underscore_form).CopyFrom(message)
. Output only the next line. | for x in dir(module) if x.startswith('PAYLOAD_') |
Given the code snippet: <|code_start|>from __future__ import absolute_import, division, print_function, unicode_literals
def test_general_lazycall_behaviour():
counter = [0]
def computation(*args, **kwargs):
eq_((args, kwargs), ((1, 2), {'a': 'b'}))
counter[0] += 1
<|code_end|>
, generate the next line using the imports in this file:
from nose.tools import eq_
from six.moves import xrange
from smarkets.lazy import LazyCall
and context (functions, classes, or occasionally code) from other files:
# Path: smarkets/lazy.py
# class LazyCall(object):
#
# """Encapsulates a computation with defined arguments.
#
# Its main use case at the moment is to pass some relatively expensive to generate content
# to logging subsystem and not do the computations unless the variable is actually used,
# for example:
#
# log.debug('Received message %s', LazyCall(expensive_message_to_string, message))
#
# General behaviour:
#
# >>> counter = [0]
# >>> def computation(*args, **kwargs):
# ... print('call!', args, kwargs)
# ... counter[0] += 1
# ... return 'result value'
# >>>
# >>> # str() convertion for the output below to not have
# >>> # the "u" prefix on Python 2 which makes this doctest
# >>> # Python 2 and Python 3 compatible.
# >>> result = LazyCall(computation, 1, 2, a=str('b'))
# >>> for i in xrange(3):
# ... print(result.get_value())
# call! (1, 2) {'a': 'b'}
# result value
# result value
# result value
# >>> print(result)
# result value
# >>> print(counter[0])
# 1
# """
#
# __slots__ = ('_callable', '_args', '_kwargs', '_value', '_has_value')
#
# def __init__(self, callable_, *args, **kwargs):
# self._callable = callable_
# self._args = args
# self._kwargs = kwargs
# self._value = None
# self._has_value = False
#
# def get_value(self):
# """Get the value of the computation. Computation is only executed once. """
# if not self._has_value:
# self._value = self._callable(*self._args, **self._kwargs)
# self._has_value = True
#
# return self._value
#
# def __str__(self):
# return str(self.get_value())
#
# def __unicode__(self):
# return str(self.get_value()).decode()
. Output only the next line. | return 'result value' |
Here is a snippet: <|code_start|>from __future__ import absolute_import, division, print_function, unicode_literals
def test_memoized():
@memoized
<|code_end|>
. Write the next line using the current file imports:
from nose.tools import eq_
from smarkets.functools import always_return, memoized
and context from other files:
# Path: smarkets/functools.py
# def always_return(value):
# def fun(*args, **kwargs):
# return value
# return fun
#
# def memoized(fun):
# storage = {}
#
# @wraps(fun)
# def wrapper(*args, **kwargs):
# key = (args, tuple(iteritems(kwargs)))
# try:
# value = storage[key]
# except KeyError:
# value = storage[key] = fun(*args, **kwargs)
# return value
# return wrapper
, which may include functions, classes, or code. Output only the next line. | def my_sum(x, y): |
Using the snippet: <|code_start|>from __future__ import absolute_import, division, print_function, unicode_literals
def test_memoized():
@memoized
def my_sum(x, y):
counter[0] += 1
return x + y
counter = [0]
eq_(my_sum(1, 2), 3)
eq_(counter[0], 1)
<|code_end|>
, determine the next line of code. You have imports:
from nose.tools import eq_
from smarkets.functools import always_return, memoized
and context (class names, function names, or code) available:
# Path: smarkets/functools.py
# def always_return(value):
# def fun(*args, **kwargs):
# return value
# return fun
#
# def memoized(fun):
# storage = {}
#
# @wraps(fun)
# def wrapper(*args, **kwargs):
# key = (args, tuple(iteritems(kwargs)))
# try:
# value = storage[key]
# except KeyError:
# value = storage[key] = fun(*args, **kwargs)
# return value
# return wrapper
. Output only the next line. | eq_(my_sum(1, 2), 3) |
Based on the snippet: <|code_start|>
def check_frame_encode(byte_array, output):
frame = bytearray()
frame_encode(frame, byte_array)
eq_(frame, output)
def test_frame_decode_all():
for input_, output in (
# frame matches the boundary
(b'', ([], b'')),
(b'\x01a\x00\x00\x02ab\x00\x03abc\x04abcd', ([b'a', b'ab', b'abc', b'abcd'], b'')),
# ends with complete header but only part of a message
(b'\x03ab', ([], b'\x03ab')),
(b'\x01a\x00\x00\x02ab\x00\x03abc\x04abcd\x03ab', ([b'a', b'ab', b'abc', b'abcd'], b'\x03ab')),
(b'\x05abcd', ([], b'\x05abcd')),
# ends with incomplete header
(b'\x80', ([], b'\x80')),
(b'\x01a\x00\x00\x02ab\x00\x03abc\x04abcd\x03ab', ([b'a', b'ab', b'abc', b'abcd'], b'\x03ab')),
# 4(or more)-byte incomplete header is a special case because it reaches the minimum frame size
# so let's make sure decoding doesn't fail at header decoding stage
(b'\x80\x80\x80\x80', ([], b'\x80\x80\x80\x80')),
(b'\x80\x80\x80\x80\x80', ([], b'\x80\x80\x80\x80\x80')),
# regression: if the second frame is shorter, we still want to decode both...
(b'\x05abcde\x03abc', ([b'abcde', b'abc'], b'')),
):
<|code_end|>
, predict the immediate next line with the help of imports:
from itertools import chain
from nose.tools import eq_, raises
from six.moves import xrange
from smarkets.streaming_api.framing import (
frame_decode_all, frame_encode, IncompleteULEB128, uleb128_decode, uleb128_encode,
)
and context (classes, functions, sometimes code) from other files:
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
#
# def frame_encode(frame, payload):
# """
# Encodes payload and appends it to the given frame.
# :type frame: bytearray
# :type payload: byte string or bytearray
# """
# byte_count = len(payload)
# header = uleb128_encode(byte_count)
# padding = b'\x00' * max(0, MIN_FRAME_SIZE - len(header) - byte_count)
# frame += header
# frame += payload
# frame += padding
#
# class IncompleteULEB128(Exception):
# pass
#
# def uleb128_decode(to_decode):
# """
# :type to_decode: bytes
# :return: decoded value and number of bytes from `to_decode` used to decode it
# :rtype: tuple of (int or long) and int
# :raises:
# :IncompleteULEB128: when `to_decode` doesn't start with ULEB128-encoded number.
# """
# CONTINUATION_MARK = 0x80
# LEAST_MEANINGFUL_PART_MASK = 0x7f
#
# shift = 0
# result = 0
# position = 0
#
# while True:
# try:
# current_byte = to_decode[position]
# except IndexError:
# raise IncompleteULEB128('to_decode does not start with a ULEB128-encoded value')
# else:
# result |= ((current_byte & LEAST_MEANINGFUL_PART_MASK) << shift)
#
# if not current_byte & CONTINUATION_MARK:
# break
# else:
# shift += 7
# position += 1
#
# return result, position + 1
#
# def uleb128_encode(value):
# """Encode a non-negative int/long as a ULEB128 number.
#
# :type value: int or long
# :rtype: bytearray
# """
# if value < 0:
# raise ValueError('Value needs to be non-negative, got %r' % value)
#
# CONTINUATION_MARK = 0x80
# LEAST_MEANINGFUL_PART_MASK = 0x7f
# bits = value & LEAST_MEANINGFUL_PART_MASK
# value >>= 7
# ret = bytearray()
# while value:
# ret += int2byte(CONTINUATION_MARK | bits)
# bits = value & LEAST_MEANINGFUL_PART_MASK
# value >>= 7
# ret += int2byte(bits)
# return ret
. Output only the next line. | yield check_frame_decode_all, bytearray(input_), output |
Given snippet: <|code_start|> (b'ab', b'\x02ab\x00'),
(b'abc', b'\x03abc'),
(b'abcd', b'\x04abcd'),
):
yield check_frame_encode, bytearray(input_), output
def check_frame_encode(byte_array, output):
frame = bytearray()
frame_encode(frame, byte_array)
eq_(frame, output)
def test_frame_decode_all():
for input_, output in (
# frame matches the boundary
(b'', ([], b'')),
(b'\x01a\x00\x00\x02ab\x00\x03abc\x04abcd', ([b'a', b'ab', b'abc', b'abcd'], b'')),
# ends with complete header but only part of a message
(b'\x03ab', ([], b'\x03ab')),
(b'\x01a\x00\x00\x02ab\x00\x03abc\x04abcd\x03ab', ([b'a', b'ab', b'abc', b'abcd'], b'\x03ab')),
(b'\x05abcd', ([], b'\x05abcd')),
# ends with incomplete header
(b'\x80', ([], b'\x80')),
(b'\x01a\x00\x00\x02ab\x00\x03abc\x04abcd\x03ab', ([b'a', b'ab', b'abc', b'abcd'], b'\x03ab')),
# 4(or more)-byte incomplete header is a special case because it reaches the minimum frame size
# so let's make sure decoding doesn't fail at header decoding stage
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from itertools import chain
from nose.tools import eq_, raises
from six.moves import xrange
from smarkets.streaming_api.framing import (
frame_decode_all, frame_encode, IncompleteULEB128, uleb128_decode, uleb128_encode,
)
and context:
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
#
# def frame_encode(frame, payload):
# """
# Encodes payload and appends it to the given frame.
# :type frame: bytearray
# :type payload: byte string or bytearray
# """
# byte_count = len(payload)
# header = uleb128_encode(byte_count)
# padding = b'\x00' * max(0, MIN_FRAME_SIZE - len(header) - byte_count)
# frame += header
# frame += payload
# frame += padding
#
# class IncompleteULEB128(Exception):
# pass
#
# def uleb128_decode(to_decode):
# """
# :type to_decode: bytes
# :return: decoded value and number of bytes from `to_decode` used to decode it
# :rtype: tuple of (int or long) and int
# :raises:
# :IncompleteULEB128: when `to_decode` doesn't start with ULEB128-encoded number.
# """
# CONTINUATION_MARK = 0x80
# LEAST_MEANINGFUL_PART_MASK = 0x7f
#
# shift = 0
# result = 0
# position = 0
#
# while True:
# try:
# current_byte = to_decode[position]
# except IndexError:
# raise IncompleteULEB128('to_decode does not start with a ULEB128-encoded value')
# else:
# result |= ((current_byte & LEAST_MEANINGFUL_PART_MASK) << shift)
#
# if not current_byte & CONTINUATION_MARK:
# break
# else:
# shift += 7
# position += 1
#
# return result, position + 1
#
# def uleb128_encode(value):
# """Encode a non-negative int/long as a ULEB128 number.
#
# :type value: int or long
# :rtype: bytearray
# """
# if value < 0:
# raise ValueError('Value needs to be non-negative, got %r' % value)
#
# CONTINUATION_MARK = 0x80
# LEAST_MEANINGFUL_PART_MASK = 0x7f
# bits = value & LEAST_MEANINGFUL_PART_MASK
# value >>= 7
# ret = bytearray()
# while value:
# ret += int2byte(CONTINUATION_MARK | bits)
# bits = value & LEAST_MEANINGFUL_PART_MASK
# value >>= 7
# ret += int2byte(bits)
# return ret
which might include code, classes, or functions. Output only the next line. | (b'\x80\x80\x80\x80', ([], b'\x80\x80\x80\x80')), |
Given the code snippet: <|code_start|>
def test_dumps():
for value, string in test_data:
yield check_dumps, value, string
def check_dumps(value, string):
eq_(uleb128_encode(value), string)
def test_loads():
for value, string in test_data:
yield check_loads, bytearray(string), value
def check_loads(byte_array, value):
eq_(uleb128_decode(byte_array), (value, len(byte_array)))
def test_loads_and_dumps_are_consistent():
for i in chain(
xrange(2 ** 18),
xrange(2 ** 20, 2 ** 26, 33333),
xrange(2 ** 26, 2 ** 32, 777777),
):
byte_dump = uleb128_encode(i)
eq_(uleb128_decode(byte_dump), (i, len(byte_dump)))
@raises(ValueError)
<|code_end|>
, generate the next line using the imports in this file:
from itertools import chain
from nose.tools import eq_, raises
from six.moves import xrange
from smarkets.streaming_api.framing import (
frame_decode_all, frame_encode, IncompleteULEB128, uleb128_decode, uleb128_encode,
)
and context (functions, classes, or occasionally code) from other files:
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
#
# def frame_encode(frame, payload):
# """
# Encodes payload and appends it to the given frame.
# :type frame: bytearray
# :type payload: byte string or bytearray
# """
# byte_count = len(payload)
# header = uleb128_encode(byte_count)
# padding = b'\x00' * max(0, MIN_FRAME_SIZE - len(header) - byte_count)
# frame += header
# frame += payload
# frame += padding
#
# class IncompleteULEB128(Exception):
# pass
#
# def uleb128_decode(to_decode):
# """
# :type to_decode: bytes
# :return: decoded value and number of bytes from `to_decode` used to decode it
# :rtype: tuple of (int or long) and int
# :raises:
# :IncompleteULEB128: when `to_decode` doesn't start with ULEB128-encoded number.
# """
# CONTINUATION_MARK = 0x80
# LEAST_MEANINGFUL_PART_MASK = 0x7f
#
# shift = 0
# result = 0
# position = 0
#
# while True:
# try:
# current_byte = to_decode[position]
# except IndexError:
# raise IncompleteULEB128('to_decode does not start with a ULEB128-encoded value')
# else:
# result |= ((current_byte & LEAST_MEANINGFUL_PART_MASK) << shift)
#
# if not current_byte & CONTINUATION_MARK:
# break
# else:
# shift += 7
# position += 1
#
# return result, position + 1
#
# def uleb128_encode(value):
# """Encode a non-negative int/long as a ULEB128 number.
#
# :type value: int or long
# :rtype: bytearray
# """
# if value < 0:
# raise ValueError('Value needs to be non-negative, got %r' % value)
#
# CONTINUATION_MARK = 0x80
# LEAST_MEANINGFUL_PART_MASK = 0x7f
# bits = value & LEAST_MEANINGFUL_PART_MASK
# value >>= 7
# ret = bytearray()
# while value:
# ret += int2byte(CONTINUATION_MARK | bits)
# bits = value & LEAST_MEANINGFUL_PART_MASK
# value >>= 7
# ret += int2byte(bits)
# return ret
. Output only the next line. | def test_uleb128_encode_fails_on_negative_number(): |
Predict the next line after this snippet: <|code_start|>def test_uleb128_decode_fails_on_invalid_input():
byte_array = uleb128_encode(12345678)
for i in xrange(len(byte_array)):
yield check_uleb128_decode_fails_on_invalid_input, byte_array[:i]
@raises(IncompleteULEB128)
def check_uleb128_decode_fails_on_invalid_input(input_):
uleb128_decode(input_)
def test_frame_encode():
for input_, output in (
(b'', b'\x00\x00\x00\x00'),
(b'a', b'\x01a\x00\x00'),
(b'ab', b'\x02ab\x00'),
(b'abc', b'\x03abc'),
(b'abcd', b'\x04abcd'),
):
yield check_frame_encode, bytearray(input_), output
def check_frame_encode(byte_array, output):
frame = bytearray()
frame_encode(frame, byte_array)
eq_(frame, output)
def test_frame_decode_all():
<|code_end|>
using the current file's imports:
from itertools import chain
from nose.tools import eq_, raises
from six.moves import xrange
from smarkets.streaming_api.framing import (
frame_decode_all, frame_encode, IncompleteULEB128, uleb128_decode, uleb128_encode,
)
and any relevant context from other files:
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
#
# def frame_encode(frame, payload):
# """
# Encodes payload and appends it to the given frame.
# :type frame: bytearray
# :type payload: byte string or bytearray
# """
# byte_count = len(payload)
# header = uleb128_encode(byte_count)
# padding = b'\x00' * max(0, MIN_FRAME_SIZE - len(header) - byte_count)
# frame += header
# frame += payload
# frame += padding
#
# class IncompleteULEB128(Exception):
# pass
#
# def uleb128_decode(to_decode):
# """
# :type to_decode: bytes
# :return: decoded value and number of bytes from `to_decode` used to decode it
# :rtype: tuple of (int or long) and int
# :raises:
# :IncompleteULEB128: when `to_decode` doesn't start with ULEB128-encoded number.
# """
# CONTINUATION_MARK = 0x80
# LEAST_MEANINGFUL_PART_MASK = 0x7f
#
# shift = 0
# result = 0
# position = 0
#
# while True:
# try:
# current_byte = to_decode[position]
# except IndexError:
# raise IncompleteULEB128('to_decode does not start with a ULEB128-encoded value')
# else:
# result |= ((current_byte & LEAST_MEANINGFUL_PART_MASK) << shift)
#
# if not current_byte & CONTINUATION_MARK:
# break
# else:
# shift += 7
# position += 1
#
# return result, position + 1
#
# def uleb128_encode(value):
# """Encode a non-negative int/long as a ULEB128 number.
#
# :type value: int or long
# :rtype: bytearray
# """
# if value < 0:
# raise ValueError('Value needs to be non-negative, got %r' % value)
#
# CONTINUATION_MARK = 0x80
# LEAST_MEANINGFUL_PART_MASK = 0x7f
# bits = value & LEAST_MEANINGFUL_PART_MASK
# value >>= 7
# ret = bytearray()
# while value:
# ret += int2byte(CONTINUATION_MARK | bits)
# bits = value & LEAST_MEANINGFUL_PART_MASK
# value >>= 7
# ret += int2byte(bits)
# return ret
. Output only the next line. | for input_, output in ( |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
try:
pickles = [pickle, cPickle]
except ImportError:
pickles = [pickle]
# This is namedtuple backported from CPython 2.7.5, it fixes http://bugs.python.org/issue15535
# Copyright © 2001-2014 Python Software Foundation; All Rights Reserved
TestNT = namedtuple('TestNT', 'x y z') # type used for pickle tests
py273_named_tuple_pickle = b'''\
ccopy_reg
_reconstructor
p0
(csmarkets.tests.collections
TestNT
p1
c__builtin__
tuple
p2
(I10
<|code_end|>
. Use current file imports:
import copy
import pickle
import unittest
import cPickle
import string
import random
from six import PY2
from smarkets.collections import namedtuple
and context (classes, functions, or code) from other files:
# Path: smarkets/collections.py
# def namedtuple(typename, field_names, verbose=False, rename=False):
# """Returns a new subclass of tuple with named fields.
#
# >>> Point = namedtuple('Point', ['x', 'y'])
# >>> Point.__doc__ # docstring for the new class
# 'Point(x, y)'
# >>> p = Point(11, y=22) # instantiate with positional args or keywords
# >>> p[0] + p[1] # indexable like a plain tuple
# 33
# >>> x, y = p # unpack like a regular tuple
# >>> x, y
# (11, 22)
# >>> p.x + p.y # fields also accessable by name
# 33
# >>> d = p._asdict() # convert to a dictionary
# >>> d['x']
# 11
# >>> Point(**d) # convert from a dictionary
# Point(x=11, y=22)
# >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
# Point(x=100, y=22)
#
# """
#
# # Validate the field names. At the user's option, either generate an error
# # message or automatically replace the field name with a valid name.
# if isinstance(field_names, string_types):
# field_names = field_names.replace(',', ' ').split()
# field_names = map(str, field_names)
# if rename:
# seen = set()
# for index, name in enumerate(field_names):
# if (not all(c.isalnum() or c == '_' for c in name) or
# _iskeyword(name) or
# not name or
# name[0].isdigit() or
# name.startswith('_') or
# name in seen):
# field_names[index] = '_%d' % index
# seen.add(name)
# for name in [typename] + field_names:
# if not all(c.isalnum() or c == '_' for c in name):
# raise ValueError('Type names and field names can only contain '
# 'alphanumeric characters and underscores: %r' % name)
# if _iskeyword(name):
# raise ValueError('Type names and field names cannot be a '
# 'keyword: %r' % name)
# if name[0].isdigit():
# raise ValueError('Type names and field names cannot start with '
# 'a number: %r' % name)
# seen = set()
# for name in field_names:
# if name.startswith('_') and not rename:
# raise ValueError('Field names cannot start with an underscore: '
# '%r' % name)
# if name in seen:
# raise ValueError('Encountered duplicate field name: %r' % name)
# seen.add(name)
#
# # Fill-in the class template
# class_definition = _class_template.format(
# typename=typename,
# field_names=tuple(field_names),
# num_fields=len(field_names),
# arg_list=repr(tuple(field_names)).replace("'", "")[1:-1],
# repr_fmt=', '.join(_repr_template.format(name=name)
# for name in field_names),
# field_defs='\n'.join(_field_template.format(index=index, name=name)
# for index, name in enumerate(field_names))
# )
# if verbose:
# print(class_definition)
#
# # Execute the template string in a temporary namespace and support
# # tracing utilities by setting a value for frame.f_globals['__name__']
# namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
# OrderedDict=OrderedDict, _property=property, _tuple=tuple)
# try:
# exec_(class_definition, namespace, namespace)
# except SyntaxError as e:
# raise SyntaxError(e.message + ':\n' + class_definition)
# result = namespace[typename]
#
# # For pickling to work, the __module__ variable needs to be set to the frame
# # where the named tuple is created. Bypass this step in environments where
# # sys._getframe is not defined (Jython for example) or sys._getframe is not
# # defined for arguments greater than 0 (IronPython).
# try:
# result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
# except (AttributeError, ValueError):
# pass
#
# return result
. Output only the next line. | I20 |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
class DateTests(unittest.TestCase):
def test_valid_iso_conversion(self):
valid_iso_dates = (
('2009-04-24T15:48:26,000000Z', datetime.datetime(2009, 0o4, 24, 15, 48, 26, 0)),
('2009-04-24T15:48:26', datetime.datetime(2009, 0o4, 24, 15, 48, 26, 0)),
('2009-04-24T15:48:26.000000Z', datetime.datetime(2009, 0o4, 24, 15, 48, 26, 0)),
)
for iso, real_date in valid_iso_dates:
result = parse_datetime(iso)
eq_(result, real_date, "Date %s didn't match %s" % (result, real_date))
def test_invalid_iso_conversion(self):
invalid_iso_dates = (
'gibberish',
)
for iso in invalid_iso_dates:
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import unittest
import iso8601
from nose.tools import assert_raises, eq_
from smarkets.datetime import parse_datetime
and context including class names, function names, and sometimes code from other files:
# Path: smarkets/datetime.py
# def parse_datetime(iso):
# """Convert ISO8601 formatted timestamp to timezone-naive, UTC-normalized datetime object."""
# iso = iso.replace(',', '.')
# return iso8601.parse_date(iso).astimezone(pytz.utc).replace(tzinfo=None)
. Output only the next line. | with assert_raises(iso8601.ParseError): |
Based on the snippet: <|code_start|>from __future__ import absolute_import, division, print_function, unicode_literals
__all__ = ('set_payload_message',)
def set_payload_message(payload, message):
underscore_form = camel_case_to_underscores(type(message).__name__)
payload_type = getattr(seto, 'PAYLOAD_' + underscore_form.upper())
<|code_end|>
, predict the immediate next line with the help of imports:
from smarkets.streaming_api import seto
from smarkets.string import camel_case_to_underscores
and context (classes, functions, sometimes code) from other files:
# Path: smarkets/streaming_api/seto.py
#
# Path: smarkets/string.py
# def camel_case_to_underscores(name):
# return _camel_case_re.sub(r'_\1', name).lower().strip('_')
. Output only the next line. | payload.type = payload_type |
Given the following code snippet before the placeholder: <|code_start|> def test_login_ok(self):
"Test the `Smarkets.login` method"
self.client.session.next_frame = read_session_buff_gen(SUCCESSFUL_LOGIN_RESPONSE_RAW)
self.client.login()
self.assertTrue(self.client.check_login())
def test_login_ok_async(self):
"Test the `Smarkets.login` method"
self.client.login(False)
self.client.session.next_frame = read_session_buff_gen(
SUCCESSFUL_LOGIN_RESPONSE_RAW +
PAYLOAD_THROTTLE_LIMITS_RAW +
PAYLOAD_THROTTLE_LIMITS_RAW)
self.client.read()
self.assertTrue(self.client.check_login())
def test_login_unauthorized(self):
"Test the `Smarkets.login` method for unauthorized"
self.client.session.next_frame = read_session_buff_gen(UNAUTHORIZED_LOGIN_RESPONSE_RAW)
try:
self.client.login()
except LoginError as ex:
self.mock_session.disconnect.assert_called_once()
self.assertEquals(eto.LOGOUT_UNAUTHORISED, ex.reason)
self.assertEquals(ex.reason_msg, 'LOGOUT_UNAUTHORISED')
return
assert False
def test_login_ok_then_timeout(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import six
from collections import namedtuple
from itertools import chain, product
from mock import patch
from nose.tools import eq_
from six.moves import xrange
from smarkets import uuid
from smarkets.streaming_api.api import eto, InvalidCallbackError, seto, StreamingAPIClient
from smarkets.streaming_api.exceptions import LoginError, LoginTimeout
from smarkets.streaming_api.framing import frame_decode_all
and context including class names, function names, and sometimes code from other files:
# Path: smarkets/uuid.py
# class UuidTag(UuidTagBase): # pylint: disable=E1001
# class Uuid(UuidBase): # pylint: disable=E1001
# def hex_str(self):
# def tag_number(self, number):
# def split_int_tag(cls, number):
# def low(self):
# def high(self):
# def shorthex(self):
# def to_slug(self, prefix=True, base=36, chars=None, pad=0):
# def to_hex(self, pad=32):
# def base_n(number, chars):
# def pad_uuid(uuid, pad=32, padchar='0'):
# def unsplit64(cls, high, low):
# def from_int(cls, number, ttype):
# def from_slug(cls, slug, base=36, chars=None):
# def from_hex(cls, hex_str):
# def int_to_slug(number, ttype):
# def slug_to_int(slug, return_tag=None, split=False):
# def uuid_to_slug(number, prefix=True):
# def slug_to_uuid(slug):
# def int_to_uuid(number, ttype):
# def uuid_to_int(uuid, return_tag=None, split=False):
# def uid_or_int_to_int(value, expected_type):
# def uuid_to_short(uuid):
# TAGS = (
# UuidTag('Account', int('acc1', 16), 'a'),
# UuidTag('ContractGroup', int('c024', 16), 'm'),
# UuidTag('Contract', int('cccc', 16), 'c'),
# UuidTag('Order', int('fff0', 16), 'o'),
# UuidTag('Comment', int('b1a4', 16), 'b'),
# UuidTag('Entity', int('0444', 16), 'n'),
# UuidTag('Event', int('1100', 16), 'e'),
# UuidTag('Session', int('9999', 16), 's'),
# UuidTag('User', int('0f00', 16), 'u'),
# UuidTag('Referrer', int('4e4e', 16), 'r'),
# )
#
# Path: smarkets/streaming_api/api.py
# SIDE_BID = seto.SIDE_BUY
# SIDE_OFFER = seto.SIDE_SELL
#
# Path: smarkets/streaming_api/exceptions.py
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
. Output only the next line. | "Test the `Smarkets.login` method for a sequence of messages" |
Given the following code snippet before the placeholder: <|code_start|> ValueError, self.client.add_handler, 'eto.pong', bad_handler)
self.assertRaises(
ValueError, self.client.add_global_handler, bad_handler)
def test_add_unknown_handler(self):
"Test trying to add a handler for an unknown callback name"
handler = lambda: None
self.assertRaises(
InvalidCallbackError, self.client.add_handler, 'foo', handler)
self.assertRaises(
InvalidCallbackError, self.client.del_handler, 'foo', handler)
@staticmethod
def _login_response():
"Create a dummy login response payload"
payload = seto.Payload()
payload.eto_payload.seq = 1
payload.eto_payload.type = eto.PAYLOAD_LOGIN_RESPONSE
payload.eto_payload.login_response.session = 'session'
payload.eto_payload.login_response.reset = 2
return payload
class UuidTestCase(unittest.TestCase):
"Unit tests for Uuids"
def test_int_roundtrip(self):
"Test converting an integer to a Uuid and back"
ttype = 'Account'
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import six
from collections import namedtuple
from itertools import chain, product
from mock import patch
from nose.tools import eq_
from six.moves import xrange
from smarkets import uuid
from smarkets.streaming_api.api import eto, InvalidCallbackError, seto, StreamingAPIClient
from smarkets.streaming_api.exceptions import LoginError, LoginTimeout
from smarkets.streaming_api.framing import frame_decode_all
and context including class names, function names, and sometimes code from other files:
# Path: smarkets/uuid.py
# class UuidTag(UuidTagBase): # pylint: disable=E1001
# class Uuid(UuidBase): # pylint: disable=E1001
# def hex_str(self):
# def tag_number(self, number):
# def split_int_tag(cls, number):
# def low(self):
# def high(self):
# def shorthex(self):
# def to_slug(self, prefix=True, base=36, chars=None, pad=0):
# def to_hex(self, pad=32):
# def base_n(number, chars):
# def pad_uuid(uuid, pad=32, padchar='0'):
# def unsplit64(cls, high, low):
# def from_int(cls, number, ttype):
# def from_slug(cls, slug, base=36, chars=None):
# def from_hex(cls, hex_str):
# def int_to_slug(number, ttype):
# def slug_to_int(slug, return_tag=None, split=False):
# def uuid_to_slug(number, prefix=True):
# def slug_to_uuid(slug):
# def int_to_uuid(number, ttype):
# def uuid_to_int(uuid, return_tag=None, split=False):
# def uid_or_int_to_int(value, expected_type):
# def uuid_to_short(uuid):
# TAGS = (
# UuidTag('Account', int('acc1', 16), 'a'),
# UuidTag('ContractGroup', int('c024', 16), 'm'),
# UuidTag('Contract', int('cccc', 16), 'c'),
# UuidTag('Order', int('fff0', 16), 'o'),
# UuidTag('Comment', int('b1a4', 16), 'b'),
# UuidTag('Entity', int('0444', 16), 'n'),
# UuidTag('Event', int('1100', 16), 'e'),
# UuidTag('Session', int('9999', 16), 's'),
# UuidTag('User', int('0f00', 16), 'u'),
# UuidTag('Referrer', int('4e4e', 16), 'r'),
# )
#
# Path: smarkets/streaming_api/api.py
# SIDE_BID = seto.SIDE_BUY
# SIDE_OFFER = seto.SIDE_SELL
#
# Path: smarkets/streaming_api/exceptions.py
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
. Output only the next line. | for i in chain(xrange(1, 1000), product(xrange(1, 10), repeat=2)): |
Next line prediction: <|code_start|> "Create a dummy login response payload"
payload = seto.Payload()
payload.eto_payload.seq = 1
payload.eto_payload.type = eto.PAYLOAD_LOGIN_RESPONSE
payload.eto_payload.login_response.session = 'session'
payload.eto_payload.login_response.reset = 2
return payload
class UuidTestCase(unittest.TestCase):
"Unit tests for Uuids"
def test_int_roundtrip(self):
"Test converting an integer to a Uuid and back"
ttype = 'Account'
for i in chain(xrange(1, 1000), product(xrange(1, 10), repeat=2)):
u1 = uuid.int_to_uuid(i, ttype)
u2, test_ttype = uuid.uuid_to_int(u1, return_tag='type', split=isinstance(i, tuple))
self.assertEquals(i, u2)
self.assertEquals(test_ttype, ttype)
u3 = uuid.int_to_slug(i, ttype)
u4, test_ttype = uuid.slug_to_int(u3, return_tag='type', split=isinstance(i, tuple))
self.assertEquals(i, u4)
self.assertEquals(test_ttype, ttype)
def test_uuid_roundtrip(self):
"Test converting a hex string to a Uuid and back"
suffix = 'acc1'
for i in xrange(1, 1000):
<|code_end|>
. Use current file imports:
(import unittest
import six
from collections import namedtuple
from itertools import chain, product
from mock import patch
from nose.tools import eq_
from six.moves import xrange
from smarkets import uuid
from smarkets.streaming_api.api import eto, InvalidCallbackError, seto, StreamingAPIClient
from smarkets.streaming_api.exceptions import LoginError, LoginTimeout
from smarkets.streaming_api.framing import frame_decode_all)
and context including class names, function names, or small code snippets from other files:
# Path: smarkets/uuid.py
# class UuidTag(UuidTagBase): # pylint: disable=E1001
# class Uuid(UuidBase): # pylint: disable=E1001
# def hex_str(self):
# def tag_number(self, number):
# def split_int_tag(cls, number):
# def low(self):
# def high(self):
# def shorthex(self):
# def to_slug(self, prefix=True, base=36, chars=None, pad=0):
# def to_hex(self, pad=32):
# def base_n(number, chars):
# def pad_uuid(uuid, pad=32, padchar='0'):
# def unsplit64(cls, high, low):
# def from_int(cls, number, ttype):
# def from_slug(cls, slug, base=36, chars=None):
# def from_hex(cls, hex_str):
# def int_to_slug(number, ttype):
# def slug_to_int(slug, return_tag=None, split=False):
# def uuid_to_slug(number, prefix=True):
# def slug_to_uuid(slug):
# def int_to_uuid(number, ttype):
# def uuid_to_int(uuid, return_tag=None, split=False):
# def uid_or_int_to_int(value, expected_type):
# def uuid_to_short(uuid):
# TAGS = (
# UuidTag('Account', int('acc1', 16), 'a'),
# UuidTag('ContractGroup', int('c024', 16), 'm'),
# UuidTag('Contract', int('cccc', 16), 'c'),
# UuidTag('Order', int('fff0', 16), 'o'),
# UuidTag('Comment', int('b1a4', 16), 'b'),
# UuidTag('Entity', int('0444', 16), 'n'),
# UuidTag('Event', int('1100', 16), 'e'),
# UuidTag('Session', int('9999', 16), 's'),
# UuidTag('User', int('0f00', 16), 'u'),
# UuidTag('Referrer', int('4e4e', 16), 'r'),
# )
#
# Path: smarkets/streaming_api/api.py
# SIDE_BID = seto.SIDE_BUY
# SIDE_OFFER = seto.SIDE_SELL
#
# Path: smarkets/streaming_api/exceptions.py
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
. Output only the next line. | hex_str = '%x%s' % (i, suffix) |
Given the code snippet: <|code_start|> self.assertRaises(
ValueError, self.client.add_handler, 'eto.pong', bad_handler)
self.assertRaises(
ValueError, self.client.add_global_handler, bad_handler)
def test_add_unknown_handler(self):
"Test trying to add a handler for an unknown callback name"
handler = lambda: None
self.assertRaises(
InvalidCallbackError, self.client.add_handler, 'foo', handler)
self.assertRaises(
InvalidCallbackError, self.client.del_handler, 'foo', handler)
@staticmethod
def _login_response():
"Create a dummy login response payload"
payload = seto.Payload()
payload.eto_payload.seq = 1
payload.eto_payload.type = eto.PAYLOAD_LOGIN_RESPONSE
payload.eto_payload.login_response.session = 'session'
payload.eto_payload.login_response.reset = 2
return payload
class UuidTestCase(unittest.TestCase):
"Unit tests for Uuids"
def test_int_roundtrip(self):
"Test converting an integer to a Uuid and back"
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import six
from collections import namedtuple
from itertools import chain, product
from mock import patch
from nose.tools import eq_
from six.moves import xrange
from smarkets import uuid
from smarkets.streaming_api.api import eto, InvalidCallbackError, seto, StreamingAPIClient
from smarkets.streaming_api.exceptions import LoginError, LoginTimeout
from smarkets.streaming_api.framing import frame_decode_all
and context (functions, classes, or occasionally code) from other files:
# Path: smarkets/uuid.py
# class UuidTag(UuidTagBase): # pylint: disable=E1001
# class Uuid(UuidBase): # pylint: disable=E1001
# def hex_str(self):
# def tag_number(self, number):
# def split_int_tag(cls, number):
# def low(self):
# def high(self):
# def shorthex(self):
# def to_slug(self, prefix=True, base=36, chars=None, pad=0):
# def to_hex(self, pad=32):
# def base_n(number, chars):
# def pad_uuid(uuid, pad=32, padchar='0'):
# def unsplit64(cls, high, low):
# def from_int(cls, number, ttype):
# def from_slug(cls, slug, base=36, chars=None):
# def from_hex(cls, hex_str):
# def int_to_slug(number, ttype):
# def slug_to_int(slug, return_tag=None, split=False):
# def uuid_to_slug(number, prefix=True):
# def slug_to_uuid(slug):
# def int_to_uuid(number, ttype):
# def uuid_to_int(uuid, return_tag=None, split=False):
# def uid_or_int_to_int(value, expected_type):
# def uuid_to_short(uuid):
# TAGS = (
# UuidTag('Account', int('acc1', 16), 'a'),
# UuidTag('ContractGroup', int('c024', 16), 'm'),
# UuidTag('Contract', int('cccc', 16), 'c'),
# UuidTag('Order', int('fff0', 16), 'o'),
# UuidTag('Comment', int('b1a4', 16), 'b'),
# UuidTag('Entity', int('0444', 16), 'n'),
# UuidTag('Event', int('1100', 16), 'e'),
# UuidTag('Session', int('9999', 16), 's'),
# UuidTag('User', int('0f00', 16), 'u'),
# UuidTag('Referrer', int('4e4e', 16), 'r'),
# )
#
# Path: smarkets/streaming_api/api.py
# SIDE_BID = seto.SIDE_BUY
# SIDE_OFFER = seto.SIDE_SELL
#
# Path: smarkets/streaming_api/exceptions.py
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
. Output only the next line. | ttype = 'Account' |
Here is a snippet: <|code_start|> client_a.add_handler('seto.order_accepted', handler)
eq_(handler.call_count, 0)
client_a.callbacks['seto.order_accepted'](message='irrelevant')
eq_(handler.call_count, 1)
client_b.callbacks['seto.order_accepted'](message='also irrelevant')
eq_(handler.call_count, 1)
def test_add_bad_handler(self):
"Test trying to add a bad handler either as a global or normal"
for bad_handler in (
50, 'foo', False, True, u'foo', 1.2, 1):
self.assertRaises(
ValueError, self.client.add_handler, 'eto.pong', bad_handler)
self.assertRaises(
ValueError, self.client.add_global_handler, bad_handler)
def test_add_unknown_handler(self):
"Test trying to add a handler for an unknown callback name"
handler = lambda: None
self.assertRaises(
InvalidCallbackError, self.client.add_handler, 'foo', handler)
self.assertRaises(
InvalidCallbackError, self.client.del_handler, 'foo', handler)
@staticmethod
def _login_response():
"Create a dummy login response payload"
payload = seto.Payload()
<|code_end|>
. Write the next line using the current file imports:
import unittest
import six
from collections import namedtuple
from itertools import chain, product
from mock import patch
from nose.tools import eq_
from six.moves import xrange
from smarkets import uuid
from smarkets.streaming_api.api import eto, InvalidCallbackError, seto, StreamingAPIClient
from smarkets.streaming_api.exceptions import LoginError, LoginTimeout
from smarkets.streaming_api.framing import frame_decode_all
and context from other files:
# Path: smarkets/uuid.py
# class UuidTag(UuidTagBase): # pylint: disable=E1001
# class Uuid(UuidBase): # pylint: disable=E1001
# def hex_str(self):
# def tag_number(self, number):
# def split_int_tag(cls, number):
# def low(self):
# def high(self):
# def shorthex(self):
# def to_slug(self, prefix=True, base=36, chars=None, pad=0):
# def to_hex(self, pad=32):
# def base_n(number, chars):
# def pad_uuid(uuid, pad=32, padchar='0'):
# def unsplit64(cls, high, low):
# def from_int(cls, number, ttype):
# def from_slug(cls, slug, base=36, chars=None):
# def from_hex(cls, hex_str):
# def int_to_slug(number, ttype):
# def slug_to_int(slug, return_tag=None, split=False):
# def uuid_to_slug(number, prefix=True):
# def slug_to_uuid(slug):
# def int_to_uuid(number, ttype):
# def uuid_to_int(uuid, return_tag=None, split=False):
# def uid_or_int_to_int(value, expected_type):
# def uuid_to_short(uuid):
# TAGS = (
# UuidTag('Account', int('acc1', 16), 'a'),
# UuidTag('ContractGroup', int('c024', 16), 'm'),
# UuidTag('Contract', int('cccc', 16), 'c'),
# UuidTag('Order', int('fff0', 16), 'o'),
# UuidTag('Comment', int('b1a4', 16), 'b'),
# UuidTag('Entity', int('0444', 16), 'n'),
# UuidTag('Event', int('1100', 16), 'e'),
# UuidTag('Session', int('9999', 16), 's'),
# UuidTag('User', int('0f00', 16), 'u'),
# UuidTag('Referrer', int('4e4e', 16), 'r'),
# )
#
# Path: smarkets/streaming_api/api.py
# SIDE_BID = seto.SIDE_BUY
# SIDE_OFFER = seto.SIDE_SELL
#
# Path: smarkets/streaming_api/exceptions.py
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
, which may include functions, classes, or code. Output only the next line. | payload.eto_payload.seq = 1 |
Next line prediction: <|code_start|>from __future__ import absolute_import
SUCCESSFUL_LOGIN_RESPONSE_RAW = bytearray(
b'@\x08\x01\x12<\x08\x01\x10\x08\x18\x0024\n\x129RK4DpIK9HY5FpZKTo\x10\x02\x1a\x13hanson'
b'@smarkets.com \x93\xa7\xb1\xc5\xa9\xa6\xd2\x18\x14\x08$\x12\x04\x08\x02\x18\x00\xaa\x02'
b'\t\x08\xf4\x03\x10\xe8\x07\x18\xc8\x01\n\x08\x01\x12\x06\x08\x03\x10\x05\x18\x00\n\x08'
b'\x01\x12\x06\x08\x04\x10\x05\x18\x00')
UNAUTHORIZED_LOGIN_RESPONSE_RAW = bytearray(
b'\x0e\x08\x01\x12\n\x08\x01\x10\t\x18\x00:\x02\x08\x07')
PAYLOAD_THROTTLE_LIMITS_RAW = bytearray(
b'\x14\x08$\x12\x04\x08\x02\x18\x00\xaa\x02\t\x08\xf4\x03\x10\xe8\x07\x18\xc8\x01')
LOGOUT_HEARTBEAT_TIMEOUT_RAW = bytearray(
b'\x0e\x08\x01\x12\n\x08\x08\x10\t\x18\x00:\x02\x08\x02')
class Frame(namedtuple('Frame', 'bytes protobuf')):
pass
def read_session_buff_gen(raw_response):
buffers = []
if raw_response:
decoded_response, dummy = frame_decode_all(raw_response)
for data in decoded_response:
payload = seto.Payload()
<|code_end|>
. Use current file imports:
(import unittest
import six
from collections import namedtuple
from itertools import chain, product
from mock import patch
from nose.tools import eq_
from six.moves import xrange
from smarkets import uuid
from smarkets.streaming_api.api import eto, InvalidCallbackError, seto, StreamingAPIClient
from smarkets.streaming_api.exceptions import LoginError, LoginTimeout
from smarkets.streaming_api.framing import frame_decode_all)
and context including class names, function names, or small code snippets from other files:
# Path: smarkets/uuid.py
# class UuidTag(UuidTagBase): # pylint: disable=E1001
# class Uuid(UuidBase): # pylint: disable=E1001
# def hex_str(self):
# def tag_number(self, number):
# def split_int_tag(cls, number):
# def low(self):
# def high(self):
# def shorthex(self):
# def to_slug(self, prefix=True, base=36, chars=None, pad=0):
# def to_hex(self, pad=32):
# def base_n(number, chars):
# def pad_uuid(uuid, pad=32, padchar='0'):
# def unsplit64(cls, high, low):
# def from_int(cls, number, ttype):
# def from_slug(cls, slug, base=36, chars=None):
# def from_hex(cls, hex_str):
# def int_to_slug(number, ttype):
# def slug_to_int(slug, return_tag=None, split=False):
# def uuid_to_slug(number, prefix=True):
# def slug_to_uuid(slug):
# def int_to_uuid(number, ttype):
# def uuid_to_int(uuid, return_tag=None, split=False):
# def uid_or_int_to_int(value, expected_type):
# def uuid_to_short(uuid):
# TAGS = (
# UuidTag('Account', int('acc1', 16), 'a'),
# UuidTag('ContractGroup', int('c024', 16), 'm'),
# UuidTag('Contract', int('cccc', 16), 'c'),
# UuidTag('Order', int('fff0', 16), 'o'),
# UuidTag('Comment', int('b1a4', 16), 'b'),
# UuidTag('Entity', int('0444', 16), 'n'),
# UuidTag('Event', int('1100', 16), 'e'),
# UuidTag('Session', int('9999', 16), 's'),
# UuidTag('User', int('0f00', 16), 'u'),
# UuidTag('Referrer', int('4e4e', 16), 'r'),
# )
#
# Path: smarkets/streaming_api/api.py
# SIDE_BID = seto.SIDE_BUY
# SIDE_OFFER = seto.SIDE_SELL
#
# Path: smarkets/streaming_api/exceptions.py
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
. Output only the next line. | payload.ParseFromString(bytes(data)) |
Using the snippet: <|code_start|> except LoginError as ex:
self.mock_session.disconnect.assert_called_once()
self.assertEquals(eto.LOGOUT_HEARTBEAT_TIMEOUT, ex.reason)
self.assertEquals(ex.reason_msg, 'LOGOUT_HEARTBEAT_TIMEOUT')
return
assert False
def test_login_noresponse(self):
"Test the `Smarkets.login` when no login response has been received"
self.client.session.next_frame = read_session_buff_gen('')
try:
self.client.login()
except LoginTimeout:
return
assert False
def test_logout_norecv(self):
"Test the `Smarkets.logout` method"
self.client.logout(False)
self.assertEquals(
self.mock_session.method_calls,
[('logout', (), {}),
('disconnect', (), {})])
def test_each_instance_has_separate_callbacks(self):
client_a, client_b = (StreamingAPIClient('_') for i in range(2))
handler = Handler()
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import six
from collections import namedtuple
from itertools import chain, product
from mock import patch
from nose.tools import eq_
from six.moves import xrange
from smarkets import uuid
from smarkets.streaming_api.api import eto, InvalidCallbackError, seto, StreamingAPIClient
from smarkets.streaming_api.exceptions import LoginError, LoginTimeout
from smarkets.streaming_api.framing import frame_decode_all
and context (class names, function names, or code) available:
# Path: smarkets/uuid.py
# class UuidTag(UuidTagBase): # pylint: disable=E1001
# class Uuid(UuidBase): # pylint: disable=E1001
# def hex_str(self):
# def tag_number(self, number):
# def split_int_tag(cls, number):
# def low(self):
# def high(self):
# def shorthex(self):
# def to_slug(self, prefix=True, base=36, chars=None, pad=0):
# def to_hex(self, pad=32):
# def base_n(number, chars):
# def pad_uuid(uuid, pad=32, padchar='0'):
# def unsplit64(cls, high, low):
# def from_int(cls, number, ttype):
# def from_slug(cls, slug, base=36, chars=None):
# def from_hex(cls, hex_str):
# def int_to_slug(number, ttype):
# def slug_to_int(slug, return_tag=None, split=False):
# def uuid_to_slug(number, prefix=True):
# def slug_to_uuid(slug):
# def int_to_uuid(number, ttype):
# def uuid_to_int(uuid, return_tag=None, split=False):
# def uid_or_int_to_int(value, expected_type):
# def uuid_to_short(uuid):
# TAGS = (
# UuidTag('Account', int('acc1', 16), 'a'),
# UuidTag('ContractGroup', int('c024', 16), 'm'),
# UuidTag('Contract', int('cccc', 16), 'c'),
# UuidTag('Order', int('fff0', 16), 'o'),
# UuidTag('Comment', int('b1a4', 16), 'b'),
# UuidTag('Entity', int('0444', 16), 'n'),
# UuidTag('Event', int('1100', 16), 'e'),
# UuidTag('Session', int('9999', 16), 's'),
# UuidTag('User', int('0f00', 16), 'u'),
# UuidTag('Referrer', int('4e4e', 16), 'r'),
# )
#
# Path: smarkets/streaming_api/api.py
# SIDE_BID = seto.SIDE_BUY
# SIDE_OFFER = seto.SIDE_SELL
#
# Path: smarkets/streaming_api/exceptions.py
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
. Output only the next line. | client_a.add_handler('seto.order_accepted', handler) |
Given snippet: <|code_start|>from __future__ import absolute_import
SUCCESSFUL_LOGIN_RESPONSE_RAW = bytearray(
b'@\x08\x01\x12<\x08\x01\x10\x08\x18\x0024\n\x129RK4DpIK9HY5FpZKTo\x10\x02\x1a\x13hanson'
b'@smarkets.com \x93\xa7\xb1\xc5\xa9\xa6\xd2\x18\x14\x08$\x12\x04\x08\x02\x18\x00\xaa\x02'
b'\t\x08\xf4\x03\x10\xe8\x07\x18\xc8\x01\n\x08\x01\x12\x06\x08\x03\x10\x05\x18\x00\n\x08'
b'\x01\x12\x06\x08\x04\x10\x05\x18\x00')
UNAUTHORIZED_LOGIN_RESPONSE_RAW = bytearray(
b'\x0e\x08\x01\x12\n\x08\x01\x10\t\x18\x00:\x02\x08\x07')
PAYLOAD_THROTTLE_LIMITS_RAW = bytearray(
b'\x14\x08$\x12\x04\x08\x02\x18\x00\xaa\x02\t\x08\xf4\x03\x10\xe8\x07\x18\xc8\x01')
LOGOUT_HEARTBEAT_TIMEOUT_RAW = bytearray(
b'\x0e\x08\x01\x12\n\x08\x08\x10\t\x18\x00:\x02\x08\x02')
class Frame(namedtuple('Frame', 'bytes protobuf')):
pass
def read_session_buff_gen(raw_response):
buffers = []
if raw_response:
decoded_response, dummy = frame_decode_all(raw_response)
for data in decoded_response:
payload = seto.Payload()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import six
from collections import namedtuple
from itertools import chain, product
from mock import patch
from nose.tools import eq_
from six.moves import xrange
from smarkets import uuid
from smarkets.streaming_api.api import eto, InvalidCallbackError, seto, StreamingAPIClient
from smarkets.streaming_api.exceptions import LoginError, LoginTimeout
from smarkets.streaming_api.framing import frame_decode_all
and context:
# Path: smarkets/uuid.py
# class UuidTag(UuidTagBase): # pylint: disable=E1001
# class Uuid(UuidBase): # pylint: disable=E1001
# def hex_str(self):
# def tag_number(self, number):
# def split_int_tag(cls, number):
# def low(self):
# def high(self):
# def shorthex(self):
# def to_slug(self, prefix=True, base=36, chars=None, pad=0):
# def to_hex(self, pad=32):
# def base_n(number, chars):
# def pad_uuid(uuid, pad=32, padchar='0'):
# def unsplit64(cls, high, low):
# def from_int(cls, number, ttype):
# def from_slug(cls, slug, base=36, chars=None):
# def from_hex(cls, hex_str):
# def int_to_slug(number, ttype):
# def slug_to_int(slug, return_tag=None, split=False):
# def uuid_to_slug(number, prefix=True):
# def slug_to_uuid(slug):
# def int_to_uuid(number, ttype):
# def uuid_to_int(uuid, return_tag=None, split=False):
# def uid_or_int_to_int(value, expected_type):
# def uuid_to_short(uuid):
# TAGS = (
# UuidTag('Account', int('acc1', 16), 'a'),
# UuidTag('ContractGroup', int('c024', 16), 'm'),
# UuidTag('Contract', int('cccc', 16), 'c'),
# UuidTag('Order', int('fff0', 16), 'o'),
# UuidTag('Comment', int('b1a4', 16), 'b'),
# UuidTag('Entity', int('0444', 16), 'n'),
# UuidTag('Event', int('1100', 16), 'e'),
# UuidTag('Session', int('9999', 16), 's'),
# UuidTag('User', int('0f00', 16), 'u'),
# UuidTag('Referrer', int('4e4e', 16), 'r'),
# )
#
# Path: smarkets/streaming_api/api.py
# SIDE_BID = seto.SIDE_BUY
# SIDE_OFFER = seto.SIDE_SELL
#
# Path: smarkets/streaming_api/exceptions.py
# class LoginError(_Error):
#
# "Raised when a login is not successful"
# def __init__(self, reason):
# self.reason_msg = 'Unknown'
# self.reason = reason
# if reason in LogoutReason.values():
# self.reason_msg = LogoutReason.Name(reason)
#
# class LoginTimeout(_Error):
#
# "Raised when no message is received after sending login request"
# pass
#
# Path: smarkets/streaming_api/framing.py
# def frame_decode_all(to_decode):
# """
# :type to_decode: bytes
# :rtype: tuple (list of bytes, remaining bytes)
# """
# payloads = []
# while len(to_decode) >= MIN_FRAME_SIZE:
# try:
# decoded = uleb128_decode(to_decode)
# except IncompleteULEB128:
# # There may be not enough data in the input to decode the header
# break
# else:
# payload_size, header_size = decoded
# frame_size = max(payload_size + header_size, MIN_FRAME_SIZE)
# if len(to_decode) >= frame_size:
# frame, to_decode = to_decode[:frame_size], to_decode[frame_size:]
# payloads.append(frame[header_size:header_size + payload_size])
# else:
# break
#
# return payloads, to_decode
which might include code, classes, or functions. Output only the next line. | payload.ParseFromString(bytes(data)) |
Given snippet: <|code_start|>from __future__ import absolute_import
def throw_or_return(to_raise=None, to_return=None):
if to_raise:
raise to_raise # pylint: disable=E0702
if to_return:
return to_return
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from nose.tools import eq_, raises
from smarkets.errors import swallow
and context:
# Path: smarkets/errors.py
# def swallow(exceptions, default=None):
# '''
# Swallow exception(s) when executing something. Works as function decorator and
# as a context manager:
#
# >>> @swallow(NameError, default=2)
# ... def fun():
# ... a = b # noqa
# ... return 1
# ...
# >>> fun()
# 2
# >>> with swallow(KeyError):
# ... raise KeyError('key')
# ...
#
# :type exceptions: iterable of Exception or Exception
# :param default: value to return in case of an exception
# '''
# if isinstance(exceptions, type):
# exceptions = (exceptions,)
# else:
# exceptions = tuple(exceptions)
#
# return _SwallowHandler(exceptions, default)
which might include code, classes, or functions. Output only the next line. | class TestSwallow(object): |
Here is a snippet: <|code_start|> pass
class ParseError(_Error):
"Error parsing a message or frame"
pass
class SocketDisconnected(_Error):
"Socket was disconnected while reading"
pass
class InvalidCallbackError(_Error):
"Invalid callback was specified"
pass
class InvalidUrlError(_Error):
"Raised when a URL is invalid"
pass
class DownloadError(_Error):
"Raised when a URL could not be fetched"
<|code_end|>
. Write the next line using the current file imports:
from smarkets.errors import Error as _Error
from smarkets.streaming_api.eto import LogoutReason
and context from other files:
# Path: smarkets/errors.py
# class Error(Exception):
#
# "Base class for every Smarkets error"
#
# Path: smarkets/streaming_api/eto.py
, which may include functions, classes, or code. Output only the next line. | pass |
Predict the next line after this snippet: <|code_start|>"Core Smarkets API exceptions"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
class ConnectionError(_Error):
"TCP connection-related error"
pass
class DecodeError(_Error):
"Header decoding error"
pass
class ParseError(_Error):
"Error parsing a message or frame"
pass
class SocketDisconnected(_Error):
<|code_end|>
using the current file's imports:
from smarkets.errors import Error as _Error
from smarkets.streaming_api.eto import LogoutReason
and any relevant context from other files:
# Path: smarkets/errors.py
# class Error(Exception):
#
# "Base class for every Smarkets error"
#
# Path: smarkets/streaming_api/eto.py
. Output only the next line. | "Socket was disconnected while reading" |
Based on the snippet: <|code_start|>
def test_snap_to_decimal_buy():
eq_(Decimal('18.87'), Odds.snap_to_decimal('buy', Decimal('18.6')).percent)
def test_snap_to_decimal_sell():
eq_(Decimal('18.52'), Odds.snap_to_decimal('sell', Decimal('18.6')).percent)
<|code_end|>
, predict the immediate next line with the help of imports:
from decimal import Decimal
from nose.tools.trivial import eq_
from smarkets.odds import Odds
and context (classes, functions, sometimes code) from other files:
# Path: smarkets/odds.py
# class Odds(object):
# __slots__ = ('percent',)
#
# __repr__ = slots_repr
#
# def __init__(self, percent):
# """
# :type percent: :class:`decimal.Decimal`
# """
# self.percent = percent
#
# @property
# def percent_str(self):
# percent = self.percent / 100
#
# # TODO: This forces a locale of GB
# return format_percent(percent, "#,##0.##%", locale="en_GB")
#
# @property
# def fractional(self):
# previous = TABLE.from_percent(self.percent)
# return (previous.numerator, previous.denominator)
#
# @property
# def fractional_str(self):
# # Common Fractional idiom for 1 to 1 is 'Evens'
# if self.fractional[0] == self.fractional[1]:
# return 'Evens'
# return '%s to %s' % self.fractional
#
# @property
# def decimal(self):
# # Takes a percentage price and returns the appropriate decimal odds
# # we don't snap any more
# try:
# value = _PCT_TO_DEC[self.percent]
# except KeyError:
# value = ONE_HUNDRED / self.percent
# return value
#
# @classmethod
# def snap_to_decimal(cls, side, odds):
# """Take a percent and snap it to the nearest equal or worse decimal price based on side.
#
# .. note::
#
# Equal or worse means equal or higher when buying and equal or lower when selling.
#
# >>> Odds.snap_to_decimal('buy', Decimal('0.3')).percent
# Decimal('0.33')
# >>> Odds.snap_to_decimal('sell', Decimal('0.3')).percent
# Decimal('0.20')
#
# :type side: 'buy' or 'sell' string
# :type odds: :class:`decimal.Decimal`
# :rtype: :class:`Odds`
# """
# return Odds.snap_to_decimal_move_out_by(side, odds, 0)
#
# @classmethod
# def snap_to_decimal_move_out_by(cls, side, odds, move_out_by):
# decimal = cls(odds).decimal
# snapped = False
# if side == 'buy':
# i = bisect.bisect_right(_DEC_TO_PCT_KEYS, decimal)
# if i - 1 - move_out_by >= 0:
# snapped = cls(_DEC_TO_PCT[_DEC_TO_PCT_KEYS[i - 1 - move_out_by]])
# elif side == 'sell':
# i = bisect.bisect_left(_DEC_TO_PCT_KEYS, decimal)
# if i + move_out_by < len(_DEC_TO_PCT_KEYS):
# snapped = cls(_DEC_TO_PCT[_DEC_TO_PCT_KEYS[i + move_out_by]])
# if not snapped:
# return None
# return snapped
#
# @property
# def decimal_str(self):
# output = str(self.decimal)
# output = re.sub('(\.[0-9])0+$', '\\1', output)
# return output
#
# @property
# def american(self):
# if self.percent < Decimal(50):
# return (Decimal(10000) / self.percent - Decimal(100)).quantize(Decimal(1))
# return (Decimal(-100) / (Decimal(100) / self.percent - Decimal(1))).quantize(Decimal(1))
#
# @property
# def american_str(self):
# amer = self.american
# return '+%s' % amer if amer > 0 else '%s' % amer
#
# @classmethod
# def from_american(cls, snap, american):
# if not isinstance(american, Decimal):
# raise Exception("American odds needs to be a Decimal object")
# if american < 0:
# return cls((Decimal(100) / (Decimal(-100) / american + 1)).quantize(QUANT))
# return cls((Decimal(10000) / (american + Decimal(100))).quantize(QUANT))
#
# @classmethod
# def from_decimal(cls, snap, dec):
# if Decimal(dec) in _DEC_TO_PCT:
# return cls(_DEC_TO_PCT[Decimal(dec)])
# else:
# pct = (ONE_HUNDRED / dec).quantize(QUANT)
# return cls(pct)
# raise ValueError
#
# @classmethod
# def from_fractional(cls, num, den):
# dec = Decimal(num) / Decimal(den) + Decimal(1)
# return cls((Decimal(100) / dec).quantize(QUANT))
#
# @classmethod
# def from_percent(cls, snap, percent):
# return cls(percent)
. Output only the next line. | def test_snap_to_decimal_move_out_by(): |
Based on the snippet: <|code_start|>
class RedisModule(Module):
def __init__(self, strict_client=True):
self.client_class = redis.StrictRedis if strict_client else redis.Redis
<|code_end|>
, predict the immediate next line with the help of imports:
from injector import inject, Module, provides, singleton
from smarkets.interfaces import Redis, RedisConfiguration
import redis
and context (classes, functions, sometimes code) from other files:
# Path: smarkets/interfaces.py
. Output only the next line. | @singleton |
Given snippet: <|code_start|>
class RedisModule(Module):
def __init__(self, strict_client=True):
self.client_class = redis.StrictRedis if strict_client else redis.Redis
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from injector import inject, Module, provides, singleton
from smarkets.interfaces import Redis, RedisConfiguration
import redis
and context:
# Path: smarkets/interfaces.py
which might include code, classes, or functions. Output only the next line. | @singleton |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
def test_uid_or_int_to_int():
eq_(uid_or_int_to_int(1234, 'irrelevant'), 1234)
eq_(uid_or_int_to_int(int_to_uuid(5454, 'Contract'), 'Contract'), 5454)
try:
uid_or_int_to_int(int_to_uuid(1234, 'Market'), 'Event')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from nose.tools import eq_
from smarkets.uuid import int_to_uuid, uid_or_int_to_int
and context:
# Path: smarkets/uuid.py
# def int_to_uuid(number, ttype):
# """Convert an untagged integer into a tagged uuid
#
# :type ttype: str or unicode on Python 2, str on Python 3
# """
# return Uuid.from_int(number, ttype).to_hex()
#
# def uid_or_int_to_int(value, expected_type):
# if not isinstance(value, integer_types):
# value, type_ = uuid_to_int(value, return_tag='type')
# if type_ != expected_type:
# raise ValueError("Expected tag %r doesn't match %r" % (expected_type, type_))
#
# return value
which might include code, classes, or functions. Output only the next line. | assert False, 'Should have failed' |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
def test_uid_or_int_to_int():
eq_(uid_or_int_to_int(1234, 'irrelevant'), 1234)
eq_(uid_or_int_to_int(int_to_uuid(5454, 'Contract'), 'Contract'), 5454)
try:
uid_or_int_to_int(int_to_uuid(1234, 'Market'), 'Event')
assert False, 'Should have failed'
<|code_end|>
. Write the next line using the current file imports:
from nose.tools import eq_
from smarkets.uuid import int_to_uuid, uid_or_int_to_int
and context from other files:
# Path: smarkets/uuid.py
# def int_to_uuid(number, ttype):
# """Convert an untagged integer into a tagged uuid
#
# :type ttype: str or unicode on Python 2, str on Python 3
# """
# return Uuid.from_int(number, ttype).to_hex()
#
# def uid_or_int_to_int(value, expected_type):
# if not isinstance(value, integer_types):
# value, type_ = uuid_to_int(value, return_tag='type')
# if type_ != expected_type:
# raise ValueError("Expected tag %r doesn't match %r" % (expected_type, type_))
#
# return value
, which may include functions, classes, or code. Output only the next line. | except ValueError: |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
class TestString(object):
binary_version = 'ąę'.encode('utf-8')
unicode_version = 'ąę'
<|code_end|>
, predict the next line using imports from the current file:
from nose.tools import eq_
from six import PY3
from smarkets.string import n, native_str_result
and context including class names, function names, and sometimes code from other files:
# Path: smarkets/string.py
# def n(string):
# n_docstring
# return string if isinstance(string, str) else string.decode('utf-8')
#
# @decorator.decorator
# def native_str_result(function, *args, **kwargs):
# '''
# '''
# return n(function(*args, **kwargs))
. Output only the next line. | inputs = (binary_version, unicode_version) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
class TestString(object):
binary_version = 'ąę'.encode('utf-8')
unicode_version = 'ąę'
<|code_end|>
. Use current file imports:
(from nose.tools import eq_
from six import PY3
from smarkets.string import n, native_str_result)
and context including class names, function names, or small code snippets from other files:
# Path: smarkets/string.py
# def n(string):
# n_docstring
# return string if isinstance(string, str) else string.decode('utf-8')
#
# @decorator.decorator
# def native_str_result(function, *args, **kwargs):
# '''
# '''
# return n(function(*args, **kwargs))
. Output only the next line. | inputs = (binary_version, unicode_version) |
Based on the snippet: <|code_start|> if matplotlib is not None:
matplotlib.rcParams.update(eval(config.get('output',
'plotproperties')))
# Check settings for parameter sweep
param_name = config.get('parameter_sweep', 'param_name')
try:
config.get('cell', param_name)
except KeyError:
print("Unkown parameter name {} to sweep.".format(param_name))
raise RuntimeError
spike_code = config.get('conversion', 'spike_code')
spike_codes = config_string_to_set_of_strings(config.get('restrictions',
'spike_codes'))
assert spike_code in spike_codes, \
"Unknown spike code {} selected. Choose from {}.".format(spike_code,
spike_codes)
if spike_code == 'temporal_pattern':
num_bits = str(config.getint('conversion', 'num_bits'))
config.set('simulation', 'duration', num_bits)
config.set('simulation', 'batch_size', '1')
elif 'ttfs' in spike_code:
config.set('cell', 'tau_refrac',
str(config.getint('simulation', 'duration')))
assert keras_backend != 'theano' or spike_code == 'temporal_mean_rate', \
"Keras backend 'theano' only works when the 'spike_code' parameter " \
"is set to 'temporal_mean_rate' in snntoolbox config."
with open(os.path.join(log_dir_of_current_run, '.config'), str('w')) as f:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import tensorflow.keras.backend as k
import matplotlib
import warnings
import nxsdk.api.n2a as sim
from importlib import import_module
from snntoolbox.parsing.model_libs.keras_input_lib import load
from snntoolbox.datasets.utils import get_dataset
from snntoolbox.conversion.utils import normalize_parameters
from functools import wraps
from snntoolbox.simulation.plotting import plot_param_sweep
from snntoolbox.utils.utils import import_configparser
from textwrap import dedent
and context (classes, functions, sometimes code) from other files:
# Path: snntoolbox/parsing/model_libs/keras_input_lib.py
# def load(path, filename, **kwargs):
# """Load network from file.
#
# Parameters
# ----------
#
# path: str
# Path to directory where to load model from.
#
# filename: str
# Name of file to load model from.
#
# Returns
# -------
#
# : dict[str, Union[keras.models.Sequential, function]]
# A dictionary of objects that constitute the input model. It must
# contain the following two keys:
#
# - 'model': keras.models.Sequential
# Keras model instance of the network.
# - 'val_fn': function
# Function that allows evaluating the original model.
# """
#
# filepath = str(os.path.join(path, filename))
#
# if os.path.exists(filepath + '.json'):
# model = models.model_from_json(open(filepath + '.json').read())
# try:
# model.load_weights(filepath + '.h5')
# except OSError:
# # Allows h5 files without a .h5 extension to be loaded.
# model.load_weights(filepath)
# # With this loading method, optimizer and loss cannot be recovered.
# # Could be specified by user, but since they are not really needed
# # at inference time, set them to the most common choice.
# # TODO: Proper reinstantiation should be doable since Keras2
# model.compile('sgd', 'categorical_crossentropy',
# ['accuracy', metrics.top_k_categorical_accuracy])
# else:
# filepath_custom_objects = kwargs.get('filepath_custom_objects', None)
# if filepath_custom_objects is not None:
# filepath_custom_objects = str(filepath_custom_objects) # python 2
#
# custom_dicts = assemble_custom_dict(
# get_custom_activations_dict(filepath_custom_objects),
# get_custom_layers_dict())
# try:
# model = models.load_model(filepath + '.h5', custom_dicts)
# except OSError as e:
# print(e)
# print("Trying to load without '.h5' extension.")
# model = models.load_model(filepath, custom_dicts)
# model.compile(model.optimizer, model.loss,
# ['accuracy', metrics.top_k_categorical_accuracy])
#
# model.summary()
# return {'model': model, 'val_fn': model.evaluate}
. Output only the next line. | config.write(f) |
Using the snippet: <|code_start|>
class Mailbox:
def __init__(self, name=None):
self.name = name
self.messages = deque()
self.handlers = deque()
def send(self, message):
try:
handler = self.handlers.popleft()
except IndexError:
self.messages.append(message)
else:
<|code_end|>
, determine the next line of code. You have imports:
from collections import deque
from .monads import callcc, done, ContinuationMonad, do
and context (class names, function names, or code) available:
# Path: cell/workflow/monads.py
# def callcc(usecc):
# return ContinuationMonad(
# lambda cont: usecc(
# lambda val: ContinuationMonad(
# lambda _: cont(val))
# ).run(cont)
# )
#
# def done(val):
# raise Done(val)
#
# class ContinuationMonad(Monad):
#
# def __init__(self, run):
# self.run = run
#
# def __call__(self, cont=fid):
# return self.run(cont)
#
# def bind(self, bindee):
# return ContinuationMonad(
# lambda cont: self.run(
# lambda val: bindee(val).run(cont))
# )
#
# @classmethod
# def unit(cls, val):
# return cls(lambda cont: cont(val))
#
# @classmethod
# def zero(cls):
# return cls(lambda cont: None)
#
# @decorator_with_args
# def do(fun, args, kwargs, Monad):
#
# @handle_monadic_throws(Monad)
# def run_maybe_iterator():
# it = fun(*args, **kwargs)
#
# if isinstance(it, types.GeneratorType):
#
# @handle_monadic_throws(Monad)
# def send(val):
# try:
# # here's the real magic
# # --what magic? please explain or the comment goes :) [ask]
# monad = it.send(val)
# return monad.bind(send)
# except StopIteration:
# return Monad.unit(None)
# return send(None)
# else:
# # not a generator
# return Monad.unit(None) if it is None else it
#
# return run_maybe_iterator()
. Output only the next line. | handler(message)() |
Given snippet: <|code_start|>
class Mailbox:
def __init__(self, name=None):
self.name = name
self.messages = deque()
self.handlers = deque()
def send(self, message):
try:
handler = self.handlers.popleft()
except IndexError:
self.messages.append(message)
else:
handler(message)()
def receive(self):
return callcc(self.react)
@do(ContinuationMonad)
def react(self, handler):
try:
message = self.messages.popleft()
except IndexError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import deque
from .monads import callcc, done, ContinuationMonad, do
and context:
# Path: cell/workflow/monads.py
# def callcc(usecc):
# return ContinuationMonad(
# lambda cont: usecc(
# lambda val: ContinuationMonad(
# lambda _: cont(val))
# ).run(cont)
# )
#
# def done(val):
# raise Done(val)
#
# class ContinuationMonad(Monad):
#
# def __init__(self, run):
# self.run = run
#
# def __call__(self, cont=fid):
# return self.run(cont)
#
# def bind(self, bindee):
# return ContinuationMonad(
# lambda cont: self.run(
# lambda val: bindee(val).run(cont))
# )
#
# @classmethod
# def unit(cls, val):
# return cls(lambda cont: cont(val))
#
# @classmethod
# def zero(cls):
# return cls(lambda cont: None)
#
# @decorator_with_args
# def do(fun, args, kwargs, Monad):
#
# @handle_monadic_throws(Monad)
# def run_maybe_iterator():
# it = fun(*args, **kwargs)
#
# if isinstance(it, types.GeneratorType):
#
# @handle_monadic_throws(Monad)
# def send(val):
# try:
# # here's the real magic
# # --what magic? please explain or the comment goes :) [ask]
# monad = it.send(val)
# return monad.bind(send)
# except StopIteration:
# return Monad.unit(None)
# return send(None)
# else:
# # not a generator
# return Monad.unit(None) if it is None else it
#
# return run_maybe_iterator()
which might include code, classes, or functions. Output only the next line. | self.handlers.append(handler) |
Predict the next line for this snippet: <|code_start|>
class Mailbox:
def __init__(self, name=None):
self.name = name
<|code_end|>
with the help of current file imports:
from collections import deque
from .monads import callcc, done, ContinuationMonad, do
and context from other files:
# Path: cell/workflow/monads.py
# def callcc(usecc):
# return ContinuationMonad(
# lambda cont: usecc(
# lambda val: ContinuationMonad(
# lambda _: cont(val))
# ).run(cont)
# )
#
# def done(val):
# raise Done(val)
#
# class ContinuationMonad(Monad):
#
# def __init__(self, run):
# self.run = run
#
# def __call__(self, cont=fid):
# return self.run(cont)
#
# def bind(self, bindee):
# return ContinuationMonad(
# lambda cont: self.run(
# lambda val: bindee(val).run(cont))
# )
#
# @classmethod
# def unit(cls, val):
# return cls(lambda cont: cont(val))
#
# @classmethod
# def zero(cls):
# return cls(lambda cont: None)
#
# @decorator_with_args
# def do(fun, args, kwargs, Monad):
#
# @handle_monadic_throws(Monad)
# def run_maybe_iterator():
# it = fun(*args, **kwargs)
#
# if isinstance(it, types.GeneratorType):
#
# @handle_monadic_throws(Monad)
# def send(val):
# try:
# # here's the real magic
# # --what magic? please explain or the comment goes :) [ask]
# monad = it.send(val)
# return monad.bind(send)
# except StopIteration:
# return Monad.unit(None)
# return send(None)
# else:
# # not a generator
# return Monad.unit(None) if it is None else it
#
# return run_maybe_iterator()
, which may contain function names, class names, or code. Output only the next line. | self.messages = deque() |
Next line prediction: <|code_start|>
def get_text(element):
if hasattr(element, 'text_content'): # lxml 2
text = element.text_content()
else:
text = ''.join(element.itertext())
return text
def word_count(element):
return len(get_text(element).split())
def paragraph_counts(pq):
wcs = [word_count(x) for x in pq('p')]
return [x for x in wcs if x > 0]
def section_stats(headers):
hs = [h for h in headers if get_text(h) != 'Contents']
# how not to write Python: ['h'+str(i) for i in range(1, 8)]
all_headers = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7']
totals = []
<|code_end|>
. Use current file imports:
(from base import Input
from wapiti import get_url
from pyquery import PyQuery
from stats import dist_stats
import wapiti)
and context including class names, function names, or small code snippets from other files:
# Path: wapiti.py
# def get_url(url, params=None, raise_exc=True):
# resp = FakeResponse()
# try:
# resp = fake_requests(url, params)
# except Exception as e:
# if raise_exc:
# raise
# else:
# resp.error = e
# return resp
. Output only the next line. | for header in hs: |
Predict the next line after this snippet: <|code_start|> self.logger = logging.getLogger('AccessLogger')
self.logger.setLevel(logging.INFO)
write_handler = logging.FileHandler(logfile)
self.logger.addHandler(write_handler)
def log(self, action, hostname, params, start_time):
self.logger.info(json.dumps({'time': time.time(), 'action': action, 'hostname': hostname, 'params': params, 'start_time': start_time}))
def outstanding(self):
# TODO: fix
lines = self.read(30)
recents = [line for line in lines if line['age'] < LOG_OUTSTANDING_LIMIT]
starts = set([(start['hostname'], start['params'], start['start_time']) for start in recents if start['action'] == 'start'])
completes = set([(finish['hostname'], finish['params'], finish['start_time']) for finish in recents if finish['action'] == 'complete'])
outstanding = starts - completes
return {'openlog': len(outstanding)}
def read(self, no):
ret = []
history = open(self.logfile, 'r')
lines = history.readlines()
if not lines[-no:]:
return []
else:
for line in lines[-no:]:
line = json.loads(line)
time_s = line['time']
line['time'] = time.ctime(time_s)
line['age'] = round(time.time() - time_s)
ret.append(line)
<|code_end|>
using the current file's imports:
from bottle import route, run, JSONPlugin, request
from bottle_compressor import CompressorPlugin
from functools import partial
from bottle import json_dumps as dumps
import bottle
import time
import os
import oursql
import logging
import json
import subprocess
import socket
import os
and any relevant context from other files:
# Path: bottle_compressor.py
# class CompressorPlugin(object):
# """
# Bottle plugin for compressing content
# """
# name = 'compressor_plugin'
# api = 2
#
# def __init__(self, content_types=DEFAULT_COMPRESSABLES, compress_level=6,\
# minimal_size=200):
# """
# Initialize attribute values
#
# Keyword arguments:
# content_types -- set the content types to be compressed
# compress_level -- set the gzip compress level
# minimal_size -- set the min size to be compressed
# """
# self.content_types = content_types
# self.compress_level = compress_level
# self.minimal_size = minimal_size
#
#
# def apply(self, callback, route):
# """
# Decorate route callback
#
# keyword arguments:
# callback -- the route callback to be decorated
# context -- an instance of Route and provides a lot of meta-information
# and context for that route
# """
# content_types = self.content_types
# compress_level = self.compress_level
# minimal_size = self.minimal_size
#
# def wrapper(*args, **kwargs):
# """
# The decorated route callback
# """
# data = callback(*args, **kwargs)
#
# # ignore empty data
# if not data or not isinstance(data, (str, unicode)):
# return data
#
# # ignore redirect
# if response.status_code >= 300 and response.status_code < 400:
# return data
#
# # ignore encoded data
# if 'Content-Encoding' in response.headers:
# return data
#
# # ignore non-compressable types
# content_type = response.headers.get('Content-Type')
# ctype = content_type.split(';')[0]
# if ctype not in content_types:
# return data
#
# # ie bug
# user_agent = request.headers.get('User-Agent')
# if user_agent and 'msie' in user_agent.lower() \
# and 'javascript' in ctype:
# return data
#
# accept_encoding = request.headers.get('Accept-Encoding')
# encoding_type = client_wants_encoding(accept_encoding) \
# if accept_encoding else None
#
# if encoding_type:
# data = ''.join(data)
# # data size smaller than minimal_size
# if len(data) < minimal_size:
# return [data]
# if encoding_type == Gzip_Encoding:
# data = compress(data, compress_level)
# response.headers.append('Content-Encoding', 'gzip')
# else:
# data = zlib.compress(data)
# response.headers.append('Content-Encoding', 'deflate')
# response.headers.append('Vary', 'Accept-Encoding')
# response.headers.replace('Content-Length', str(len(data)))
# data = [data]
# return data
#
# return wrapper
. Output only the next line. | return ret[::-1] |
Given snippet: <|code_start|>
class Watchers(Input):
prefix = 'wa'
def fetch(self):
result = get_json('http://toolserver.org/~slaporte/rs/wl?title=' + self.page_title.replace(' ', '_'))
return result
stats = {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from base import Input
from wapiti import get_json
and context:
# Path: wapiti.py
# def get_json(*args, **kwargs):
# resp = get_url(*args, **kwargs)
# return json.loads(resp.text)
which might include code, classes, or functions. Output only the next line. | 'count': lambda f_res: f_res.get('watchers'), |
Using the snippet: <|code_start|>
class PageViews(Input):
prefix = 'pv'
def fetch(self):
return get_json('http://stats.grok.se/json/en/latest90/' + self.page_title)
stats = {
'90_days': lambda f: dist_stats(f['daily_views'].values()),
<|code_end|>
, determine the next line of code. You have imports:
from base import Input
from wapiti import get_json
from stats import dist_stats
and context (class names, function names, or code) available:
# Path: wapiti.py
# def get_json(*args, **kwargs):
# resp = get_url(*args, **kwargs)
# return json.loads(resp.text)
. Output only the next line. | } |
Based on the snippet: <|code_start|> if rev['rev_len'] == 0:
reverted[rev['rev_id']] = rev
clean = [r for r in revs if r['rev_id'] not in reverted]
return reverted.values(), clean
class Revisions(Input):
prefix = 'rv'
def fetch(self):
ret = {}
revs = get_json('http://toolserver.org/~slaporte/rs/all/?title=' + self.page_title.replace(' ', '_'))
ret['article'] = preprocess_revs(revs['article'])
ret['talk'] = preprocess_revs(revs['talk'])
ret['article_reverted'], ret['article_without_reverted'] = partition_reverts(ret['article'])
ret['talk_reverted'], ret['talk_without_reverted'] = partition_reverts(ret['talk'])
return ret
def new_fetch(self):
pass
stats = {
# subject page
'wo_undid': lambda f: all_revisions(f['article_without_reverted']),
'undid': lambda f: all_revisions(f['article_reverted']),
'all': lambda f: all_revisions(f['article']),
# talk page stuff follows
't_wo_undid': lambda f: all_revisions(f['talk_without_reverted']),
<|code_end|>
, predict the immediate next line with the help of imports:
from base import Input
from wapiti import get_json
from stats import dist_stats
from datetime import datetime, timedelta, date
from math import ceil
from collections import OrderedDict, defaultdict
and context (classes, functions, sometimes code) from other files:
# Path: wapiti.py
# def get_json(*args, **kwargs):
# resp = get_url(*args, **kwargs)
# return json.loads(resp.text)
. Output only the next line. | 't_undid': lambda f: all_revisions(f['talk_reverted']), |
Given snippet: <|code_start|>
if self.pred_loss_coeff > 0:
next_obs, factors = self.get_batch(
epoch=epoch, sample_factors=True)
(reconstructions, obs_distribution_params,
latent_distribution_params, y_pred) = self.model(next_obs, predict_factors=True)
pred_loss = self.model.prediction_loss(y_pred, factors)
pred_losses.append(pred_loss.item())
else:
if sample_batch is not None:
data = sample_batch(self.batch_size, epoch)
next_obs = data['next_obs']
else:
next_obs = self.get_batch(
epoch=epoch, sample_factors=False)
(reconstructions, obs_distribution_params,
latent_distribution_params) = self.model(next_obs)
pred_loss = 0
log_prob = self.model.logprob(next_obs, obs_distribution_params)
kle = self.model.kl_divergence(latent_distribution_params)
encoder_mean = self.model.get_encoding_from_latent_distribution_params(
latent_distribution_params)
z_data = ptu.get_numpy(encoder_mean.cpu())
for i in range(len(z_data)):
zs.append(z_data[i, :])
loss = -1 * log_prob + beta * kle + self.pred_loss_coeff * pred_loss
self.optimizer.zero_grad()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from os import path as osp
from torchvision.utils import save_image
from multiworld.core.image_env import normalize_image
from rlkit.core import logger
from rlkit.torch import pytorch_util as ptu
from rlkit.torch.vae.vae_trainer import ConvVAETrainer
from weakly_supervised_control.vae.conv_vae import ConvVAE
import numpy as np
import torch
and context:
# Path: weakly_supervised_control/vae/conv_vae.py
# class VAE(ConvVAE):
# def __init__(
# self,
# x_shape: List[int],
# representation_size: int,
# init_w: float = 1e-3,
# num_factors: int = None,
# **kwargs
# ):
# def predict_factors(self, input):
# def prediction_loss(self, pred, labels):
# def forward(self, input, predict_factors=False):
which might include code, classes, or functions. Output only the next line. | loss.backward() |
Given the code snippet: <|code_start|> try:
iter(data[0])
except TypeError:
pass
else:
data = np.concatenate(data)
if (isinstance(data, np.ndarray) and data.size == 1
and not always_show_all_stats):
return OrderedDict({name: float(data)})
stats = OrderedDict([
(name + ' Mean', np.mean(data)),
(name + ' Std', np.std(data)),
])
if not exclude_max_min:
stats[name + ' Max'] = np.max(data)
stats[name + ' Min'] = np.min(data)
return stats
def get_stat_in_paths(paths, dict_name, scalar_name):
if len(paths) == 0:
return np.array([[]])
if type(paths[0][dict_name]) == dict:
# Support rllab interface
return [path[dict_name][scalar_name] for path in paths]
return [
<|code_end|>
, generate the next line using the imports in this file:
from typing import Dict, List, Tuple
from collections import OrderedDict
from numbers import Number
from PIL import Image
from multiworld.core.multitask_env import MultitaskEnv
from multiworld.core.wrapper_env import ProxyEnv
from multiworld.envs.env_util import concatenate_box_spaces
from weakly_supervised_control.envs.env_util import normalize_image, unormalize_image, concat_images
import random
import warnings
import cv2
import gym
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: weakly_supervised_control/envs/env_util.py
# def normalize_image(image: np.ndarray, dtype=np.float64) -> np.ndarray:
# assert image.dtype == np.uint8
# return dtype(image) / 255.0
#
# def unormalize_image(image: np.ndarray) -> np.ndarray:
# assert image.dtype != np.uint8
# return np.uint8(image * 255.0)
#
# def concat_images(images: np.ndarray,
# resize_shape: Tuple[int, int] = None,
# concat_horizontal: bool = True):
# """Concatenates N images into a single image.
# Args:
# images: An RGB array of shape (N, width, height, 3)
# resize_shape: (width, height)
# concat_horizontal: If true, returns an image of size (N * width, height).
# Otherwise returns an image of size (width, N * height).
# """
# assert len(images.shape) == 4, images.shape
# assert images.shape[3] == 3, images.shape
# if resize_shape:
# images = np.array([cv2.resize(image, resize_shape)
# for image in images])
# if concat_horizontal:
# stacked_images = np.concatenate(images, axis=1)
# else:
# stacked_images = np.concatenate(images, axis=0)
# return stacked_images
. Output only the next line. | [info[scalar_name] for info in path[dict_name]] |
Predict the next line for this snippet: <|code_start|> sub_dict = create_stats_ordered_dict(
"{0}_{1}".format(name, number),
d,
)
ordered_dict.update(sub_dict)
return ordered_dict
if isinstance(data, list):
try:
iter(data[0])
except TypeError:
pass
else:
data = np.concatenate(data)
if (isinstance(data, np.ndarray) and data.size == 1
and not always_show_all_stats):
return OrderedDict({name: float(data)})
stats = OrderedDict([
(name + ' Mean', np.mean(data)),
(name + ' Std', np.std(data)),
])
if not exclude_max_min:
stats[name + ' Max'] = np.max(data)
stats[name + ' Min'] = np.min(data)
return stats
def get_stat_in_paths(paths, dict_name, scalar_name):
<|code_end|>
with the help of current file imports:
from typing import Dict, List, Tuple
from collections import OrderedDict
from numbers import Number
from PIL import Image
from multiworld.core.multitask_env import MultitaskEnv
from multiworld.core.wrapper_env import ProxyEnv
from multiworld.envs.env_util import concatenate_box_spaces
from weakly_supervised_control.envs.env_util import normalize_image, unormalize_image, concat_images
import random
import warnings
import cv2
import gym
import numpy as np
and context from other files:
# Path: weakly_supervised_control/envs/env_util.py
# def normalize_image(image: np.ndarray, dtype=np.float64) -> np.ndarray:
# assert image.dtype == np.uint8
# return dtype(image) / 255.0
#
# def unormalize_image(image: np.ndarray) -> np.ndarray:
# assert image.dtype != np.uint8
# return np.uint8(image * 255.0)
#
# def concat_images(images: np.ndarray,
# resize_shape: Tuple[int, int] = None,
# concat_horizontal: bool = True):
# """Concatenates N images into a single image.
# Args:
# images: An RGB array of shape (N, width, height, 3)
# resize_shape: (width, height)
# concat_horizontal: If true, returns an image of size (N * width, height).
# Otherwise returns an image of size (width, N * height).
# """
# assert len(images.shape) == 4, images.shape
# assert images.shape[3] == 3, images.shape
# if resize_shape:
# images = np.array([cv2.resize(image, resize_shape)
# for image in images])
# if concat_horizontal:
# stacked_images = np.concatenate(images, axis=1)
# else:
# stacked_images = np.concatenate(images, axis=0)
# return stacked_images
, which may contain function names, class names, or code. Output only the next line. | if len(paths) == 0: |
Predict the next line after this snippet: <|code_start|> attr_name.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attr_name), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quote_char = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quote_char:
next(data)
return b"".join(attr_name), b"".join(attr_value)
# 10.4
elif c in ascii_uppercase_bytes:
attr_value.append(c.lower())
# 10.5
else:
attr_value.append(c)
elif c == b">":
return b"".join(attr_name), b""
<|code_end|>
using the current file's imports:
import string
from .encoding_names import encodings
and any relevant context from other files:
# Path: src/html5_parser/encoding_names.py
. Output only the next line. | elif c in ascii_uppercase_bytes: |
Here is a snippet: <|code_start|>admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^api', include(api.urls)),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from .resources import api
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
and context from other files:
# Path: tests/testapp/resources.py
# class UserResource(Resource):
# class Meta:
# class AuthorResource(Resource):
# class Meta:
# class PostWithPictureResource(Resource):
# class Meta:
# class PostResource(Resource):
# class Meta:
# class CommentResource(Resource):
# class Meta:
# class GroupResource(Resource):
# class Meta:
# class MembershipResource(Resource):
# class Meta:
# def clean_resources(cls, resources, request=None, **kwargs):
# def dump_document_dummy(obj):
# def dump_document_title(obj):
# def get_filters(cls, filters):
, which may include functions, classes, or code. Output only the next line. | settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
Given the following code snippet before the placeholder: <|code_start|>
class ModelInfo(object):
def __init__(self, name, fields_own=None, fields_to_one=None,
fields_to_many=None, auth_user_paths=None, is_user=None):
<|code_end|>
, predict the next line using imports from the current file:
from django.db import models
from django.contrib.auth import get_user_model
from .utils import Choices
from .django_utils import get_model_name, get_models
and context including class names, function names, and sometimes code from other files:
# Path: jsonapi/utils.py
# class Choices(object):
#
# """ Choices."""
#
# def __init__(self, *choices):
# self._choices = []
# self._choice_dict = {}
#
# for choice in choices:
# if isinstance(choice, (list, tuple)):
# if len(choice) == 2:
# choice = (choice[0], choice[1], choice[1])
#
# elif len(choice) != 3:
# raise ValueError(
# "Choices can't handle a list/tuple of length {0}, only\
# 2 or 3".format(choice))
# else:
# choice = (choice, choice, choice)
#
# self._choices.append((choice[0], choice[2]))
# self._choice_dict[choice[1]] = choice[0]
#
# def __getattr__(self, attname):
# try:
# return self._choice_dict[attname]
# except KeyError:
# raise AttributeError(attname)
#
# def __iter__(self):
# return iter(self._choices)
#
# def __getitem__(self, index):
# return self._choices[index]
#
# def __delitem__(self, index):
# del self._choices[index]
#
# def __setitem__(self, index, value):
# self._choices[index] = value
#
# def __repr__(self):
# return "{0}({1})".format(
# self.__class__.__name__,
# self._choices
# )
#
# def __len__(self):
# return len(self._choices)
#
# def __contains__(self, element):
# return element in self._choice_dict.values()
#
# Path: jsonapi/django_utils.py
# def get_model_name(model):
# """ Get model name for the field.
#
# Django 1.5 uses module_name, does not support model_name
# Django 1.6 uses module_name and model_name
# DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
#
# """
# opts = model._meta
# if django.VERSION[:2] < (1, 7):
# model_name = opts.module_name
# else:
# model_name = opts.model_name
#
# return model_name
#
# def get_models():
# if django.VERSION[:2] < (1, 8):
# return models.get_models()
# else:
# from django.apps import apps
# return apps.get_models()
. Output only the next line. | self.name = name |
Given the code snippet: <|code_start|>
class ModelInfo(object):
def __init__(self, name, fields_own=None, fields_to_one=None,
fields_to_many=None, auth_user_paths=None, is_user=None):
self.name = name
self.fields_own = fields_own or []
self.fields_to_one = fields_to_one or []
self.fields_to_many = fields_to_many or []
<|code_end|>
, generate the next line using the imports in this file:
from django.db import models
from django.contrib.auth import get_user_model
from .utils import Choices
from .django_utils import get_model_name, get_models
and context (functions, classes, or occasionally code) from other files:
# Path: jsonapi/utils.py
# class Choices(object):
#
# """ Choices."""
#
# def __init__(self, *choices):
# self._choices = []
# self._choice_dict = {}
#
# for choice in choices:
# if isinstance(choice, (list, tuple)):
# if len(choice) == 2:
# choice = (choice[0], choice[1], choice[1])
#
# elif len(choice) != 3:
# raise ValueError(
# "Choices can't handle a list/tuple of length {0}, only\
# 2 or 3".format(choice))
# else:
# choice = (choice, choice, choice)
#
# self._choices.append((choice[0], choice[2]))
# self._choice_dict[choice[1]] = choice[0]
#
# def __getattr__(self, attname):
# try:
# return self._choice_dict[attname]
# except KeyError:
# raise AttributeError(attname)
#
# def __iter__(self):
# return iter(self._choices)
#
# def __getitem__(self, index):
# return self._choices[index]
#
# def __delitem__(self, index):
# del self._choices[index]
#
# def __setitem__(self, index, value):
# self._choices[index] = value
#
# def __repr__(self):
# return "{0}({1})".format(
# self.__class__.__name__,
# self._choices
# )
#
# def __len__(self):
# return len(self._choices)
#
# def __contains__(self, element):
# return element in self._choice_dict.values()
#
# Path: jsonapi/django_utils.py
# def get_model_name(model):
# """ Get model name for the field.
#
# Django 1.5 uses module_name, does not support model_name
# Django 1.6 uses module_name and model_name
# DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
#
# """
# opts = model._meta
# if django.VERSION[:2] < (1, 7):
# model_name = opts.module_name
# else:
# model_name = opts.model_name
#
# return model_name
#
# def get_models():
# if django.VERSION[:2] < (1, 8):
# return models.get_models()
# else:
# from django.apps import apps
# return apps.get_models()
. Output only the next line. | self.auth_user_paths = auth_user_paths or [] |
Given the following code snippet before the placeholder: <|code_start|>
class ModelInfo(object):
def __init__(self, name, fields_own=None, fields_to_one=None,
fields_to_many=None, auth_user_paths=None, is_user=None):
self.name = name
<|code_end|>
, predict the next line using imports from the current file:
from django.db import models
from django.contrib.auth import get_user_model
from .utils import Choices
from .django_utils import get_model_name, get_models
and context including class names, function names, and sometimes code from other files:
# Path: jsonapi/utils.py
# class Choices(object):
#
# """ Choices."""
#
# def __init__(self, *choices):
# self._choices = []
# self._choice_dict = {}
#
# for choice in choices:
# if isinstance(choice, (list, tuple)):
# if len(choice) == 2:
# choice = (choice[0], choice[1], choice[1])
#
# elif len(choice) != 3:
# raise ValueError(
# "Choices can't handle a list/tuple of length {0}, only\
# 2 or 3".format(choice))
# else:
# choice = (choice, choice, choice)
#
# self._choices.append((choice[0], choice[2]))
# self._choice_dict[choice[1]] = choice[0]
#
# def __getattr__(self, attname):
# try:
# return self._choice_dict[attname]
# except KeyError:
# raise AttributeError(attname)
#
# def __iter__(self):
# return iter(self._choices)
#
# def __getitem__(self, index):
# return self._choices[index]
#
# def __delitem__(self, index):
# del self._choices[index]
#
# def __setitem__(self, index, value):
# self._choices[index] = value
#
# def __repr__(self):
# return "{0}({1})".format(
# self.__class__.__name__,
# self._choices
# )
#
# def __len__(self):
# return len(self._choices)
#
# def __contains__(self, element):
# return element in self._choice_dict.values()
#
# Path: jsonapi/django_utils.py
# def get_model_name(model):
# """ Get model name for the field.
#
# Django 1.5 uses module_name, does not support model_name
# Django 1.6 uses module_name and model_name
# DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
#
# """
# opts = model._meta
# if django.VERSION[:2] < (1, 7):
# model_name = opts.module_name
# else:
# model_name = opts.model_name
#
# return model_name
#
# def get_models():
# if django.VERSION[:2] < (1, 8):
# return models.get_models()
# else:
# from django.apps import apps
# return apps.get_models()
. Output only the next line. | self.fields_own = fields_own or [] |
Using the snippet: <|code_start|>
class UserForm(forms.ModelForm):
class Meta:
model = User
exclude = ["date_joined"]
class PostWithPictureForm(forms.ModelForm):
<|code_end|>
, determine the next line of code. You have imports:
from django import forms
from .models import User, PostWithPicture
and context (class names, function names, or code) available:
# Path: tests/testapp/models.py
# class Author(models.Model):
# class Post(models.Model):
# class PostWithPicture(Post):
# class Comment(models.Model):
# class TestSerializerAllFields(models.Model):
# class Group(models.Model):
# class Membership(models.Model):
# class AAbstractOne(models.Model):
# class AAbstractManyToMany(models.Model):
# class AAbstract(models.Model):
# class Meta:
# class AA(AAbstract):
# class AOne(models.Model):
# class AManyToMany(models.Model):
# class A(AA):
# class B(A):
# class BMany(models.Model):
# class BManyToMany(models.Model):
# class BManyToManyChild(BManyToMany):
# class BProxy(B):
# class Meta:
# def save(self, *args, **kwargs):
# def title_uppercased(self):
# def title_uppercased(self, value):
. Output only the next line. | class Meta: |
Given the code snippet: <|code_start|>
class TestResource(TestCase):
def test_get_form(self):
# Return defined in Meta forms
self.assertEqual(UserResource.get_form(), UserResource.Meta.form)
def test_get_partial_form(self):
Form = UserResource.get_partial_form(UserResource.get_form(), None)
self.assertEqual(Form, UserResource.get_form())
self.assertNotIn("date_joined", Form.base_fields)
Form = UserResource.get_partial_form(
UserResource.get_form(), ["date_joined"])
# Fields could only be excluded.
<|code_end|>
, generate the next line using the imports in this file:
from django.test import TestCase
from ..resources import UserResource
and context (functions, classes, or occasionally code) from other files:
# Path: tests/testapp/resources.py
# class UserResource(Resource):
#
# """ User Resource."""
#
# class Meta:
# model = settings.AUTH_USER_MODEL
# authenticators = [Resource.AUTHENTICATORS.SESSION]
# fieldnames_exclude = ['password']
# form = UserForm
# allowed_methods = 'GET', 'PUT', 'DELETE'
. Output only the next line. | self.assertNotIn("date_joined", Form.base_fields) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Register your models here.
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ('name', 'age', 'double_age')
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from .models import Author, Book
and context from other files:
# Path: demo/library/models.py
# class Author(models.Model):
# name = models.CharField("Name", max_length=128)
# penname = models.CharField("Pen Name", max_length=128)
# age = models.SmallIntegerField("Age", null=True, blank=True)
#
# class Meta:
# ordering = ('name',)
# verbose_name = "Author"
# verbose_name_plural = "Authors"
#
# def __str__(self):
# return self.name
#
# def double_age(self):
# return self.age*2 if self.age else ''
# double_age.label = "Double Age"
#
# class Book(models.Model):
# title = models.CharField(_("Title"), max_length=128)
# isbn = models.CharField("ISBN", max_length=12)
# author = models.ForeignKey(Author, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('title',)
# verbose_name = "Book"
# verbose_name_plural = "Books"
#
# def __str__(self):
# return self.title
, which may contain function names, class names, or code. Output only the next line. | def double_age(self, obj): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Register your models here.
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ('name', 'age', 'double_age')
def double_age(self, obj):
return obj.age*2
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from .models import Author, Book
and context:
# Path: demo/library/models.py
# class Author(models.Model):
# name = models.CharField("Name", max_length=128)
# penname = models.CharField("Pen Name", max_length=128)
# age = models.SmallIntegerField("Age", null=True, blank=True)
#
# class Meta:
# ordering = ('name',)
# verbose_name = "Author"
# verbose_name_plural = "Authors"
#
# def __str__(self):
# return self.name
#
# def double_age(self):
# return self.age*2 if self.age else ''
# double_age.label = "Double Age"
#
# class Book(models.Model):
# title = models.CharField(_("Title"), max_length=128)
# isbn = models.CharField("ISBN", max_length=12)
# author = models.ForeignKey(Author, on_delete=models.CASCADE)
#
# class Meta:
# ordering = ('title',)
# verbose_name = "Book"
# verbose_name_plural = "Books"
#
# def __str__(self):
# return self.title
which might include code, classes, or functions. Output only the next line. | double_age.short_description = "Double Age" |
Continue the code snippet: <|code_start|> num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
return {
'headers': headers,
'results': list_display_results(view, queryset, context),
'num_sorted_fields': num_sorted_fields,
}
@register.inclusion_tag("popupcrud/empty_list.html", takes_context=True)
def empty_list(context):
viewset = context['view']._viewset
return {
'viewset': viewset,
'icon': viewset.get_empty_list_icon(),
'message': viewset.get_empty_list_message(),
'new_button_text': ugettext("New {0}").format(
viewset.model._meta.verbose_name),
}
class PopupCrudFormsetFormRenderer(FormRenderer):
'''A special class to render formset forms fields as table
row columns'''
def render_fields(self):
rendered_fields = []
visible_fields = []
<|code_end|>
. Use current file imports:
from django.core.exceptions import FieldDoesNotExist
from django.db.models.fields.related import RelatedField
from django.forms.utils import pretty_name
from django.template import Library
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext
from django.utils.html import format_html
from django.utils.text import capfirst
from django.contrib.admin.utils import lookup_field, label_for_field as lff
from bootstrap3.renderers import FormRenderer, FormsetRenderer
from bootstrap3.bootstrap import get_bootstrap_setting
from bootstrap3.forms import render_field
from popupcrud.views import ORDER_VAR
import six
and context (classes, functions, or code) from other files:
# Path: popupcrud/views.py
# ORDER_VAR = 'o'
. Output only the next line. | hidden_fields = [] |
Continue the code snippet: <|code_start|> self.assertTemplateUsed(response, "popupcrud/list.html")
# template should have the three embedded bootstrap modals
for pattern in MODAL_PATTERNS:
self.assertTrue(
re.search(pattern, response.content.decode('utf-8')))
def test_list_display(self):
name = "John"
author = Author.objects.create(name=name, age=26)
response = self.client.get(reverse("authors"))
html = response.content.decode('utf-8')
self.assertTrue(
re.search(r'<th.*sortable.*>.*Name.*</th>', html, re.DOTALL))
self.assertTrue(
re.search(r'<th.*sortable.*>.*Age.*</th>', html, re.DOTALL))
self.assertTrue(
re.search(r'<th.*sortable.*>.*Half Age.*</th>', html, re.DOTALL))
self.assertTrue(
re.search(r'<th.*Double Age.*</th>', html, re.DOTALL))
self.assertFalse(
re.search(r'<th.*sortable.*>.*DOUBLE AGE.*</th>', html, re.DOTALL))
# also tests the get_obj_name() method
first_col = """<a name="object_detail" data-url="{0}" data-title="Author Detail" href="javascript:void(0);">{1}</a><div data-name=\'{1}\'></div>"""
self.assertContains(
response,
first_col.format(
reverse("author-detail", kwargs={'pk': author.pk}),
name)
)
self.assertContains(response, "<td>26</td>")
<|code_end|>
. Use current file imports:
import re
import json
import six
from django.test import TestCase
from django.http import JsonResponse
from django.urls import reverse
from django.core.urlresolvers import reverse
from .models import Author, Book
from .views import AuthorCrudViewset, BookCrudViewset, BookUUIDCrudViewSet
from popupcrud.views import POPUPCRUD
and context (classes, functions, or code) from other files:
# Path: test/models.py
# class Author(models.Model):
# name = models.CharField("Name", max_length=128)
# age = models.SmallIntegerField("Age", null=True, blank=True)
#
# class Meta:
# ordering = ('name',)
# verbose_name = "Author"
# verbose_name_plural = "Authors"
#
# def __str__(self):
# return self.name
#
# def double_age(self):
# return self.age*2
# double_age.short_description = "Double Age"
#
# class Book(models.Model):
# title = models.CharField("Title", max_length=128)
# author = models.ForeignKey(Author, on_delete=models.CASCADE)
# uuid = models.UUIDField(default=uuid.uuid4)
#
# class Meta:
# ordering = ('title',)
# verbose_name = "Book"
# verbose_name_plural = "Books"
#
# def __str__(self):
# return self.title
#
# Path: test/views.py
# class AuthorCrudViewset(PopupCrudViewSet):
# model = Author
# fields = ('name', 'age')
# list_display = ('name', 'age', 'half_age', 'double_age')
# list_url = reverse_lazy("authors")
# new_url = reverse_lazy("new-author")
# page_title = "Author List"
#
# """
# form_class = AuthorForm
# list_permission_required = ('tests.add_author',)
# create_permission_required = ('tests.add_author',)
# update_permission_required = ('tests.change_author',)
# delete_permission_required = ('tests.delete_author',)
# """
#
# def half_age(self, author):
# return int(author.age/2)
# half_age.short_description = "Half Age"
# half_age.order_field = 'age'
#
# def get_detail_url(self, obj):
# return reverse("author-detail", kwargs={'pk': obj.pk})
#
# def get_edit_url(self, obj):
# return reverse("edit-author", kwargs={'pk': obj.pk})
#
# def get_delete_url(self, obj):
# if obj.age < 18:
# return None
# return reverse("delete-author", kwargs={'pk': obj.pk})
#
# class BookCrudViewset(PopupCrudViewSet):
# model = Book
# form_class = BookForm
# list_display = ('title', 'author')
# list_url = reverse_lazy("books:list")
# new_url = reverse_lazy("books:create")
# related_object_popups = {
# 'author': reverse_lazy("new-author")
# }
# legacy_crud = True
# item_actions = [
# ('Up', 'glyphicon glyphicon-ok', 'up_vote'),
# ('Down', 'glyphicon glyphicon-remove', 'down_vote'),
# ]
#
# @staticmethod
# def get_edit_url(obj):
# return reverse_lazy("books:update", kwargs={'pk': obj.pk})
#
# @staticmethod
# def get_delete_url(obj):
# return reverse_lazy("books:delete", kwargs={'pk': obj.pk})
#
# @staticmethod
# def get_detail_url(obj):
# return reverse_lazy("books:detail", kwargs={'pk': obj.pk})
#
# def up_vote(self, request, book):
# return True, "Up vote successful"
#
# def down_vote(self, request, book):
# return True, "Down vote successful"
#
# class BookUUIDCrudViewSet(PopupCrudViewSet):
# '''CRUD views using slug field as url kwarg instead of the default pk'''
#
# model = Book
# form_class = BookForm
# list_display = ('title', 'author')
# list_url = reverse_lazy("uuidbooks:list")
# new_url = reverse_lazy("uuidbooks:create")
# pk_url_kwarg = None
# slug_field = 'uuid'
# slug_url_kwarg = 'uuid'
#
# @staticmethod
# def get_edit_url(obj):
# return reverse("uuidbooks:update", kwargs={'uuid': obj.uuid.hex})
#
# @staticmethod
# def get_delete_url(obj):
# return reverse("uuidbooks:delete", kwargs={'uuid': obj.uuid.hex})
#
# @staticmethod
# def get_detail_url(obj):
# return reverse("uuidbooks:detail", kwargs={'uuid': obj.uuid.hex})
. Output only the next line. | self.assertContains(response, "<td>13</td>") # Author.half_age |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
# pylint: skip-file
try:
except expression as identifier:
RE_CREATE_EDIT_FORM = r"\n<form class=\'form-horizontal\' id=\'create-edit-form\' action=\'{0}\' method=\'post\' accept-charset=\'utf-8\'>.*</form>"
MODAL_PATTERNS = [
<|code_end|>
, predict the next line using imports from the current file:
import re
import json
import six
from django.test import TestCase
from django.http import JsonResponse
from django.urls import reverse
from django.core.urlresolvers import reverse
from .models import Author, Book
from .views import AuthorCrudViewset, BookCrudViewset, BookUUIDCrudViewSet
from popupcrud.views import POPUPCRUD
and context including class names, function names, and sometimes code from other files:
# Path: test/models.py
# class Author(models.Model):
# name = models.CharField("Name", max_length=128)
# age = models.SmallIntegerField("Age", null=True, blank=True)
#
# class Meta:
# ordering = ('name',)
# verbose_name = "Author"
# verbose_name_plural = "Authors"
#
# def __str__(self):
# return self.name
#
# def double_age(self):
# return self.age*2
# double_age.short_description = "Double Age"
#
# class Book(models.Model):
# title = models.CharField("Title", max_length=128)
# author = models.ForeignKey(Author, on_delete=models.CASCADE)
# uuid = models.UUIDField(default=uuid.uuid4)
#
# class Meta:
# ordering = ('title',)
# verbose_name = "Book"
# verbose_name_plural = "Books"
#
# def __str__(self):
# return self.title
#
# Path: test/views.py
# class AuthorCrudViewset(PopupCrudViewSet):
# model = Author
# fields = ('name', 'age')
# list_display = ('name', 'age', 'half_age', 'double_age')
# list_url = reverse_lazy("authors")
# new_url = reverse_lazy("new-author")
# page_title = "Author List"
#
# """
# form_class = AuthorForm
# list_permission_required = ('tests.add_author',)
# create_permission_required = ('tests.add_author',)
# update_permission_required = ('tests.change_author',)
# delete_permission_required = ('tests.delete_author',)
# """
#
# def half_age(self, author):
# return int(author.age/2)
# half_age.short_description = "Half Age"
# half_age.order_field = 'age'
#
# def get_detail_url(self, obj):
# return reverse("author-detail", kwargs={'pk': obj.pk})
#
# def get_edit_url(self, obj):
# return reverse("edit-author", kwargs={'pk': obj.pk})
#
# def get_delete_url(self, obj):
# if obj.age < 18:
# return None
# return reverse("delete-author", kwargs={'pk': obj.pk})
#
# class BookCrudViewset(PopupCrudViewSet):
# model = Book
# form_class = BookForm
# list_display = ('title', 'author')
# list_url = reverse_lazy("books:list")
# new_url = reverse_lazy("books:create")
# related_object_popups = {
# 'author': reverse_lazy("new-author")
# }
# legacy_crud = True
# item_actions = [
# ('Up', 'glyphicon glyphicon-ok', 'up_vote'),
# ('Down', 'glyphicon glyphicon-remove', 'down_vote'),
# ]
#
# @staticmethod
# def get_edit_url(obj):
# return reverse_lazy("books:update", kwargs={'pk': obj.pk})
#
# @staticmethod
# def get_delete_url(obj):
# return reverse_lazy("books:delete", kwargs={'pk': obj.pk})
#
# @staticmethod
# def get_detail_url(obj):
# return reverse_lazy("books:detail", kwargs={'pk': obj.pk})
#
# def up_vote(self, request, book):
# return True, "Up vote successful"
#
# def down_vote(self, request, book):
# return True, "Down vote successful"
#
# class BookUUIDCrudViewSet(PopupCrudViewSet):
# '''CRUD views using slug field as url kwarg instead of the default pk'''
#
# model = Book
# form_class = BookForm
# list_display = ('title', 'author')
# list_url = reverse_lazy("uuidbooks:list")
# new_url = reverse_lazy("uuidbooks:create")
# pk_url_kwarg = None
# slug_field = 'uuid'
# slug_url_kwarg = 'uuid'
#
# @staticmethod
# def get_edit_url(obj):
# return reverse("uuidbooks:update", kwargs={'uuid': obj.uuid.hex})
#
# @staticmethod
# def get_delete_url(obj):
# return reverse("uuidbooks:delete", kwargs={'uuid': obj.uuid.hex})
#
# @staticmethod
# def get_detail_url(obj):
# return reverse("uuidbooks:detail", kwargs={'uuid': obj.uuid.hex})
. Output only the next line. | r'<div class="modal fade".*id="create-edit-modal"', |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
# pylint: skip-file
try:
except expression as identifier:
RE_CREATE_EDIT_FORM = r"\n<form class=\'form-horizontal\' id=\'create-edit-form\' action=\'{0}\' method=\'post\' accept-charset=\'utf-8\'>.*</form>"
MODAL_PATTERNS = [
r'<div class="modal fade".*id="create-edit-modal"',
r'<div class="modal fade".*id="delete-modal"',
r'<div class="modal fade".*id="action-result-modal"',
r'<div class="modal fade".*id="add-related-modal"',
]
class PopupCrudViewSetTests(TestCase):
def test_settings(self):
self.assertEquals(POPUPCRUD['base_template'], "test/base.html")
def test_template(self):
author = Author.objects.create(name="John", age=26)
response = self.client.get(reverse("authors"))
self.assertTemplateUsed(response, "popupcrud/list.html")
# template should have the three embedded bootstrap modals
for pattern in MODAL_PATTERNS:
self.assertTrue(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import json
import six
from django.test import TestCase
from django.http import JsonResponse
from django.urls import reverse
from django.core.urlresolvers import reverse
from .models import Author, Book
from .views import AuthorCrudViewset, BookCrudViewset, BookUUIDCrudViewSet
from popupcrud.views import POPUPCRUD
and context:
# Path: test/models.py
# class Author(models.Model):
# name = models.CharField("Name", max_length=128)
# age = models.SmallIntegerField("Age", null=True, blank=True)
#
# class Meta:
# ordering = ('name',)
# verbose_name = "Author"
# verbose_name_plural = "Authors"
#
# def __str__(self):
# return self.name
#
# def double_age(self):
# return self.age*2
# double_age.short_description = "Double Age"
#
# class Book(models.Model):
# title = models.CharField("Title", max_length=128)
# author = models.ForeignKey(Author, on_delete=models.CASCADE)
# uuid = models.UUIDField(default=uuid.uuid4)
#
# class Meta:
# ordering = ('title',)
# verbose_name = "Book"
# verbose_name_plural = "Books"
#
# def __str__(self):
# return self.title
#
# Path: test/views.py
# class AuthorCrudViewset(PopupCrudViewSet):
# model = Author
# fields = ('name', 'age')
# list_display = ('name', 'age', 'half_age', 'double_age')
# list_url = reverse_lazy("authors")
# new_url = reverse_lazy("new-author")
# page_title = "Author List"
#
# """
# form_class = AuthorForm
# list_permission_required = ('tests.add_author',)
# create_permission_required = ('tests.add_author',)
# update_permission_required = ('tests.change_author',)
# delete_permission_required = ('tests.delete_author',)
# """
#
# def half_age(self, author):
# return int(author.age/2)
# half_age.short_description = "Half Age"
# half_age.order_field = 'age'
#
# def get_detail_url(self, obj):
# return reverse("author-detail", kwargs={'pk': obj.pk})
#
# def get_edit_url(self, obj):
# return reverse("edit-author", kwargs={'pk': obj.pk})
#
# def get_delete_url(self, obj):
# if obj.age < 18:
# return None
# return reverse("delete-author", kwargs={'pk': obj.pk})
#
# class BookCrudViewset(PopupCrudViewSet):
# model = Book
# form_class = BookForm
# list_display = ('title', 'author')
# list_url = reverse_lazy("books:list")
# new_url = reverse_lazy("books:create")
# related_object_popups = {
# 'author': reverse_lazy("new-author")
# }
# legacy_crud = True
# item_actions = [
# ('Up', 'glyphicon glyphicon-ok', 'up_vote'),
# ('Down', 'glyphicon glyphicon-remove', 'down_vote'),
# ]
#
# @staticmethod
# def get_edit_url(obj):
# return reverse_lazy("books:update", kwargs={'pk': obj.pk})
#
# @staticmethod
# def get_delete_url(obj):
# return reverse_lazy("books:delete", kwargs={'pk': obj.pk})
#
# @staticmethod
# def get_detail_url(obj):
# return reverse_lazy("books:detail", kwargs={'pk': obj.pk})
#
# def up_vote(self, request, book):
# return True, "Up vote successful"
#
# def down_vote(self, request, book):
# return True, "Down vote successful"
#
# class BookUUIDCrudViewSet(PopupCrudViewSet):
# '''CRUD views using slug field as url kwarg instead of the default pk'''
#
# model = Book
# form_class = BookForm
# list_display = ('title', 'author')
# list_url = reverse_lazy("uuidbooks:list")
# new_url = reverse_lazy("uuidbooks:create")
# pk_url_kwarg = None
# slug_field = 'uuid'
# slug_url_kwarg = 'uuid'
#
# @staticmethod
# def get_edit_url(obj):
# return reverse("uuidbooks:update", kwargs={'uuid': obj.uuid.hex})
#
# @staticmethod
# def get_delete_url(obj):
# return reverse("uuidbooks:delete", kwargs={'uuid': obj.uuid.hex})
#
# @staticmethod
# def get_detail_url(obj):
# return reverse("uuidbooks:detail", kwargs={'uuid': obj.uuid.hex})
which might include code, classes, or functions. Output only the next line. | re.search(pattern, response.content.decode('utf-8'))) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
#coding=utf-8
@permit.route('/host', u"主机管理", MenuRes, is_menu=True, order=3.0001)
class HostHandler(base.BaseHandler):
@authenticated
<|code_end|>
, predict the immediate next line with the help of imports:
import base
from toughnms.console.forms import host_form
from toughnms.console.handlers.base import MenuRes
from toughlib.permit import permit
from cyclone.web import authenticated
and context (classes, functions, sometimes code) from other files:
# Path: toughnms/console/forms/host_form.py
# def host_add_form(groups=[]):
# def host_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
. Output only the next line. | def get(self, template_variables={}): |
Using the snippet: <|code_start|>#!/usr/bin/env python
#coding=utf-8
@permit.route('/host', u"主机管理", MenuRes, is_menu=True, order=3.0001)
class HostHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
self.post()
@authenticated
def post(self,**kwargs):
group_name = self.get_argument("group_name",None)
all_hosts = self.nagapi.list_host(group_name)
groups = self.nagapi.list_hostgroup()
self.render('hosts.html',
curr_group=group_name,
hosts=all_hosts,
groups=groups
)
@permit.route('/host/add', u"主机新增", MenuRes, order=3.0002)
class HostAddHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
<|code_end|>
, determine the next line of code. You have imports:
import base
from toughnms.console.forms import host_form
from toughnms.console.handlers.base import MenuRes
from toughlib.permit import permit
from cyclone.web import authenticated
and context (class names, function names, or code) available:
# Path: toughnms/console/forms/host_form.py
# def host_add_form(groups=[]):
# def host_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
. Output only the next line. | groups = self.nagapi.list_hostgroup() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
#coding=utf-8
@permit.route('/status/hosts', u"主机状态", MenuRes, is_menu=True, order=7.0001)
class HostHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
<|code_end|>
with the help of current file imports:
import base
from toughnms.console.forms import host_form
from toughlib.permit import permit
from toughlib import utils,logger
from toughnms.console.handlers.base import MenuRes
from cyclone.web import authenticated
from toughnms.common.nagutils import STATUS,STYLE
from cyclone.web import authenticated
and context from other files:
# Path: toughnms/console/forms/host_form.py
# def host_add_form(groups=[]):
# def host_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/nagutils.py
# STATUS = {0: u"正常", 1: u"警告", 2:u"严重", 3: u"未知", 255: u"未知"}
#
# STYLE = {0: u"status_ok", 1: u"status_warn", 2: u"status_fail", 3: u"status_unknow", 255: u'status_unknow'}
, which may contain function names, class names, or code. Output only the next line. | return self.post() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
#coding=utf-8
@permit.route('/status/hosts', u"主机状态", MenuRes, is_menu=True, order=7.0001)
class HostHandler(base.BaseHandler):
@authenticated
<|code_end|>
using the current file's imports:
import base
from toughnms.console.forms import host_form
from toughlib.permit import permit
from toughlib import utils,logger
from toughnms.console.handlers.base import MenuRes
from cyclone.web import authenticated
from toughnms.common.nagutils import STATUS,STYLE
from cyclone.web import authenticated
and any relevant context from other files:
# Path: toughnms/console/forms/host_form.py
# def host_add_form(groups=[]):
# def host_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/nagutils.py
# STATUS = {0: u"正常", 1: u"警告", 2:u"严重", 3: u"未知", 255: u"未知"}
#
# STYLE = {0: u"status_ok", 1: u"status_warn", 2: u"status_fail", 3: u"status_unknow", 255: u'status_unknow'}
. Output only the next line. | def get(self, template_variables={}): |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
#coding=utf-8
@permit.route('/status/hosts', u"主机状态", MenuRes, is_menu=True, order=7.0001)
class HostHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
return self.post()
@authenticated
def post(self, template_variables={}):
<|code_end|>
, predict the next line using imports from the current file:
import base
from toughnms.console.forms import host_form
from toughlib.permit import permit
from toughlib import utils,logger
from toughnms.console.handlers.base import MenuRes
from cyclone.web import authenticated
from toughnms.common.nagutils import STATUS,STYLE
from cyclone.web import authenticated
and context including class names, function names, and sometimes code from other files:
# Path: toughnms/console/forms/host_form.py
# def host_add_form(groups=[]):
# def host_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/nagutils.py
# STATUS = {0: u"正常", 1: u"警告", 2:u"严重", 3: u"未知", 255: u"未知"}
#
# STYLE = {0: u"status_ok", 1: u"status_warn", 2: u"status_fail", 3: u"status_unknow", 255: u'status_unknow'}
. Output only the next line. | group_name = self.get_argument("group_name",None) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
#coding=utf-8
@permit.route('/perfdata', u"主机性能监控", MenuRes, is_menu=False, order=7.0001)
class HostPerfDataHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
return self.post(template_variables)
@authenticated
def post(self, template_variables={}):
day_code = self.get_argument("day_code",utils.get_currdate())
begin_time = utils.datetime2msec("%s 00:00:00"%day_code)
end_time = utils.datetime2msec("%s 23:59:59"%day_code)
logger.info("query perfdata %s -- %s"%(begin_time,end_time))
group_name = self.get_argument("group_name",None)
groups = self.nagapi.list_hostgroup()
all_hosts = self.nagapi.list_host(group_name)
host_name = self.get_argument("host_name",None)
host = self.nagapi.get_host(host_name)
self.render("host_perf.html",
groups=groups,
group_name=group_name,
host_name=host_name,
<|code_end|>
. Use current file imports:
import base
import time
from toughnms.console.forms import host_form
from toughlib.permit import permit
from toughlib import utils,logger
from toughnms.console.handlers.base import MenuRes
from cyclone.web import authenticated
from toughnms.common.nagutils import STATUS,STYLE
from cyclone.web import authenticated
and context (classes, functions, or code) from other files:
# Path: toughnms/console/forms/host_form.py
# def host_add_form(groups=[]):
# def host_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/nagutils.py
# STATUS = {0: u"正常", 1: u"警告", 2:u"严重", 3: u"未知", 255: u"未知"}
#
# STYLE = {0: u"status_ok", 1: u"status_warn", 2: u"status_fail", 3: u"status_unknow", 255: u'status_unknow'}
. Output only the next line. | host=host, |
Predict the next line after this snippet: <|code_start|>class HostPerfDiskHandler(base.BaseHandler):
@authenticated
def post(self, template_variables={}):
host_name = self.get_argument("host_name")
begin_time = self.get_argument("begin_time")
end_time = self.get_argument("end_time")
diskdata = self.mongodb.query_disk_perfdata(host_name,begin_time,end_time)
_data = [ (d['lastcheck']*1000,d['data'].get('part',"/"), d['data']['usage']) for d in diskdata if d['data']]
parts = {}
for lastcheck,part,usage in _data:
if part not in parts:
parts[part] = {'name':part,'data':[]}
_part_data = parts[part]
_part_data['data'].append([lastcheck,usage])
self.render_json(data=parts.values())
@permit.route('/perfdata/load_perf')
class HostPerfLoadHandler(base.BaseHandler):
@authenticated
def post(self, template_variables={}):
host_name = self.get_argument("host_name")
begin_time = self.get_argument("begin_time")
end_time = self.get_argument("end_time")
loaddata = self.mongodb.query_load_perfdata(host_name,begin_time,end_time)
load1 = {"name":u"1分钟负载","data":[]}
load5 = {"name":u"5分钟负载","data":[]}
load15 = {"name":u"15分钟负载","data":[]}
<|code_end|>
using the current file's imports:
import base
import time
from toughnms.console.forms import host_form
from toughlib.permit import permit
from toughlib import utils,logger
from toughnms.console.handlers.base import MenuRes
from cyclone.web import authenticated
from toughnms.common.nagutils import STATUS,STYLE
from cyclone.web import authenticated
and any relevant context from other files:
# Path: toughnms/console/forms/host_form.py
# def host_add_form(groups=[]):
# def host_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/nagutils.py
# STATUS = {0: u"正常", 1: u"警告", 2:u"严重", 3: u"未知", 255: u"未知"}
#
# STYLE = {0: u"status_ok", 1: u"status_warn", 2: u"status_fail", 3: u"status_unknow", 255: u'status_unknow'}
. Output only the next line. | for d in loaddata: |
Predict the next line after this snippet: <|code_start|> parts = {}
for lastcheck,part,usage in _data:
if part not in parts:
parts[part] = {'name':part,'data':[]}
_part_data = parts[part]
_part_data['data'].append([lastcheck,usage])
self.render_json(data=parts.values())
@permit.route('/perfdata/load_perf')
class HostPerfLoadHandler(base.BaseHandler):
@authenticated
def post(self, template_variables={}):
host_name = self.get_argument("host_name")
begin_time = self.get_argument("begin_time")
end_time = self.get_argument("end_time")
loaddata = self.mongodb.query_load_perfdata(host_name,begin_time,end_time)
load1 = {"name":u"1分钟负载","data":[]}
load5 = {"name":u"5分钟负载","data":[]}
load15 = {"name":u"15分钟负载","data":[]}
for d in loaddata:
_last_check = d['lastcheck']*1000
_data = d.get('data')
_load1 = _data['load1'] if _data is not None else 0
_load5 = _data['load5'] if _data is not None else 0
_load15 = _data['load15'] if _data is not None else 0
load1["data"].append([_last_check,_load1])
load5["data"].append([_last_check,_load5])
<|code_end|>
using the current file's imports:
import base
import time
from toughnms.console.forms import host_form
from toughlib.permit import permit
from toughlib import utils,logger
from toughnms.console.handlers.base import MenuRes
from cyclone.web import authenticated
from toughnms.common.nagutils import STATUS,STYLE
from cyclone.web import authenticated
and any relevant context from other files:
# Path: toughnms/console/forms/host_form.py
# def host_add_form(groups=[]):
# def host_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/nagutils.py
# STATUS = {0: u"正常", 1: u"警告", 2:u"严重", 3: u"未知", 255: u"未知"}
#
# STYLE = {0: u"status_ok", 1: u"status_warn", 2: u"status_fail", 3: u"status_unknow", 255: u'status_unknow'}
. Output only the next line. | load15["data"].append([_last_check,_load15]) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# coding:utf-8
###############################################################################
# password update
###############################################################################
@permit.route(r"/password", u"密码修改", MenuSys, order=1.0000)
class PasswordUpdateHandler(BaseHandler):
@authenticated
def get(self):
form = password_forms.password_update_form()
form.fill(tra_user=self.get_secure_cookie("tra_user"))
return self.render("base_form.html", form=form)
@authenticated
def post(self):
form = password_forms.password_update_form()
<|code_end|>
with the help of current file imports:
from toughlib import utils
from toughnms.console.handlers.base import BaseHandler, MenuSys
from toughlib.permit import permit
from toughnms.console import models
from toughnms.console.handlers import password_forms
from cyclone.web import authenticated
from hashlib import md5
and context from other files:
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
, which may contain function names, class names, or code. Output only the next line. | if not form.validates(source=self.get_params()): |
Using the snippet: <|code_start|>#!/usr/bin/env python
#coding=utf-8
@permit.route('/service', u"服务管理", MenuSys, order=4.0001)
class ServiceHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
host_name = self.get_argument("host_name",None)
services = self.nagapi.list_service(host_name) or []
self.render('services.html',host_name=host_name,services=services)
@permit.route('/service/add', u"服务新增", MenuSys, order=4.0002)
class serviceAddHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
host_name = self.get_argument("host_name",None)
form = service_form.service_add_form()
form.host_name.set_value(host_name)
self.render("service_form.html",
<|code_end|>
, determine the next line of code. You have imports:
import base
from toughnms.console.forms import service_form
from toughnms.console.handlers.base import MenuSys
from toughlib.permit import permit
from toughnms.common.cmdhelp import help_dict
from cyclone.web import authenticated
and context (class names, function names, or code) available:
# Path: toughnms/console/forms/service_form.py
# def service_add_form():
# def service_update_form():
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/cmdhelp.py
. Output only the next line. | form=form, |
Predict the next line for this snippet: <|code_start|> return
ret = self.nagapi.update_service(
form.d.service_id,
form.d.service_description,
form.d.check_command,
use = form.d.use,
notifications_enabled = form.d.notifications_enabled,
process_perf_data = form.d.process_perf_data,
max_check_attempts = form.d.max_check_attempts,
normal_check_interval = form.d.normal_check_interval or 5,
retry_check_interval = form.d.retry_check_interval or 1
)
if ret.code > 0:
self.render_error(msg=ret.msg)
else:
self.redirect('/service?host_name='+form.d.host_name, permanent=False)
@permit.route('/service/delete', u"服务删除", MenuSys, order=4.0004)
class ServiceDeleteHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
service_id = self.get_argument("service_id")
host_name = self.get_argument("host_name")
if not service_id:
raise ValueError("service_id is empty")
<|code_end|>
with the help of current file imports:
import base
from toughnms.console.forms import service_form
from toughnms.console.handlers.base import MenuSys
from toughlib.permit import permit
from toughnms.common.cmdhelp import help_dict
from cyclone.web import authenticated
and context from other files:
# Path: toughnms/console/forms/service_form.py
# def service_add_form():
# def service_update_form():
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/cmdhelp.py
, which may contain function names, class names, or code. Output only the next line. | ret = self.nagapi.del_service(service_id) |
Given the following code snippet before the placeholder: <|code_start|> return
ret = self.nagapi.add_service(
form.d.host_name,
form.d.service_description,
form.d.check_command,
use = form.d.use,
notifications_enabled = form.d.notifications_enabled,
max_check_attempts = form.d.max_check_attempts,
normal_check_interval = form.d.normal_check_interval or 5,
retry_check_interval = form.d.retry_check_interval or 1
)
if ret.code > 0:
self.render_error(msg=ret.msg)
else:
self.redirect('/service?host_name='+form.d.host_name, permanent=False)
@permit.route('/service/update', u"服务更新", MenuSys, order=4.0003)
class serviceUpdateHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
sid = self.get_argument("service_id")
form = service_form.service_update_form()
service = self.nagapi.get_service(sid)
if not service:
raise ValueError("service not exists")
form.fill(service)
<|code_end|>
, predict the next line using imports from the current file:
import base
from toughnms.console.forms import service_form
from toughnms.console.handlers.base import MenuSys
from toughlib.permit import permit
from toughnms.common.cmdhelp import help_dict
from cyclone.web import authenticated
and context including class names, function names, and sometimes code from other files:
# Path: toughnms/console/forms/service_form.py
# def service_add_form():
# def service_update_form():
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
#
# Path: toughnms/common/cmdhelp.py
. Output only the next line. | form.service_id.set_value(sid) |
Predict the next line after this snippet: <|code_start|>
@authenticated
def get(self, template_variables={}):
form = group_form.group_update_form()
group = self.nagapi.get_hostgroup(self.get_argument("group_name"))
if not group:
raise ValueError("group not exists")
form.fill(group)
self.render("base_form.html", form=form)
@authenticated
def post(self,**kwargs):
form = group_form.group_update_form()
if not form.validates(source=self.get_params()):
self.render("base_form.html", form=form)
return
group = self.nagapi.get_hostgroup(form.d.hostgroup_name)
if not group:
raise ValueError("group not exists")
ret = self.nagapi.update_hostgroup(form.d.hostgroup_name,form.d.alias)
if ret.code > 0:
self.render_error(msg=ret.msg)
else:
self.redirect('/group', permanent=False)
@permit.route('/group/delete', u"主机分组新增", MenuRes, order=3.0004)
class GroupDeleteHandler(base.BaseHandler):
<|code_end|>
using the current file's imports:
import base
from toughnms.console.forms import group_form
from toughlib.permit import permit
from toughnms.console.handlers.base import MenuRes
from cyclone.web import authenticated
and any relevant context from other files:
# Path: toughnms/console/forms/group_form.py
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
. Output only the next line. | @authenticated |
Given the following code snippet before the placeholder: <|code_start|> @authenticated
def get(self, template_variables={}):
form = group_form.group_add_form()
self.render('base_form.html',form=form)
@authenticated
def post(self,**kwargs):
form = group_form.group_add_form()
if not form.validates(source=self.get_params()):
self.render("base_form.html", form=form)
return
ret = self.nagapi.add_hostgroup(form.d.hostgroup_name,form.d.alias)
if ret.code > 0:
self.render_error(msg=ret.msg)
else:
self.redirect('/group', permanent=False)
@permit.route('/group/update', u"主机分组更新", MenuRes, order=3.0003)
class GroupUpdateHandler(base.BaseHandler):
@authenticated
def get(self, template_variables={}):
form = group_form.group_update_form()
group = self.nagapi.get_hostgroup(self.get_argument("group_name"))
if not group:
raise ValueError("group not exists")
form.fill(group)
self.render("base_form.html", form=form)
<|code_end|>
, predict the next line using imports from the current file:
import base
from toughnms.console.forms import group_form
from toughlib.permit import permit
from toughnms.console.handlers.base import MenuRes
from cyclone.web import authenticated
and context including class names, function names, and sometimes code from other files:
# Path: toughnms/console/forms/group_form.py
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
. Output only the next line. | @authenticated |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# coding:utf-8
@permit.route(r"/sendmail", u"发送邮件", MenuSys, order=6.0000)
class SendMailHandler(BaseHandler):
def send_mail(self, mailto, topic, content):
smtp_server = self.get_param_value("smtp_server",'127.0.0.1')
from_addr = self.get_param_value("smtp_from")
smtp_port = int(self.get_param_value("smtp_port",25))
smtp_user = self.get_param_value("smtp_user",None)
smtp_pwd = self.get_param_value("smtp_pwd",None)
return sendmail(server=smtp_server, port=smtp_port,user=smtp_user, password=smtp_pwd,
from_addr=from_addr, mailto=mailto, topic=topic, content=content)
def get(self):
token = self.get_argument("token",None)
if not token or token not in md5(self.settings.config.system.secret.encode('utf-8')).hexdigest():
return self.render_json(code=1,msg=u"token invalid")
<|code_end|>
. Write the next line using the current file imports:
from hashlib import md5
from toughlib import utils,logger
from toughnms.console.handlers.base import BaseHandler, MenuSys
from toughlib.permit import permit
from toughnms.console import models
from cyclone.web import authenticated
from toughlib.mail import send_mail as sendmail
from email.mime.text import MIMEText
from email import Header
and context from other files:
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
, which may include functions, classes, or code. Output only the next line. | mailto = self.get_argument('mailto') |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# coding:utf-8
@permit.route(r"/sendmail", u"发送邮件", MenuSys, order=6.0000)
class SendMailHandler(BaseHandler):
def send_mail(self, mailto, topic, content):
smtp_server = self.get_param_value("smtp_server",'127.0.0.1')
from_addr = self.get_param_value("smtp_from")
smtp_port = int(self.get_param_value("smtp_port",25))
smtp_user = self.get_param_value("smtp_user",None)
smtp_pwd = self.get_param_value("smtp_pwd",None)
return sendmail(server=smtp_server, port=smtp_port,user=smtp_user, password=smtp_pwd,
from_addr=from_addr, mailto=mailto, topic=topic, content=content)
def get(self):
token = self.get_argument("token",None)
if not token or token not in md5(self.settings.config.system.secret.encode('utf-8')).hexdigest():
return self.render_json(code=1,msg=u"token invalid")
mailto = self.get_argument('mailto')
topic = self.get_argument('topic')
ctx = self.get_argument('content')
logger.info("sendmail: %s %s %s"% (mailto, utils.safeunicode(topic), utils.safeunicode(ctx)))
self.send_mail(mailto, topic, ctx).addCallbacks(logger.info,logger.error)
<|code_end|>
with the help of current file imports:
from hashlib import md5
from toughlib import utils,logger
from toughnms.console.handlers.base import BaseHandler, MenuSys
from toughlib.permit import permit
from toughnms.console import models
from cyclone.web import authenticated
from toughlib.mail import send_mail as sendmail
from email.mime.text import MIMEText
from email import Header
and context from other files:
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
, which may contain function names, class names, or code. Output only the next line. | self.mongodb.add_mail_alert(mailto,ctx) |
Based on the snippet: <|code_start|> all_contacts = self.nagapi.list_contact()
self.render('contacts.html',contacts=all_contacts)
@permit.route('/contact/add', u"联系人新增", MenuSys, order=2.0002)
class ContactAddHandler(GroupHandler):
@authenticated
def get(self,template_variables={}):
form = contact_form.contact_add_form(self.get_groups())
self.render('base_form.html',form=form)
@authenticated
def post(self,**kwargs):
form = contact_form.contact_add_form(self.get_groups())
if not form.validates(source=self.get_params()):
return self.render("base_form.html", form=form)
ret = self.nagapi.add_contact(
form.d.contact_name,
form.d.alias,
form.d.email,
form.d.contactgroup_name,
pager=form.d.pager
)
if ret.code > 0:
self.render_error(msg=ret.msg)
else:
<|code_end|>
, predict the immediate next line with the help of imports:
import base
from toughnms.console.forms import contact_form
from toughnms.console.handlers.base import MenuSys
from toughnms.console.settings import *
from toughlib.permit import permit
from cyclone.web import authenticated
and context (classes, functions, sometimes code) from other files:
# Path: toughnms/console/forms/contact_form.py
# def contact_add_form(groups=[]):
# def contact_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
. Output only the next line. | self.redirect('/contact', permanent=False) |
Continue the code snippet: <|code_start|>
@permit.route('/contact', u"联系人管理", MenuSys, is_menu=True, order=2.0001)
class ContactHandler(GroupHandler):
@authenticated
def get(self, template_variables={}):
self.post()
@authenticated
def post(self,**kwargs):
all_contacts = self.nagapi.list_contact()
self.render('contacts.html',contacts=all_contacts)
@permit.route('/contact/add', u"联系人新增", MenuSys, order=2.0002)
class ContactAddHandler(GroupHandler):
@authenticated
def get(self,template_variables={}):
form = contact_form.contact_add_form(self.get_groups())
self.render('base_form.html',form=form)
@authenticated
def post(self,**kwargs):
form = contact_form.contact_add_form(self.get_groups())
if not form.validates(source=self.get_params()):
return self.render("base_form.html", form=form)
<|code_end|>
. Use current file imports:
import base
from toughnms.console.forms import contact_form
from toughnms.console.handlers.base import MenuSys
from toughnms.console.settings import *
from toughlib.permit import permit
from cyclone.web import authenticated
and context (classes, functions, or code) from other files:
# Path: toughnms/console/forms/contact_form.py
# def contact_add_form(groups=[]):
# def contact_update_form(groups=[]):
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
. Output only the next line. | ret = self.nagapi.add_contact( |
Given snippet: <|code_start|>#!/usr/bin/env python
# coding:utf-8
@permit.route(r"/config", u"参数配置管理", MenuSys, order=1.0011, is_menu=True)
class ConfigHandler(base.BaseHandler):
@authenticated
def get(self):
active = self.get_argument("active", "default")
default_form = config_forms.default_form()
default_form.fill(self.settings.config.system)
database_form = config_forms.database_form()
database_form.fill(self.settings.config.database)
nagios_form = config_forms.nagios_form()
nagios_form.fill(self.settings.config.nagios)
mail_form = config_forms.mail_form()
fparam = {}
for p in self.db.query(models.TlParam):
fparam[p.param_name] = p.param_value
for form in (mail_form,):
form.fill(fparam)
self.render("config.html",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import cyclone.auth
import cyclone.escape
import cyclone.web
import base
import ConfigParser
from toughlib import utils, logger, dispatch
from toughnms.console.forms import config_forms
from toughnms.console.handlers.base import MenuSys
from toughnms.console.settings import *
from toughlib.permit import permit
from cyclone.web import authenticated
from toughnms.console import models
from toughlib import dispatch,db_cache
from hashlib import md5
and context:
# Path: toughnms/console/forms/config_forms.py
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
which might include code, classes, or functions. Output only the next line. | active=active, |
Given snippet: <|code_start|> with open("/var/toughnms/token","wb") as tf:
tf.write(md5(new_secret).hexdigest())
self.render_json(code=0)
@permit.route(r"/config/database/update", u"数据库配置", MenuSys, order=1.0023)
class DatabaseHandler(base.BaseHandler):
@cyclone.web.authenticated
def post(self):
config = self.settings.config
config.database.echo = self.get_argument("echo")
config.database.dbtype = self.get_argument("dbtype")
config.database.dburl = self.get_argument("dburl")
config.database.pool_size = self.get_argument("pool_size")
config.database.pool_recycle = self.get_argument("pool_recycle")
config.database.backup_path = self.get_argument("backup_path")
config.update()
self.redirect("/config?active=database")
@permit.route(r"/config/nagios/update", u"nagios配置", MenuSys, order=1.0024)
class NagiosHandler(base.BaseHandler):
@cyclone.web.authenticated
def post(self):
config = self.settings.config
config.nagios.nagios_bin = self.get_argument("nagios_bin")
config.nagios.nagios_service = self.get_argument("nagios_service")
config.nagios.nagios_cfg = self.get_argument("nagios_cfg")
config.nagios.nagios_host_group_cfg = self.get_argument("nagios_host_group_cfg")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import cyclone.auth
import cyclone.escape
import cyclone.web
import base
import ConfigParser
from toughlib import utils, logger, dispatch
from toughnms.console.forms import config_forms
from toughnms.console.handlers.base import MenuSys
from toughnms.console.settings import *
from toughlib.permit import permit
from cyclone.web import authenticated
from toughnms.console import models
from toughlib import dispatch,db_cache
from hashlib import md5
and context:
# Path: toughnms/console/forms/config_forms.py
#
# Path: toughnms/console/handlers/base.py
# class BaseHandler(cyclone.web.RequestHandler):
# def __init__(self, *argc, **argkw):
# def initialize(self):
# def on_finish(self):
# def get_error_html(self, status_code=500, **kwargs):
# def render(self, template_name, **template_vars):
# def render_error(self, **template_vars):
# def _write(self, resp):
# def render_json(self, **template_vars):
# def render_string(self, template_name, **template_vars):
# def render_from_string(self, template_string, **template_vars):
# def make_sign(self, secret, params=[]):
# def check_sign(self, secret, msg):
# def get_page_data(self, query):
# def get_mdb_page_data(self, query):
# def get_page_url(self, page, form_id=None):
# def get_current_user(self):
# def get_params(self):
# def get_params_obj(self, obj):
# def get_param_value(self, name, defval=None):
# def export_file(self, filename, data):
which might include code, classes, or functions. Output only the next line. | config.nagios.nagios_contact_cfg = self.get_argument("nagios_contact_cfg") |
Given the code snippet: <|code_start|>
class AlwaysTrueExit(Exit):
def __init__(self, name=None):
super().__init__(name=name)
def can_exit(self, trade):
<|code_end|>
, generate the next line using the imports in this file:
from zaifbot.rules.exit.base import Exit
and context (functions, classes, or occasionally code) from other files:
# Path: zaifbot/rules/exit/base.py
# class Exit(Rule):
# def __init__(self, name=None):
# self.name = name or self.__class__.__name__
#
# def can_exit(self, trade):
# raise NotImplementedError
#
# @staticmethod
# def exit(trade):
# trade.exit()
. Output only the next line. | return True |
Given the code snippet: <|code_start|>
class ZaifBot(Flask):
def __init__(self, import_name):
super().__init__(import_name)
self.portfolio = Portfolio()
def register_strategies(self, strategy, *strategies):
self.portfolio.register_strategies(strategy, *strategies)
def start(self, *, sec_wait=1, host=None, port=None, debug=None, **options):
self.portfolio.start(sec_wait=sec_wait)
<|code_end|>
, generate the next line using the imports in this file:
from zaifbot.trade.portfolio import Portfolio
from flask import Flask
and context (functions, classes, or occasionally code) from other files:
# Path: zaifbot/trade/portfolio.py
# class Portfolio:
# def __init__(self):
# self._strategies = dict()
#
# def register_strategies(self, strategy, *strategies):
# for strategy in itertools.chain((strategy,), strategies):
# self._strategies[strategy.id_] = dict()
# self._strategies[strategy.id_]['strategy'] = strategy
#
# def start(self, *, sec_wait=1):
# strategies = self.collect_strategies()
# for strategy in strategies:
# self._thread_start(strategy, sec_wait=sec_wait)
#
# def find_strategy(self, id_):
# strategy = self._strategies.get(id_, {})
# return strategy.get('strategy', None)
#
# def find_thread(self, id_):
# strategy = self._strategies.get(id_, {})
# return strategy.get('thread', None)
#
# def remove(self, id_):
# if id_ in self._strategies:
# del self._strategies[id_]
#
# def collect_strategies(self):
# return [strategy['strategy'] for strategy in self._strategies.values()]
#
# def collect_threads(self):
# return [strategy['thread'] for strategy in self._strategies.values()]
#
# def _thread_start(self, strategy, *, sec_wait=1):
# thread = Thread(target=strategy.start,
# kwargs={'sec_wait': sec_wait},
# daemon=True)
# thread.start()
# self._strategies[strategy.id_]['thread'] = thread
. Output only the next line. | self.run(host, port, debug, **options) |
Using the snippet: <|code_start|>
def install_ta_lib():
if sys.platform.startswith('linux'):
# fixme
cwd = os.path.dirname(__file__)
subprocess.call(['tar', '-xzf', 'ta-lib-0.4.0-src.tar.gz'], cwd=cwd)
talib_path = os.path.join(cwd, 'ta-lib')
subprocess.call(['./configure', '--prefix=/usr'], cwd=talib_path, shell=True)
subprocess.call(['make'], cwd=talib_path, shell=True)
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import subprocess
from zaifbot.errors import ZaifBotError
and context (class names, function names, or code) available:
# Path: zaifbot/errors.py
# class ZaifBotError(Exception):
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return str(self.message)
. Output only the next line. | subprocess.call(['sudo', 'make', 'install'], cwd=talib_path) |
Using the snippet: <|code_start|> 3600,
1800,
900,
300,
60,
]
def test_init(self):
day1 = Period('1d')
day2 = Period(86400)
day3 = Period(self.one_day)
self.assertEqual(day1, day2)
self.assertEqual(day1, day3)
def test_label(self):
for label in self.labels:
period = Period(label)
self.assertEqual(period.label, label)
def test_sec(self):
for sec in self.secs:
period = Period(sec)
self.assertEqual(period.sec, sec)
def test_label_from_sec(self):
length = len(self.labels)
for i in range(length):
period = Period(self.labels[i])
self.assertEqual(period.sec, self.secs[i])
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from zaifbot.exchange import Period
and context (class names, function names, or code) available:
# Path: zaifbot/exchange/period.py
# def Period(period):
# for cls in _TradePeriod.__subclasses__():
# if isinstance(period, str):
# if cls.is_my_label(period):
# return cls(period)
# continue
#
# if isinstance(period, int):
# if cls.is_my_sec(period):
# return cls(period)
# continue
#
# if isinstance(period, _TradePeriod):
# return period
#
# raise ValueError('illegal argument received')
. Output only the next line. | def test_sec_from_label(self): |
Here is a snippet: <|code_start|>
def __str__(self):
return self._name
@property
def name(self):
return self._name
@property
def info(self):
return self._info
@property
def is_token(self):
return self._info['is_token']
class _ZaifCurrencyPairsInfo:
_instance = None
_lock = Lock()
_currency_pairs = None
def __new__(cls):
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
api = BotPublicApi()
cls._currency_pairs = api.currency_pairs('all')
return cls._instance
<|code_end|>
. Write the next line using the current file imports:
from threading import Lock
from zaifbot.exchange.api.http import BotPublicApi
and context from other files:
# Path: zaifbot/exchange/api/http.py
# class BotPublicApi(ZaifPublicApi):
#
# @_with_retry
# def last_price(self, currency_pair):
# return super().last_price(str(currency_pair))
#
# @_with_retry
# def ticker(self, currency_pair):
# return super().ticker(currency_pair)
#
# @_with_retry
# def trades(self, currency_pair):
# return super().trades(currency_pair)
#
# @_with_retry
# def depth(self, currency_pair):
# return super().depth(currency_pair)
#
# @_with_retry
# def currency_pairs(self, currency_pair):
# return super().currency_pairs(currency_pair)
#
# @_with_retry
# def currencies(self, currency):
# return super().currencies(currency)
, which may include functions, classes, or code. Output only the next line. | def __getitem__(self, currency_pair): |
Using the snippet: <|code_start|>
class MACD(Indicator):
_NAME = 'macd'
def __init__(self, currency_pair='btc_jpy', period='1d', short=12, long=26, signal=9):
super().__init__(currency_pair, period)
self._short = self._bounded_length(short)
self._long = self._bounded_length(long)
self._signal = self._bounded_length(signal)
def request_data(self, count=100, to_epoch_time=None):
candlesticks_df = self._get_candlesticks_df(count, to_epoch_time)
macd = self._exec_talib_func(candlesticks_df,
price='close',
<|code_end|>
, determine the next line of code. You have imports:
import pandas as pd
from .indicator import Indicator
and context (class names, function names, or code) available:
# Path: zaifbot/indicators/indicator.py
# class Indicator(metaclass=ABCMeta):
# _MAX_LENGTH = 100
# _MAX_COUNT = 1000
# _NAME = None
#
# def __init__(self, currency_pair, period):
# self._currency_pair = CurrencyPair(currency_pair)
# self._period = Period(period)
#
# @abstractmethod
# def request_data(self, *args, **kwargs):
# raise NotImplementedError
#
# def _exec_talib_func(self, *args, **kwargs):
# return abstract.Function(self.name)(*args, **kwargs)
#
# def _get_candlesticks_df(self, count, to_epoch_time):
# required_data_count = self._required_candlesticks_count(count)
#
# candle_sticks_data = CandleSticks(
# self._currency_pair,
# self._period
# ).request_data(required_data_count, to_epoch_time)
#
# return DataFrame(candle_sticks_data)
#
# @property
# def name(self):
# return self._NAME
#
# @classmethod
# def _bounded_length(cls, value):
# return min(max(value, 0), cls._MAX_LENGTH)
#
# @classmethod
# def _bounded_count(cls, value):
# return min(max(value, 0), cls._MAX_COUNT)
#
# @abstractmethod
# def _required_candlesticks_count(self, count):
# raise NotImplementedError
. Output only the next line. | fastperiod=self._short, |
Predict the next line for this snippet: <|code_start|> self._trade.action = 'bid'
self._trade2.action = 'ask'
results = (self._trade.is_long, self._trade2.is_long)
expected = (True, False)
self.assertEqual(results, expected)
def test_is_short(self):
self._trade.action = 'bid'
self._trade2.action = 'ask'
results = (self._trade.is_short, self._trade2.is_short)
expected = (False, True)
self.assertEqual(results, expected)
def test_is_closed(self):
self._trade.closed = True
self._trade2.closed = False
results = (self._trade.is_closed, self._trade2.is_closed)
expected = (True, False)
self.assertEqual(results, expected)
def test_profit(self):
self._trade.action = 'bid'
self._trade.entry_price = 100
self._trade.exit_price = 200
self._trade2.action = 'ask'
self._trade2.entry_price = 100
self._trade2.exit_price = 200
<|code_end|>
with the help of current file imports:
import unittest
from zaifbot.trade.trade import Trade
and context from other files:
# Path: zaifbot/trade/trade.py
# class Trade:
# def __init__(self):
# self.currency_pair = None
# self.entry_datetime = None
# self.entry_price = None
# self.amount = None
# self.action = None
# self.exit_price = None
# self.exit_datetime = None
# self.id_ = None
# self.closed = False
# self._trade_api = BotTradeApi()
# self._dao = TradesDao()
# self.strategy_name = None
# self.process_id = None
#
# def entry(self, currency_pair, amount, action):
# self.currency_pair = CurrencyPair(currency_pair)
# self.amount = amount
# self.entry_price = self._rounded_last_price()
# self.action = Action(action)
# self.entry_datetime = datetime.now()
#
# self._trade_api.trade(currency_pair=self.currency_pair,
# amount=self.amount,
# price=self.entry_price,
# action=self.action)
#
# trade_obj = self._dao.create(currency_pair=self.currency_pair.name,
# amount=self.amount,
# entry_price=self.entry_price,
# action=self.action.name,
# strategy_name=self.strategy_name,
# process_id=self.process_id)
#
# self.id_ = trade_obj.id_
# self._logging_entry()
#
# def exit(self):
# self.exit_price = self._rounded_last_price()
# self.exit_datetime = datetime.now()
#
# self._trade_api.trade(currency_pair=self.currency_pair,
# amount=self.amount,
# price=self.exit_price,
# action=self.action.opposite_action())
#
# self.closed = True
#
# self._dao.update(id_=self.id_,
# exit_price=self.exit_price,
# exit_datetime=self.exit_datetime,
# profit=self.profit(),
# closed=self.closed)
#
# self._logging_exit()
#
# def profit(self):
# if self.action == Buy:
# return self.exit_price - self.entry_price
# else:
# return self.entry_price - self.exit_price
#
# @property
# def is_short(self):
# return self.action == Sell
#
# @property
# def is_long(self):
# return self.action == Buy
#
# @property
# def is_closed(self):
# return self.closed
#
# def _logging_entry(self):
# log_frame = "Entry: {{trade_id: {}, currency_pair: {}, action: {}," \
# " amount: {}, entry_price: {}, entry_datetime: {}}}"
# log_msg = log_frame.format(self.id_, self.currency_pair, self.action,
# self.amount, self.entry_price, self.entry_datetime)
# trade_logger.info(log_msg, extra={'strategyid': self._strategy_descriptor()})
#
# def _logging_exit(self):
# log_frame = "Exit: {{trade_id: {}, currency_pair: {}, exit_price: {}, exit_datetime: {}}}"
# log_msg = log_frame.format(self.id_, self.currency_pair, self.exit_price, self.exit_datetime)
# trade_logger.info(log_msg, extra={'strategyid': self._strategy_descriptor()})
#
# def _strategy_descriptor(self):
# return self.strategy_name or self.process_id[:12] or ''
#
# def _rounded_last_price(self):
# tick = Tick(self.currency_pair)
# price = last_price(self.currency_pair)
# return tick.truncate_price(price)
, which may contain function names, class names, or code. Output only the next line. | results = (self._trade.profit(), self._trade2.profit()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.