Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>
PM_ID = "private_message"
# Define models
PMParticipants = db.Table('{}_participants'.format(PM_ID),
db.Column('user_id',
db.Integer(),
db.ForeignKey(User.id),
nullable=False),
db.Column('pm_id',
db.Integer(),
db.ForeignKey("objects.id"),
nullable=False))
class PrivateMessage(Object):
__mapper_args__ = {
'polymorphic_identity': PM_ID
}
title = PayloadProperty('title')
# db.Column(db.String(255), nullable=False)
participants = db.relationship('User', secondary=PMParticipants,
backref=db.backref('{}s'.format(PM_ID),
<|code_end|>
. Use current file imports:
from beavy.models.object import Object
from beavy.models.object import User
from beavy.common.payload_property import PayloadProperty
from beavy.utils.url_converters import ModelConverter
from beavy.app import db
and context (classes, functions, or code) from other files:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/models/object.py
# class ObjectQuery(AccessQuery):
# class Object(db.Model):
# class Capabilities(Enum):
# def by_capability(self, aborting=True, abort_code=404, *caps):
# def with_my_activities(self):
#
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
#
# Path: beavy/utils/url_converters.py
# class ModelConverter(BaseConverter):
# __OBJECTS__ = {
# 'user': User,
# 'object': Object,
# 'activity': Activity
# }
#
# def __init__(self, url_map, obj="object"):
# super(ModelConverter, self).__init__(url_map)
# # match ID or string
# self.regex = '-?\d+|\S+'
# self.cls = self.__OBJECTS__[obj]
#
# def to_python(self, value):
# cls = self.cls
# try:
# return cls.query.get_or_404(int(value))
# except ValueError:
# pass
#
# if not getattr(cls, "__LOOKUP_ATTRS__", False):
# abort(404)
#
# return cls.query.filter(or_(*[getattr(cls, key) == value
# for key in cls.__LOOKUP_ATTRS__])
# ).first_or_404()
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | lazy='dynamic')) |
Predict the next line for this snippet: <|code_start|>
class ModelConverter(BaseConverter):
__OBJECTS__ = {
'user': User,
'object': Object,
'activity': Activity
}
def __init__(self, url_map, obj="object"):
super(ModelConverter, self).__init__(url_map)
# match ID or string
self.regex = '-?\d+|\S+'
self.cls = self.__OBJECTS__[obj]
def to_python(self, value):
cls = self.cls
try:
return cls.query.get_or_404(int(value))
except ValueError:
pass
if not getattr(cls, "__LOOKUP_ATTRS__", False):
abort(404)
return cls.query.filter(or_(*[getattr(cls, key) == value
for key in cls.__LOOKUP_ATTRS__])
<|code_end|>
with the help of current file imports:
from sqlalchemy.sql import or_
from flask import abort
from werkzeug.routing import BaseConverter
from ..models.user import User
from ..models.activity import Activity
from ..models.object import Object
and context from other files:
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
# __LOOKUP_ATTRS__ = []
# id = db.Column(db.Integer, primary_key=True)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# email = db.Column(db.String(255), unique=True, nullable=False)
# name = db.Column(db.String(255))
# password = db.Column(db.String(255))
# active = db.Column(db.Boolean())
# confirmed_at = db.Column(db.DateTime())
#
# last_login_at = db.Column(db.DateTime())
# current_login_at = db.Column(db.DateTime())
# last_login_ip = db.Column(db.String(255))
# current_login_ip = db.Column(db.String(255))
# login_count = db.Column(db.Integer())
# language_preference = db.Column(db.String(2))
#
# roles = db.relationship('Role', secondary=roles_users,
# backref=db.backref('users', lazy='dynamic'))
#
# def __str__(self):
# return "<User #{} '{}' ({})>".format(self.id,
# self.name or "",
# self.email)
#
# Path: beavy/models/activity.py
# class Activity(db.Model):
# """
# We record activities on objects through this
# """
# @unique
# class Capabilities(Enum):
# pass
#
# __tablename__ = "activities"
# query_class = AccessQuery
#
# id = db.Column(db.Integer, primary_key=True)
# subject_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# discriminator = db.Column('verb', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# object_id = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# whom_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=True)
# payload = db.Column('payload', JSONB, nullable=True)
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# subject = db.relationship(User, backref=db.backref("activities"),
# foreign_keys=subject_id)
# object = db.relationship(Object, backref=db.backref("activities"))
#
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
, which may contain function names, class names, or code. Output only the next line. | ).first_or_404() |
Given the following code snippet before the placeholder: <|code_start|>
class ModelConverter(BaseConverter):
__OBJECTS__ = {
'user': User,
'object': Object,
'activity': Activity
}
def __init__(self, url_map, obj="object"):
<|code_end|>
, predict the next line using imports from the current file:
from sqlalchemy.sql import or_
from flask import abort
from werkzeug.routing import BaseConverter
from ..models.user import User
from ..models.activity import Activity
from ..models.object import Object
and context including class names, function names, and sometimes code from other files:
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
# __LOOKUP_ATTRS__ = []
# id = db.Column(db.Integer, primary_key=True)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# email = db.Column(db.String(255), unique=True, nullable=False)
# name = db.Column(db.String(255))
# password = db.Column(db.String(255))
# active = db.Column(db.Boolean())
# confirmed_at = db.Column(db.DateTime())
#
# last_login_at = db.Column(db.DateTime())
# current_login_at = db.Column(db.DateTime())
# last_login_ip = db.Column(db.String(255))
# current_login_ip = db.Column(db.String(255))
# login_count = db.Column(db.Integer())
# language_preference = db.Column(db.String(2))
#
# roles = db.relationship('Role', secondary=roles_users,
# backref=db.backref('users', lazy='dynamic'))
#
# def __str__(self):
# return "<User #{} '{}' ({})>".format(self.id,
# self.name or "",
# self.email)
#
# Path: beavy/models/activity.py
# class Activity(db.Model):
# """
# We record activities on objects through this
# """
# @unique
# class Capabilities(Enum):
# pass
#
# __tablename__ = "activities"
# query_class = AccessQuery
#
# id = db.Column(db.Integer, primary_key=True)
# subject_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# discriminator = db.Column('verb', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# object_id = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# whom_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=True)
# payload = db.Column('payload', JSONB, nullable=True)
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# subject = db.relationship(User, backref=db.backref("activities"),
# foreign_keys=subject_id)
# object = db.relationship(Object, backref=db.backref("activities"))
#
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
. Output only the next line. | super(ModelConverter, self).__init__(url_map) |
Given the following code snippet before the placeholder: <|code_start|> print("You need to configure the APP to be used!")
exit(1)
exit(behave_main(sys.argv[2:] + ['--no-capture',
"beavy_apps/{}/tests/features".format(frontend)]))
if has_behave:
manager.add_command("behave", Behave())
try:
has_pytest = True
except ImportError:
has_pytest = False
def pytest(path=None, no_coverage=False, maxfail=0, # noqa
debug=False, verbose=False):
arguments = []
def add_path_with_coverage(x):
arguments.append("--cov={}".format(x))
arguments.append(x)
def simple_add(x):
arguments.append(x)
if maxfail:
arguments.append("--maxfail={}".format(maxfail))
<|code_end|>
, predict the next line using imports from the current file:
from flask.ext.script import Command, Option
from beavy.app import app, manager, migrate
from behave.configuration import options as behave_options
from behave.__main__ import main as behave_main
import sys
import os
import re
import pytest
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | if verbose: |
Here is a snippet: <|code_start|> if not re.match("^[a-z][a-z0-9]{2,24}$", name):
print("""Sorry, the app name has to be a lower-cased 3-25 character
long string only containing letters, numbers and underscore and starting
with a letter!""")
print("RegEx: ^[a-z][a-z0-9]{2,24}$ ")
exit(1)
APP_DIR = os.path.join(ROOT_DIR, "beavy_apps", name)
if os.path.exists(APP_DIR):
print("{} directory already exists. Exiting.".format(name))
exit(1)
# minimal setup
os.mkdir(APP_DIR)
open(os.path.join(APP_DIR, "__init__.py"), 'w').close()
# create minimal frontend
os.mkdir(os.path.join(APP_DIR, "frontend"))
with open(os.path.join(APP_DIR, "frontend",
"application.jsx"), 'w') as jsx:
jsx.write("""
import React from "react";
import { MainMenu } from "components/MainMenu";
import UserModal from "containers/UserModal";
import UserMenuWidget from "containers/UserMenuWidget";
import { getExtensions } from "config/extensions";
<|code_end|>
. Write the next line using the current file imports:
from flask.ext.script import Command, Option
from beavy.app import app, manager, migrate
from behave.configuration import options as behave_options
from behave.__main__ import main as behave_main
import sys
import os
import re
import pytest
import pytest
and context from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
, which may include functions, classes, or code. Output only the next line. | // This is your app entry point |
Predict the next line after this snippet: <|code_start|> """
Setup beavy template and infrastructure for a new app
given the @name.
"""
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
if not re.match("^[a-z][a-z0-9]{2,24}$", name):
print("""Sorry, the app name has to be a lower-cased 3-25 character
long string only containing letters, numbers and underscore and starting
with a letter!""")
print("RegEx: ^[a-z][a-z0-9]{2,24}$ ")
exit(1)
APP_DIR = os.path.join(ROOT_DIR, "beavy_apps", name)
if os.path.exists(APP_DIR):
print("{} directory already exists. Exiting.".format(name))
exit(1)
# minimal setup
os.mkdir(APP_DIR)
open(os.path.join(APP_DIR, "__init__.py"), 'w').close()
# create minimal frontend
os.mkdir(os.path.join(APP_DIR, "frontend"))
with open(os.path.join(APP_DIR, "frontend",
"application.jsx"), 'w') as jsx:
jsx.write("""
import React from "react";
<|code_end|>
using the current file's imports:
from flask.ext.script import Command, Option
from beavy.app import app, manager, migrate
from behave.configuration import options as behave_options
from behave.__main__ import main as behave_main
import sys
import os
import re
import pytest
import pytest
and any relevant context from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | import { MainMenu } from "components/MainMenu"; |
Predict the next line after this snippet: <|code_start|>
# from unittest import mock
class TestObject():
def __init__(self):
self.payload = {}
title = PayloadProperty("title")
header_o = PayloadProperty("other", "content.header")
header_p = PayloadProperty("p", "content.header")
def test_simple(mocker):
TestObject.title.flag_modified = mocker.MagicMock()
t = TestObject()
assert t.payload == {}
t.title = "test"
assert t.payload == {'title': 'test'}
TestObject.title.flag_modified.assert_called_once_with(t, "payload")
<|code_end|>
using the current file's imports:
from .payload_property import PayloadProperty
and any relevant context from other files:
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
. Output only the next line. | def test_deeper(mocker): |
Predict the next line for this snippet: <|code_start|>
class BaseObject(Schema):
class Meta:
type_ = "object"
id = fields.Integer()
created_at = fields.DateTime()
owner = fields.Nested(BaseUser)
belongs_to_id = fields.Integer() # don't leak
type = fields.String(attribute="discriminator")
class ObjectField(MorphingSchema):
FALLBACK = BaseObject
registry = {}
class ObjectSchema(ObjectField, Schema):
<|code_end|>
with the help of current file imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.common.morphing_schema import MorphingSchema
from marshmallow_jsonapi import Schema, fields
from .user import BaseUser
and context from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/common/morphing_schema.py
# class MorphingSchema():
#
# @pre_dump
# def select_processor(self, obj, many=False,
# strict=False, update_fields=False):
# if many:
# return [self._get_serializer(item) for item in obj]
# return self._get_serializer(obj)
#
# def _obj_to_name(self, obj):
# return obj.__mapper__.polymorphic_identity
#
# def _get_serializer(self, obj):
# name = self._obj_to_name(obj)
# return self.registry.get(name, self.FALLBACK)()
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
, which may contain function names, class names, or code. Output only the next line. | pass |
Given the following code snippet before the placeholder: <|code_start|>
class BaseObject(Schema):
class Meta:
type_ = "object"
<|code_end|>
, predict the next line using imports from the current file:
from beavy.common.paging_schema import makePaginationSchema
from beavy.common.morphing_schema import MorphingSchema
from marshmallow_jsonapi import Schema, fields
from .user import BaseUser
and context including class names, function names, and sometimes code from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/common/morphing_schema.py
# class MorphingSchema():
#
# @pre_dump
# def select_processor(self, obj, many=False,
# strict=False, update_fields=False):
# if many:
# return [self._get_serializer(item) for item in obj]
# return self._get_serializer(obj)
#
# def _obj_to_name(self, obj):
# return obj.__mapper__.polymorphic_identity
#
# def _get_serializer(self, obj):
# name = self._obj_to_name(obj)
# return self.registry.get(name, self.FALLBACK)()
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
. Output only the next line. | id = fields.Integer() |
Given the following code snippet before the placeholder: <|code_start|>
class Like(Activity):
__mapper_args__ = {
'polymorphic_identity': 'like'
}
Object.likes_count = db.Column(db.Integer())
@event.listens_for(Like, 'after_insert')
def update_object_likes_count(mapper, connection, target):
# unfortunately, we can't do an aggregate in update directly...
<|code_end|>
, predict the next line using imports from the current file:
from beavy.app import db
from beavy.models.activity import Activity
from beavy.models.object import Object
from sqlalchemy import event
and context including class names, function names, and sometimes code from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
#
# Path: beavy/models/activity.py
# class Activity(db.Model):
# """
# We record activities on objects through this
# """
# @unique
# class Capabilities(Enum):
# pass
#
# __tablename__ = "activities"
# query_class = AccessQuery
#
# id = db.Column(db.Integer, primary_key=True)
# subject_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# discriminator = db.Column('verb', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# object_id = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# whom_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=True)
# payload = db.Column('payload', JSONB, nullable=True)
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# subject = db.relationship(User, backref=db.backref("activities"),
# foreign_keys=subject_id)
# object = db.relationship(Object, backref=db.backref("activities"))
#
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
. Output only the next line. | likes_count = Like.query.filter(Like.object_id == target.object_id).count() |
Given the following code snippet before the placeholder: <|code_start|>
class Like(Activity):
__mapper_args__ = {
'polymorphic_identity': 'like'
}
Object.likes_count = db.Column(db.Integer())
@event.listens_for(Like, 'after_insert')
def update_object_likes_count(mapper, connection, target):
# unfortunately, we can't do an aggregate in update directly...
likes_count = Like.query.filter(Like.object_id == target.object_id).count()
Object.query.filter(Object.id == target.object_id
<|code_end|>
, predict the next line using imports from the current file:
from beavy.app import db
from beavy.models.activity import Activity
from beavy.models.object import Object
from sqlalchemy import event
and context including class names, function names, and sometimes code from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
#
# Path: beavy/models/activity.py
# class Activity(db.Model):
# """
# We record activities on objects through this
# """
# @unique
# class Capabilities(Enum):
# pass
#
# __tablename__ = "activities"
# query_class = AccessQuery
#
# id = db.Column(db.Integer, primary_key=True)
# subject_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# discriminator = db.Column('verb', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# object_id = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# whom_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=True)
# payload = db.Column('payload', JSONB, nullable=True)
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# subject = db.relationship(User, backref=db.backref("activities"),
# foreign_keys=subject_id)
# object = db.relationship(Object, backref=db.backref("activities"))
#
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
. Output only the next line. | ).update({'likes_count': likes_count}) |
Predict the next line for this snippet: <|code_start|> provider = db.Column(db.String(255), nullable=False)
profile_id = db.Column(db.String(255), nullable=False)
username = db.Column(db.String(255))
email = db.Column(db.String(255))
access_token = db.Column(db.String(255))
secret = db.Column(db.String(255))
first_name = db.Column(db.String(255))
last_name = db.Column(db.String(255))
cn = db.Column(db.String(255))
profile_url = db.Column(db.String(512))
image_url = db.Column(db.String(512))
def get_user(self):
return self.user
@classmethod
def by_profile(cls, profile):
provider = profile.data["provider"]
return cls.query.filter(cls.provider == provider,
cls.profile_id == profile.id).first()
@classmethod
def from_profile(cls, user, profile):
if not user or user.is_anonymous:
if not app.config.get("SECURITY_REGISTERABLE"):
msg = "User not found. Registration disabled."
logging.warning(msg)
raise Exception(_(msg))
email = profile.data.get("email")
if not email:
<|code_end|>
with the help of current file imports:
from flask_babel import gettext as _
from sqlalchemy import orm, func
from ..app import db, app
from .user import User
import logging
import datetime
and context from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
#
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
# __LOOKUP_ATTRS__ = []
# id = db.Column(db.Integer, primary_key=True)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# email = db.Column(db.String(255), unique=True, nullable=False)
# name = db.Column(db.String(255))
# password = db.Column(db.String(255))
# active = db.Column(db.Boolean())
# confirmed_at = db.Column(db.DateTime())
#
# last_login_at = db.Column(db.DateTime())
# current_login_at = db.Column(db.DateTime())
# last_login_ip = db.Column(db.String(255))
# current_login_ip = db.Column(db.String(255))
# login_count = db.Column(db.Integer())
# language_preference = db.Column(db.String(2))
#
# roles = db.relationship('Role', secondary=roles_users,
# backref=db.backref('users', lazy='dynamic'))
#
# def __str__(self):
# return "<User #{} '{}' ({})>".format(self.id,
# self.name or "",
# self.email)
, which may contain function names, class names, or code. Output only the next line. | msg = "Please provide an email address." |
Predict the next line for this snippet: <|code_start|> if not user or user.is_anonymous:
if not app.config.get("SECURITY_REGISTERABLE"):
msg = "User not found. Registration disabled."
logging.warning(msg)
raise Exception(_(msg))
email = profile.data.get("email")
if not email:
msg = "Please provide an email address."
logging.warning(msg)
raise Exception(_(msg))
conflict = User.query.filter(User.email == email).first()
if conflict:
msg = "Email {} is already used. Login and then connect " + \
"external profile."
msg = _(msg).format(email)
logging.warning(msg)
raise Exception(msg)
now = datetime.now()
user = User(
email=email,
name="{} {}".format(profile.data.get("first_name"),
profile.data.get("last_name")),
confirmed_at=now,
active=True)
db.session.add(user)
db.session.flush()
assert user.id, "User does not have an id"
<|code_end|>
with the help of current file imports:
from flask_babel import gettext as _
from sqlalchemy import orm, func
from ..app import db, app
from .user import User
import logging
import datetime
and context from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
#
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
# __LOOKUP_ATTRS__ = []
# id = db.Column(db.Integer, primary_key=True)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# email = db.Column(db.String(255), unique=True, nullable=False)
# name = db.Column(db.String(255))
# password = db.Column(db.String(255))
# active = db.Column(db.Boolean())
# confirmed_at = db.Column(db.DateTime())
#
# last_login_at = db.Column(db.DateTime())
# current_login_at = db.Column(db.DateTime())
# last_login_ip = db.Column(db.String(255))
# current_login_ip = db.Column(db.String(255))
# login_count = db.Column(db.Integer())
# language_preference = db.Column(db.String(2))
#
# roles = db.relationship('Role', secondary=roles_users,
# backref=db.backref('users', lazy='dynamic'))
#
# def __str__(self):
# return "<User #{} '{}' ({})>".format(self.id,
# self.name or "",
# self.email)
, which may contain function names, class names, or code. Output only the next line. | connection = cls(user_id=user.id, **profile.data) |
Next line prediction: <|code_start|>
class SocialConnection(db.Model):
id = db.Column(db.Integer, primary_key=True)
created_at = db.Column('created_at', db.DateTime(),
nullable=False, server_default=func.now())
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = orm.relationship(User, foreign_keys=user_id,
backref=orm.backref('connections', order_by=id))
provider = db.Column(db.String(255), nullable=False)
profile_id = db.Column(db.String(255), nullable=False)
username = db.Column(db.String(255))
email = db.Column(db.String(255))
access_token = db.Column(db.String(255))
secret = db.Column(db.String(255))
first_name = db.Column(db.String(255))
last_name = db.Column(db.String(255))
cn = db.Column(db.String(255))
profile_url = db.Column(db.String(512))
image_url = db.Column(db.String(512))
def get_user(self):
return self.user
<|code_end|>
. Use current file imports:
(from flask_babel import gettext as _
from sqlalchemy import orm, func
from ..app import db, app
from .user import User
import logging
import datetime)
and context including class names, function names, or small code snippets from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
#
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
# __LOOKUP_ATTRS__ = []
# id = db.Column(db.Integer, primary_key=True)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# email = db.Column(db.String(255), unique=True, nullable=False)
# name = db.Column(db.String(255))
# password = db.Column(db.String(255))
# active = db.Column(db.Boolean())
# confirmed_at = db.Column(db.DateTime())
#
# last_login_at = db.Column(db.DateTime())
# current_login_at = db.Column(db.DateTime())
# last_login_ip = db.Column(db.String(255))
# current_login_ip = db.Column(db.String(255))
# login_count = db.Column(db.Integer())
# language_preference = db.Column(db.String(2))
#
# roles = db.relationship('Role', secondary=roles_users,
# backref=db.backref('users', lazy='dynamic'))
#
# def __str__(self):
# return "<User #{} '{}' ({})>".format(self.id,
# self.name or "",
# self.email)
. Output only the next line. | @classmethod |
Next line prediction: <|code_start|> raise UnSupportedExceptions('sort', sort)
return self.do('GET', 'projects',
query_params={'name': name, 'sort': sort}
)
def create_project(self, name, datastore='light', location='false'):
if validate_datastore(datastore) is not True:
raise UnSupportedExceptions('datastore', datastore)
if validate_location(location) is not True:
raise UnSupportedExceptions('location', location)
return self.do('POST', 'projects',
request_params={
'name': name,
'datastore': datastore,
'location': location
}
)
def delete_project(self, project_id):
return self.do('DELETE', 'projects/{project_id}',
url_params={'project_id': project_id}
)
def show_project(self, project_id):
return self.do('GET', 'projects/{project_id}',
url_params={'project_id': project_id}
)
<|code_end|>
. Use current file imports:
(from sakuraio.software.exceptions import UnSupportedExceptions
from sakuraio.software.utils import validate_sort_project, validate_datastore, validate_location)
and context including class names, function names, or small code snippets from other files:
# Path: sakuraio/software/exceptions.py
# class UnSupportedExceptions(SakuraIOClientBaseExceptions):
# def __init__(self, type, value):
# self.type = type
# self.value = value
#
# def __str__(self):
# return '[ERROR] {0} is unsupported {1} option.'.format(self.value, self.type)
#
# Path: sakuraio/software/utils.py
# def validate_sort_project(value):
# sort_options = [None, '', 'name', 'id', '-name', '-id']
# if value not in sort_options:
# return False
#
# return True
#
# def validate_datastore(value):
# datastore_options = ['light', 'standard']
# if value not in datastore_options:
# return False
#
# return True
#
# def validate_location(value):
# location_options = ['false', 'true']
# if value not in location_options:
# return False
#
# return True
. Output only the next line. | def update_project(self, project_id, name, location): |
Based on the snippet: <|code_start|>
class ProjectMixins(object):
def show_projects(self, name=None, sort=None):
# validate sort option
if not validate_sort_project(sort):
raise UnSupportedExceptions('sort', sort)
return self.do('GET', 'projects',
query_params={'name': name, 'sort': sort}
)
def create_project(self, name, datastore='light', location='false'):
if validate_datastore(datastore) is not True:
raise UnSupportedExceptions('datastore', datastore)
if validate_location(location) is not True:
raise UnSupportedExceptions('location', location)
return self.do('POST', 'projects',
request_params={
'name': name,
'datastore': datastore,
<|code_end|>
, predict the immediate next line with the help of imports:
from sakuraio.software.exceptions import UnSupportedExceptions
from sakuraio.software.utils import validate_sort_project, validate_datastore, validate_location
and context (classes, functions, sometimes code) from other files:
# Path: sakuraio/software/exceptions.py
# class UnSupportedExceptions(SakuraIOClientBaseExceptions):
# def __init__(self, type, value):
# self.type = type
# self.value = value
#
# def __str__(self):
# return '[ERROR] {0} is unsupported {1} option.'.format(self.value, self.type)
#
# Path: sakuraio/software/utils.py
# def validate_sort_project(value):
# sort_options = [None, '', 'name', 'id', '-name', '-id']
# if value not in sort_options:
# return False
#
# return True
#
# def validate_datastore(value):
# datastore_options = ['light', 'standard']
# if value not in datastore_options:
# return False
#
# return True
#
# def validate_location(value):
# location_options = ['false', 'true']
# if value not in location_options:
# return False
#
# return True
. Output only the next line. | 'location': location |
Predict the next line for this snippet: <|code_start|>
class ProjectMixins(object):
def show_projects(self, name=None, sort=None):
# validate sort option
if not validate_sort_project(sort):
raise UnSupportedExceptions('sort', sort)
return self.do('GET', 'projects',
query_params={'name': name, 'sort': sort}
<|code_end|>
with the help of current file imports:
from sakuraio.software.exceptions import UnSupportedExceptions
from sakuraio.software.utils import validate_sort_project, validate_datastore, validate_location
and context from other files:
# Path: sakuraio/software/exceptions.py
# class UnSupportedExceptions(SakuraIOClientBaseExceptions):
# def __init__(self, type, value):
# self.type = type
# self.value = value
#
# def __str__(self):
# return '[ERROR] {0} is unsupported {1} option.'.format(self.value, self.type)
#
# Path: sakuraio/software/utils.py
# def validate_sort_project(value):
# sort_options = [None, '', 'name', 'id', '-name', '-id']
# if value not in sort_options:
# return False
#
# return True
#
# def validate_datastore(value):
# datastore_options = ['light', 'standard']
# if value not in datastore_options:
# return False
#
# return True
#
# def validate_location(value):
# location_options = ['false', 'true']
# if value not in location_options:
# return False
#
# return True
, which may contain function names, class names, or code. Output only the next line. | ) |
Given the code snippet: <|code_start|>
class ProjectMixins(object):
def show_projects(self, name=None, sort=None):
# validate sort option
if not validate_sort_project(sort):
raise UnSupportedExceptions('sort', sort)
return self.do('GET', 'projects',
query_params={'name': name, 'sort': sort}
)
def create_project(self, name, datastore='light', location='false'):
if validate_datastore(datastore) is not True:
raise UnSupportedExceptions('datastore', datastore)
if validate_location(location) is not True:
raise UnSupportedExceptions('location', location)
return self.do('POST', 'projects',
request_params={
'name': name,
'datastore': datastore,
'location': location
<|code_end|>
, generate the next line using the imports in this file:
from sakuraio.software.exceptions import UnSupportedExceptions
from sakuraio.software.utils import validate_sort_project, validate_datastore, validate_location
and context (functions, classes, or occasionally code) from other files:
# Path: sakuraio/software/exceptions.py
# class UnSupportedExceptions(SakuraIOClientBaseExceptions):
# def __init__(self, type, value):
# self.type = type
# self.value = value
#
# def __str__(self):
# return '[ERROR] {0} is unsupported {1} option.'.format(self.value, self.type)
#
# Path: sakuraio/software/utils.py
# def validate_sort_project(value):
# sort_options = [None, '', 'name', 'id', '-name', '-id']
# if value not in sort_options:
# return False
#
# return True
#
# def validate_datastore(value):
# datastore_options = ['light', 'standard']
# if value not in datastore_options:
# return False
#
# return True
#
# def validate_location(value):
# location_options = ['false', 'true']
# if value not in location_options:
# return False
#
# return True
. Output only the next line. | } |
Predict the next line for this snippet: <|code_start|>
class ModuleMixins(object):
def show_modules(self, project_id=None, serial_number=None, model=None, sort=None):
sort_options = [
None, '',
'project', '-project',
'name', '-name',
'id', '-id',
'selial_number', '-serial_number',
'model', '-model'
]
<|code_end|>
with the help of current file imports:
from sakuraio.software.exceptions import UnSupportedExceptions
and context from other files:
# Path: sakuraio/software/exceptions.py
# class UnSupportedExceptions(SakuraIOClientBaseExceptions):
# def __init__(self, type, value):
# self.type = type
# self.value = value
#
# def __str__(self):
# return '[ERROR] {0} is unsupported {1} option.'.format(self.value, self.type)
, which may contain function names, class names, or code. Output only the next line. | if sort not in sort_options: |
Given the following code snippet before the placeholder: <|code_start|> return self.do('POST', 'services/?type=outgoing-webhook',
request_params={
'name': name,
'type': 'outgoing-webhook',
'project': project_id,
'url': url,
'secret': secret
}
)
def create_incoming_webhook_service(self, name, project_id, url, secret):
return self.do('POST', 'services/?type=incoming-webhook',
request_params={
'name': name,
'type': 'incoming-webhook',
'project': project_id,
'url': url,
'secret': secret
}
)
def create_datastore_service(self, name, project_id):
return self.do('POST', 'services/?type=datastore',
request_params={
'name': name,
'type': 'datastore',
'project': project_id
}
)
<|code_end|>
, predict the next line using imports from the current file:
from sakuraio.software.exceptions import UnSupportedExceptions
and context including class names, function names, and sometimes code from other files:
# Path: sakuraio/software/exceptions.py
# class UnSupportedExceptions(SakuraIOClientBaseExceptions):
# def __init__(self, type, value):
# self.type = type
# self.value = value
#
# def __str__(self):
# return '[ERROR] {0} is unsupported {1} option.'.format(self.value, self.type)
. Output only the next line. | def create_mqtt_service(self, name, project_id, hostname, port, publish_prefix, subscribe_topic, |
Given the code snippet: <|code_start|>
# Transmit
CMD_TX_ENQUEUE = 0x20
CMD_TX_SENDIMMED = 0x21
CMD_TX_LENGTH = 0x22
CMD_TX_CLEAR = 0x23
CMD_TX_SEND = 0x24
CMD_TX_STAT = 0x25
<|code_end|>
, generate the next line using the imports in this file:
import struct
import datetime
from .utils import pack, value_to_bytes
and context (functions, classes, or occasionally code) from other files:
# Path: sakuraio/hardware/commands/utils.py
# def pack(fmt, *args):
# """pack() is wrapper of struct.pack
# """
#
# value = struct.pack(fmt, *args)
# result = []
#
# if isinstance(value, str):
# # For Python2
# for v in value:
# result.append(ord(v))
#
# return result
# elif isinstance(value, bytes):
# # For Python3
# result += value
# return result
# else:
# TypeError()
#
# def value_to_bytes(value):
# """Convert value to raw values.
#
# :param value:
# Value to Convert
# :type value: integer, float, str or bytes
#
# :return: Tuple of `Type` string and `Value` list
# :rtype: (str, list)
# """
#
# if isinstance(value, float):
# return ("d", pack("<d", value))
#
# if isinstance(value, int):
# if value > 9223372036854775807:
# return ("L", pack("<Q", value))
# return ("l", pack("<q", value))
#
# if platform.python_version_tuple()[0] == "2" and isinstance(value, long):
# return ("L", pack("<Q", value))
#
# if isinstance(value, str):
# if platform.python_version_tuple()[0] == "2":
# result = []
# for c in value.encode("utf-8"):
# result.append(ord(c))
# return ("b", (result+[0x00]*8)[:8])
# else:
# return ("b", (list(value.encode("utf-8"))+[0x00]*8)[:8])
#
# if isinstance(value, bytes):
# return ("b", (list(value)+[0x00]*8)[:8])
#
# raise ValueError("Unsupported Type %s", value.__class__)
. Output only the next line. | class TransmitMixins(object): |
Based on the snippet: <|code_start|> sakuraio = self._initial(0x01, [0x01, ord("b"), 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 31, 239, 255, 255, 255, 255, 255, 255])
self.assertEqual(sakuraio.dequeue_rx_raw(), {'channel': 1, 'data': [1, 2, 3, 4, 5, 6, 7, 8], 'offset': -4321, 'type': 'b'})
self.assertEqual(sakuraio.values, [CMD_RX_DEQUEUE, 0, CMD_RX_DEQUEUE])
def test_peek_rx_raw(self):
sakuraio = self._initial(0x01, [0x01, ord("b"), 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 31, 239, 255, 255, 255, 255, 255, 255])
self.assertEqual(sakuraio.peek_rx_raw(), {'channel': 1, 'data': [1, 2, 3, 4, 5, 6, 7, 8], 'offset': -4321, 'type': 'b'})
self.assertEqual(sakuraio.values, [CMD_RX_PEEK, 0, CMD_RX_PEEK])
def test_get_rx_queue_length(self):
sakuraio = self._initial(0x01, [23, 14])
self.assertEqual(sakuraio.get_rx_queue_length(), {'queued': 14, 'available': 23})
self.assertEqual(sakuraio.values, [CMD_RX_LENGTH, 0, CMD_RX_LENGTH])
def test_clear_rx(self):
sakuraio = self._initial(0x01, [])
sakuraio.clear_rx()
self.assertEqual(sakuraio.values, [CMD_RX_CLEAR, 0, CMD_RX_CLEAR])
def test_start_file_download(self):
sakuraio = self._initial(0x01, [])
sakuraio.start_file_download(1)
self.assertEqual(sakuraio.values, [CMD_START_FILE_DOWNLOAD, 2, 0x01, 0x00, 67])
# for Compatibility
sakuraio = self._initial(0x01, [])
sakuraio.start_file_download([1])
self.assertEqual(sakuraio.values, [CMD_START_FILE_DOWNLOAD, 2, 0x01, 0x00, 67])
def test_get_file_download_status(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import datetime
from sakuraio.hardware.base import calc_parity
from sakuraio.hardware.commands import *
from sakuraio.hardware.commands.utils import value_to_bytes
from sakuraio.hardware.dummy import DummySakuraIO
from sakuraio.hardware.exceptions import CommandError, ParityError
and context (classes, functions, sometimes code) from other files:
# Path: sakuraio/hardware/base.py
# def calc_parity(values):
# parity = 0x00
# for value in values:
# parity ^= value
# return parity
#
# Path: sakuraio/hardware/commands/utils.py
# def value_to_bytes(value):
# """Convert value to raw values.
#
# :param value:
# Value to Convert
# :type value: integer, float, str or bytes
#
# :return: Tuple of `Type` string and `Value` list
# :rtype: (str, list)
# """
#
# if isinstance(value, float):
# return ("d", pack("<d", value))
#
# if isinstance(value, int):
# if value > 9223372036854775807:
# return ("L", pack("<Q", value))
# return ("l", pack("<q", value))
#
# if platform.python_version_tuple()[0] == "2" and isinstance(value, long):
# return ("L", pack("<Q", value))
#
# if isinstance(value, str):
# if platform.python_version_tuple()[0] == "2":
# result = []
# for c in value.encode("utf-8"):
# result.append(ord(c))
# return ("b", (result+[0x00]*8)[:8])
# else:
# return ("b", (list(value.encode("utf-8"))+[0x00]*8)[:8])
#
# if isinstance(value, bytes):
# return ("b", (list(value)+[0x00]*8)[:8])
#
# raise ValueError("Unsupported Type %s", value.__class__)
#
# Path: sakuraio/hardware/dummy.py
# class DummySakuraIO(SakuraIOBase):
#
# def start(self, write=True):
# pass
#
# def end(self):
# pass
#
# def initial(self, response):
# self.return_values = response
# self.values = []
#
# def send_byte(self, value):
# self.values.append(value)
#
# def recv_byte(self):
# value = self.return_values[0]
# self.return_values = self.return_values[1:]
# return value
#
# Path: sakuraio/hardware/exceptions.py
# class CommandError(SakuraIOBaseException):
#
# def __init__(self, status):
# self.status = status
#
# def __str__(self):
# return "Invalid response status '0x{0:02x}'".format(self.status)
#
# class ParityError(SakuraIOBaseException):
#
# def __init__(self):
# pass
#
# def __str__(self):
# return "Invalid parity"
. Output only the next line. | sakuraio = self._initial(0x01, [0, 0x01, 0x02, 0x03, 0x04]) |
Predict the next line for this snippet: <|code_start|> sakuraio = self._initial(0x01, [0x01, 0x02, 0x03, 0x04, 0x05])
result = sakuraio.get_file_data([128])
self.assertEqual(sakuraio.values, [CMD_GET_FILE_DATA, 1, 128, 197])
self.assertEqual(result, {"data":[0x01, 0x02, 0x03, 0x04, 0x05]})
def test_get_product_id(self):
sakuraio = self._initial(0x01, [0x02, 0x00])
self.assertEqual(sakuraio.get_product_id(), 2)
self.assertEqual(sakuraio.values, [CMD_GET_PRODUCT_ID, 0, CMD_GET_PRODUCT_ID])
def test_get_product_name(self):
sakuraio = self._initial(0x01, [0x01, 0x00])
self.assertEqual(sakuraio.get_product_name(), "SCM-LTE-BETA")
self.assertEqual(sakuraio.values, [CMD_GET_PRODUCT_ID, 0, CMD_GET_PRODUCT_ID])
sakuraio = self._initial(0x01, [0x02, 0x00])
self.assertEqual(sakuraio.get_product_name(), "SCM-LTE-01")
self.assertEqual(sakuraio.values, [CMD_GET_PRODUCT_ID, 0, CMD_GET_PRODUCT_ID])
def test_get_unique_id(self):
sakuraio = self._initial(0x01, [49, 54, 66, 48, 49, 48, 48, 50, 54, 48])
self.assertEqual(sakuraio.get_unique_id(), "16B0100260")
self.assertEqual(sakuraio.values, [CMD_GET_UNIQUE_ID, 0, CMD_GET_UNIQUE_ID])
def test_get_firmware_version(self):
sakuraio = self._initial(0x01, [49, 54, 66, 48, 49, 48, 48, 50, 54, 48])
self.assertEqual(sakuraio.get_firmware_version(), "16B0100260")
self.assertEqual(sakuraio.values, [CMD_GET_FIRMWARE_VERSION, 0, CMD_GET_FIRMWARE_VERSION])
def test_unlock(self):
<|code_end|>
with the help of current file imports:
import unittest
import datetime
from sakuraio.hardware.base import calc_parity
from sakuraio.hardware.commands import *
from sakuraio.hardware.commands.utils import value_to_bytes
from sakuraio.hardware.dummy import DummySakuraIO
from sakuraio.hardware.exceptions import CommandError, ParityError
and context from other files:
# Path: sakuraio/hardware/base.py
# def calc_parity(values):
# parity = 0x00
# for value in values:
# parity ^= value
# return parity
#
# Path: sakuraio/hardware/commands/utils.py
# def value_to_bytes(value):
# """Convert value to raw values.
#
# :param value:
# Value to Convert
# :type value: integer, float, str or bytes
#
# :return: Tuple of `Type` string and `Value` list
# :rtype: (str, list)
# """
#
# if isinstance(value, float):
# return ("d", pack("<d", value))
#
# if isinstance(value, int):
# if value > 9223372036854775807:
# return ("L", pack("<Q", value))
# return ("l", pack("<q", value))
#
# if platform.python_version_tuple()[0] == "2" and isinstance(value, long):
# return ("L", pack("<Q", value))
#
# if isinstance(value, str):
# if platform.python_version_tuple()[0] == "2":
# result = []
# for c in value.encode("utf-8"):
# result.append(ord(c))
# return ("b", (result+[0x00]*8)[:8])
# else:
# return ("b", (list(value.encode("utf-8"))+[0x00]*8)[:8])
#
# if isinstance(value, bytes):
# return ("b", (list(value)+[0x00]*8)[:8])
#
# raise ValueError("Unsupported Type %s", value.__class__)
#
# Path: sakuraio/hardware/dummy.py
# class DummySakuraIO(SakuraIOBase):
#
# def start(self, write=True):
# pass
#
# def end(self):
# pass
#
# def initial(self, response):
# self.return_values = response
# self.values = []
#
# def send_byte(self, value):
# self.values.append(value)
#
# def recv_byte(self):
# value = self.return_values[0]
# self.return_values = self.return_values[1:]
# return value
#
# Path: sakuraio/hardware/exceptions.py
# class CommandError(SakuraIOBaseException):
#
# def __init__(self, status):
# self.status = status
#
# def __str__(self):
# return "Invalid response status '0x{0:02x}'".format(self.status)
#
# class ParityError(SakuraIOBaseException):
#
# def __init__(self):
# pass
#
# def __str__(self):
# return "Invalid parity"
, which may contain function names, class names, or code. Output only the next line. | sakuraio = self._initial(0x01, []) |
Given the following code snippet before the placeholder: <|code_start|>
class SakuraIOBaseTest(unittest.TestCase):
def test_parity(self):
self.assertEqual(calc_parity([0x00]), 0x00)
self.assertEqual(calc_parity([0x24]), 0x24)
self.assertEqual(calc_parity([0x00, 0x24]), 0x24)
self.assertEqual(calc_parity([0x24, 0x24]), 0x00)
self.assertEqual(calc_parity([0x00, 0x01, 0xa2, 0x33]), 0x90)
def _execute_command(self, cmd, request, response, as_bytes=False):
base = DummySakuraIO()
base.initial(response)
return base.execute_command(cmd, request, as_bytes=as_bytes)
def test_execute_command(self):
base = DummySakuraIO()
cmd = 0x10
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from sakuraio.hardware.base import calc_parity
from sakuraio.hardware.dummy import DummySakuraIO
from sakuraio.hardware.exceptions import CommandError, ParityError
and context including class names, function names, and sometimes code from other files:
# Path: sakuraio/hardware/base.py
# def calc_parity(values):
# parity = 0x00
# for value in values:
# parity ^= value
# return parity
#
# Path: sakuraio/hardware/dummy.py
# class DummySakuraIO(SakuraIOBase):
#
# def start(self, write=True):
# pass
#
# def end(self):
# pass
#
# def initial(self, response):
# self.return_values = response
# self.values = []
#
# def send_byte(self, value):
# self.values.append(value)
#
# def recv_byte(self):
# value = self.return_values[0]
# self.return_values = self.return_values[1:]
# return value
#
# Path: sakuraio/hardware/exceptions.py
# class CommandError(SakuraIOBaseException):
#
# def __init__(self, status):
# self.status = status
#
# def __str__(self):
# return "Invalid response status '0x{0:02x}'".format(self.status)
#
# class ParityError(SakuraIOBaseException):
#
# def __init__(self):
# pass
#
# def __str__(self):
# return "Invalid parity"
. Output only the next line. | request = [0x01, 0x02, 0x03, 0x04] |
Here is a snippet: <|code_start|>
cmd = 0x10
request = [0x01, 0x02, 0x03, 0x04]
request.append(calc_parity(request))
response = [0x01, 0x04, 0x11, 0x12, 0x13, 0x14]
response.append(calc_parity(response))
expected = response[2:-1]
self.assertEqual(self._execute_command(cmd, request, response), expected)
def test_execute_command_status_error(self):
base = DummySakuraIO()
cmd = 0x10
request = [0x01, 0x02, 0x03, 0x04]
request.append(calc_parity(request))
status = 0x02
response = [status, 0x00]
response.append(calc_parity(response))
with self.assertRaises(CommandError):
self._execute_command(cmd, request, response)
def test_execute_command_parity_error(self):
base = DummySakuraIO()
cmd = 0x10
<|code_end|>
. Write the next line using the current file imports:
import unittest
from sakuraio.hardware.base import calc_parity
from sakuraio.hardware.dummy import DummySakuraIO
from sakuraio.hardware.exceptions import CommandError, ParityError
and context from other files:
# Path: sakuraio/hardware/base.py
# def calc_parity(values):
# parity = 0x00
# for value in values:
# parity ^= value
# return parity
#
# Path: sakuraio/hardware/dummy.py
# class DummySakuraIO(SakuraIOBase):
#
# def start(self, write=True):
# pass
#
# def end(self):
# pass
#
# def initial(self, response):
# self.return_values = response
# self.values = []
#
# def send_byte(self, value):
# self.values.append(value)
#
# def recv_byte(self):
# value = self.return_values[0]
# self.return_values = self.return_values[1:]
# return value
#
# Path: sakuraio/hardware/exceptions.py
# class CommandError(SakuraIOBaseException):
#
# def __init__(self, status):
# self.status = status
#
# def __str__(self):
# return "Invalid response status '0x{0:02x}'".format(self.status)
#
# class ParityError(SakuraIOBaseException):
#
# def __init__(self):
# pass
#
# def __str__(self):
# return "Invalid parity"
, which may include functions, classes, or code. Output only the next line. | request = [0x01, 0x02, 0x03, 0x04] |
Predict the next line after this snippet: <|code_start|> request.append(calc_parity(request))
response = [0x01, 0x04, 0x11, 0x12, 0x13, 0x14]
response.append(calc_parity(response))
expected = response[2:-1]
self.assertEqual(self._execute_command(cmd, request, response), expected)
def test_execute_command_status_error(self):
base = DummySakuraIO()
cmd = 0x10
request = [0x01, 0x02, 0x03, 0x04]
request.append(calc_parity(request))
status = 0x02
response = [status, 0x00]
response.append(calc_parity(response))
with self.assertRaises(CommandError):
self._execute_command(cmd, request, response)
def test_execute_command_parity_error(self):
base = DummySakuraIO()
cmd = 0x10
request = [0x01, 0x02, 0x03, 0x04]
request.append(calc_parity(request))
<|code_end|>
using the current file's imports:
import unittest
from sakuraio.hardware.base import calc_parity
from sakuraio.hardware.dummy import DummySakuraIO
from sakuraio.hardware.exceptions import CommandError, ParityError
and any relevant context from other files:
# Path: sakuraio/hardware/base.py
# def calc_parity(values):
# parity = 0x00
# for value in values:
# parity ^= value
# return parity
#
# Path: sakuraio/hardware/dummy.py
# class DummySakuraIO(SakuraIOBase):
#
# def start(self, write=True):
# pass
#
# def end(self):
# pass
#
# def initial(self, response):
# self.return_values = response
# self.values = []
#
# def send_byte(self, value):
# self.values.append(value)
#
# def recv_byte(self):
# value = self.return_values[0]
# self.return_values = self.return_values[1:]
# return value
#
# Path: sakuraio/hardware/exceptions.py
# class CommandError(SakuraIOBaseException):
#
# def __init__(self, status):
# self.status = status
#
# def __str__(self):
# return "Invalid response status '0x{0:02x}'".format(self.status)
#
# class ParityError(SakuraIOBaseException):
#
# def __init__(self):
# pass
#
# def __str__(self):
# return "Invalid parity"
. Output only the next line. | status = 0x01 |
Given the code snippet: <|code_start|> return base.execute_command(cmd, request, as_bytes=as_bytes)
def test_execute_command(self):
base = DummySakuraIO()
cmd = 0x10
request = [0x01, 0x02, 0x03, 0x04]
request.append(calc_parity(request))
response = [0x01, 0x04, 0x11, 0x12, 0x13, 0x14]
response.append(calc_parity(response))
expected = response[2:-1]
self.assertEqual(self._execute_command(cmd, request, response), expected)
def test_execute_command_status_error(self):
base = DummySakuraIO()
cmd = 0x10
request = [0x01, 0x02, 0x03, 0x04]
request.append(calc_parity(request))
status = 0x02
response = [status, 0x00]
response.append(calc_parity(response))
with self.assertRaises(CommandError):
self._execute_command(cmd, request, response)
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from sakuraio.hardware.base import calc_parity
from sakuraio.hardware.dummy import DummySakuraIO
from sakuraio.hardware.exceptions import CommandError, ParityError
and context (functions, classes, or occasionally code) from other files:
# Path: sakuraio/hardware/base.py
# def calc_parity(values):
# parity = 0x00
# for value in values:
# parity ^= value
# return parity
#
# Path: sakuraio/hardware/dummy.py
# class DummySakuraIO(SakuraIOBase):
#
# def start(self, write=True):
# pass
#
# def end(self):
# pass
#
# def initial(self, response):
# self.return_values = response
# self.values = []
#
# def send_byte(self, value):
# self.values.append(value)
#
# def recv_byte(self):
# value = self.return_values[0]
# self.return_values = self.return_values[1:]
# return value
#
# Path: sakuraio/hardware/exceptions.py
# class CommandError(SakuraIOBaseException):
#
# def __init__(self, status):
# self.status = status
#
# def __str__(self):
# return "Invalid response status '0x{0:02x}'".format(self.status)
#
# class ParityError(SakuraIOBaseException):
#
# def __init__(self):
# pass
#
# def __str__(self):
# return "Invalid parity"
. Output only the next line. | def test_execute_command_parity_error(self): |
Here is a snippet: <|code_start|>
class DummySakuraIO(SakuraIOBase):
def start(self, write=True):
pass
def end(self):
pass
def initial(self, response):
self.return_values = response
<|code_end|>
. Write the next line using the current file imports:
from sakuraio.hardware.base import SakuraIOBase
and context from other files:
# Path: sakuraio/hardware/base.py
# class SakuraIOBase(CommandMixins):
# response_wait_time = 0.01
#
# def start(self, write=True):
# return
#
# def end(self):
# return
#
# def send_byte(self, value):
# raise NotImplementedError()
#
# def recv_byte(self):
# raise NotImplementedError()
#
# def execute_command(self, cmd, request=[], as_bytes=False):
# response = []
#
# request = [cmd, len(request)] + request
# request.append(calc_parity(request))
#
# try:
# # Request
# self.start(True)
# for value in request:
# self.send_byte(value)
#
# # wait response
# time.sleep(self.response_wait_time)
#
# # Response
# self.start(False)
# status = self.recv_byte()
# if status != CMD_ERROR_NONE:
# raise CommandError(status)
#
# length = self.recv_byte()
# response = []
# for i in range(length):
# response.append(self.recv_byte())
# parity = self.recv_byte()
#
# if parity != calc_parity([status, length] + response):
# raise ParityError()
#
# except:
# self.end()
# raise
#
# self.end()
#
# if as_bytes:
# return struct.pack("B" * len(response), *response)
# return response
, which may include functions, classes, or code. Output only the next line. | self.values = [] |
Predict the next line for this snippet: <|code_start|> d[item] = value
# _put modified data
self._put_nosync(d)
def __delitem__(self, item):
self._write_op(self._delitem_nosync, item)
def _delitem_nosync(self, key):
# load existing data
d = self._get_nosync()
# delete key value
del d[key]
# _put modified data
self._put_nosync(d)
def put(self, d):
"""Overwrite all attributes with the key/value pairs in the provided dictionary
`d` in a single operation."""
self._write_op(self._put_nosync, d)
def _put_nosync(self, d):
self.store[self.key] = json_dumps(d)
if self.cache:
self._cached_asdict = d
# noinspection PyMethodOverriding
<|code_end|>
with the help of current file imports:
from collections.abc import MutableMapping
from zarr._storage.store import Store
from zarr.util import json_dumps
and context from other files:
# Path: zarr/_storage/store.py
# class Store(BaseStore):
# """Abstract store class used by implementations following the Zarr v2 spec.
#
# Adds public `listdir`, `rename`, and `rmdir` methods on top of BaseStore.
#
# .. added: 2.11.0
#
# """
#
# def listdir(self, path: str = "") -> List[str]:
# path = normalize_storage_path(path)
# return _listdir_from_keys(self, path)
#
# def rmdir(self, path: str = "") -> None:
# if not self.is_erasable():
# raise NotImplementedError(
# f'{type(self)} is not erasable, cannot call "rmdir"'
# ) # pragma: no cover
# path = normalize_storage_path(path)
# _rmdir_from_keys(self, path)
#
# Path: zarr/util.py
# def json_dumps(o: Any) -> bytes:
# """Write JSON in a consistent, human-readable way."""
# return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
# separators=(',', ': ')).encode('ascii')
, which may contain function names, class names, or code. Output only the next line. | def update(self, *args, **kwargs): |
Given snippet: <|code_start|> if dtype.kind == 'V' and dtype.hasobject:
if object_codec is None:
raise ValueError('missing object_codec for object array')
v = object_codec.encode(v)
v = str(base64.standard_b64encode(v), 'ascii')
return v
if dtype.kind == "f":
if np.isnan(v):
return "NaN"
elif np.isposinf(v):
return "Infinity"
elif np.isneginf(v):
return "-Infinity"
else:
return float(v)
elif dtype.kind in "ui":
return int(v)
elif dtype.kind == "b":
return bool(v)
elif dtype.kind in "c":
c = cast(np.complex128, np.dtype(complex).type())
v = (cls.encode_fill_value(v.real, c.real.dtype, object_codec),
cls.encode_fill_value(v.imag, c.imag.dtype, object_codec))
return v
elif dtype.kind in "SV":
v = str(base64.standard_b64encode(v), "ascii")
return v
elif dtype.kind == "U":
return v
elif dtype.kind in "mM":
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import base64
import numpy as np
import numcodecs
import numcodecs
from collections.abc import Mapping
from zarr.errors import MetadataError
from zarr.util import json_dumps, json_loads
from typing import cast, Union, Any, List, Mapping as MappingType
and context:
# Path: zarr/errors.py
# class MetadataError(Exception):
# pass
#
# Path: zarr/util.py
# def json_dumps(o: Any) -> bytes:
# """Write JSON in a consistent, human-readable way."""
# return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
# separators=(',', ': ')).encode('ascii')
#
# def json_loads(s: str) -> Dict[str, Any]:
# """Read JSON in a consistent way."""
# return json.loads(ensure_text(s, 'ascii'))
which might include code, classes, or functions. Output only the next line. | return int(v.view("i8")) |
Using the snippet: <|code_start|>
# check metadata format version
zarr_format = meta.get("zarr_format", None)
if zarr_format != cls.ZARR_FORMAT:
raise MetadataError("unsupported zarr format: %s" % zarr_format)
meta = dict(zarr_format=zarr_format)
return meta
# N.B., keep `meta` parameter as a placeholder for future
# noinspection PyUnusedLocal
@classmethod
def encode_group_metadata(cls, meta=None) -> bytes:
meta = dict(zarr_format=cls.ZARR_FORMAT)
return json_dumps(meta)
@classmethod
def decode_fill_value(cls, v: Any, dtype: np.dtype, object_codec: Any = None) -> Any:
# early out
if v is None:
return v
if dtype.kind == 'V' and dtype.hasobject:
if object_codec is None:
raise ValueError('missing object_codec for object array')
v = base64.standard_b64decode(v)
v = object_codec.decode(v)
v = np.array(v, dtype=dtype)[()]
return v
if dtype.kind == "f":
if v == "NaN":
<|code_end|>
, determine the next line of code. You have imports:
import base64
import numpy as np
import numcodecs
import numcodecs
from collections.abc import Mapping
from zarr.errors import MetadataError
from zarr.util import json_dumps, json_loads
from typing import cast, Union, Any, List, Mapping as MappingType
and context (class names, function names, or code) available:
# Path: zarr/errors.py
# class MetadataError(Exception):
# pass
#
# Path: zarr/util.py
# def json_dumps(o: Any) -> bytes:
# """Write JSON in a consistent, human-readable way."""
# return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
# separators=(',', ': ')).encode('ascii')
#
# def json_loads(s: str) -> Dict[str, Any]:
# """Read JSON in a consistent way."""
# return json.loads(ensure_text(s, 'ascii'))
. Output only the next line. | return np.nan |
Based on the snippet: <|code_start|> object_codec = None
meta = dict(
zarr_format=cls.ZARR_FORMAT,
shape=meta["shape"] + sdshape,
chunks=meta["chunks"],
dtype=cls.encode_dtype(dtype),
compressor=meta["compressor"],
fill_value=cls.encode_fill_value(meta["fill_value"], dtype, object_codec),
order=meta["order"],
filters=meta["filters"],
)
if dimension_separator:
meta['dimension_separator'] = dimension_separator
if dimension_separator:
meta["dimension_separator"] = dimension_separator
return json_dumps(meta)
@classmethod
def encode_dtype(cls, d: np.dtype):
if d.fields is None:
return d.str
else:
return d.descr
@classmethod
def _decode_dtype_descr(cls, d) -> List[Any]:
# need to convert list of lists to list of tuples
<|code_end|>
, predict the immediate next line with the help of imports:
import base64
import numpy as np
import numcodecs
import numcodecs
from collections.abc import Mapping
from zarr.errors import MetadataError
from zarr.util import json_dumps, json_loads
from typing import cast, Union, Any, List, Mapping as MappingType
and context (classes, functions, sometimes code) from other files:
# Path: zarr/errors.py
# class MetadataError(Exception):
# pass
#
# Path: zarr/util.py
# def json_dumps(o: Any) -> bytes:
# """Write JSON in a consistent, human-readable way."""
# return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
# separators=(',', ': ')).encode('ascii')
#
# def json_loads(s: str) -> Dict[str, Any]:
# """Read JSON in a consistent way."""
# return json.loads(ensure_text(s, 'ascii'))
. Output only the next line. | if isinstance(d, list): |
Given the code snippet: <|code_start|> if compressor:
chunk = compressor.decode(cdata)
else:
chunk = cdata
actual = np.frombuffer(chunk, dtype=encode_dtype)
expect = data.astype(encode_dtype)[i*chunk_size:(i+1)*chunk_size]
assert_array_equal(expect, actual)
def test_array_with_scaleoffset_filter():
# setup
astype = 'u1'
dtype = 'f8'
flt = FixedScaleOffset(scale=10, offset=1000, astype=astype, dtype=dtype)
filters = [flt]
data = np.linspace(1000, 1001, 34, dtype='f8')
for compressor in compressors:
a = array(data, chunks=5, compressor=compressor, filters=filters)
# check round-trip
assert_array_almost_equal(data, a[:], decimal=1)
# check chunks
for i in range(6):
cdata = a.store[str(i)]
if compressor:
chunk = compressor.decode(cdata)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from numcodecs import (BZ2, AsType, Blosc, Categorize, Delta, FixedScaleOffset,
PackBits, Quantize, Zlib)
from numpy.testing import assert_array_almost_equal, assert_array_equal
from zarr.creation import array
from numcodecs import LZMA
and context (functions, classes, or occasionally code) from other files:
# Path: zarr/creation.py
# def array(data, **kwargs):
# """Create an array filled with `data`.
#
# The `data` argument should be a NumPy array or array-like object. For
# other parameter definitions see :func:`zarr.creation.create`.
#
# Examples
# --------
# >>> import numpy as np
# >>> import zarr
# >>> a = np.arange(100000000).reshape(10000, 10000)
# >>> z = zarr.array(a, chunks=(1000, 1000))
# >>> z
# <zarr.core.Array (10000, 10000) int64>
#
# """
#
# # ensure data is array-like
# if not hasattr(data, 'shape') or not hasattr(data, 'dtype'):
# data = np.asanyarray(data)
#
# # setup dtype
# kw_dtype = kwargs.get('dtype')
# if kw_dtype is None:
# kwargs['dtype'] = data.dtype
# else:
# kwargs['dtype'] = kw_dtype
#
# # setup shape and chunks
# data_shape, data_chunks = _get_shape_chunks(data)
# kwargs['shape'] = data_shape
# kw_chunks = kwargs.get('chunks')
# if kw_chunks is None:
# kwargs['chunks'] = data_chunks
# else:
# kwargs['chunks'] = kw_chunks
#
# # pop read-only to apply after storing the data
# read_only = kwargs.pop('read_only', False)
#
# # instantiate array
# z = create(**kwargs)
#
# # fill with data
# z[...] = data
#
# # set read_only property afterwards
# z.read_only = read_only
#
# return z
. Output only the next line. | else: |
Based on the snippet: <|code_start|> # 2D
assert is_total_slice(Ellipsis, (100, 100))
assert is_total_slice(slice(None), (100, 100))
assert is_total_slice((slice(None), slice(None)), (100, 100))
assert is_total_slice((slice(0, 100), slice(0, 100)), (100, 100))
assert not is_total_slice((slice(0, 100), slice(0, 50)), (100, 100))
assert not is_total_slice((slice(0, 50), slice(0, 100)), (100, 100))
assert not is_total_slice((slice(0, 50), slice(0, 50)), (100, 100))
assert not is_total_slice((slice(0, 100, 2), slice(0, 100)), (100, 100))
with pytest.raises(TypeError):
is_total_slice('foo', (100,))
def test_normalize_resize_args():
# 1D
assert (200,) == normalize_resize_args((100,), 200)
assert (200,) == normalize_resize_args((100,), (200,))
# 2D
assert (200, 100) == normalize_resize_args((100, 100), (200, 100))
assert (200, 100) == normalize_resize_args((100, 100), (200, None))
assert (200, 100) == normalize_resize_args((100, 100), 200, 100)
assert (200, 100) == normalize_resize_args((100, 100), 200, None)
with pytest.raises(ValueError):
normalize_resize_args((100,), (200, 100))
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (classes, functions, sometimes code) from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | def test_human_readable_size(): |
Predict the next line for this snippet: <|code_start|> normalize_order('foo')
def test_normalize_fill_value():
assert b'' == normalize_fill_value(0, dtype=np.dtype('S1'))
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
def test_guess_chunks():
shapes = (
(100,),
(100, 100),
(1000000,),
(1000000000,),
(10000000000000000000000,),
(10000, 10000),
(10000000, 1000),
(1000, 10000000),
(10000000, 1000, 2),
(1000, 10000000, 2),
(10000, 10000, 10000),
(100000, 100000, 100000),
(1000000000, 1000000000, 1000000000),
(0,),
(0, 0),
(10, 0),
(0, 10),
<|code_end|>
with the help of current file imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
, which may contain function names, class names, or code. Output only the next line. | (1, 2, 0, 4, 5), |
Given the following code snippet before the placeholder: <|code_start|> assert '100' == human_readable_size(100)
assert '1.0K' == human_readable_size(2**10)
assert '1.0M' == human_readable_size(2**20)
assert '1.0G' == human_readable_size(2**30)
assert '1.0T' == human_readable_size(2**40)
assert '1.0P' == human_readable_size(2**50)
def test_normalize_order():
assert 'F' == normalize_order('F')
assert 'C' == normalize_order('C')
assert 'F' == normalize_order('f')
assert 'C' == normalize_order('c')
with pytest.raises(ValueError):
normalize_order('foo')
def test_normalize_fill_value():
assert b'' == normalize_fill_value(0, dtype=np.dtype('S1'))
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
def test_guess_chunks():
shapes = (
(100,),
(100, 100),
(1000000,),
<|code_end|>
, predict the next line using imports from the current file:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context including class names, function names, and sometimes code from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | (1000000000,), |
Based on the snippet: <|code_start|>
def test_normalize_order():
assert 'F' == normalize_order('F')
assert 'C' == normalize_order('C')
assert 'F' == normalize_order('f')
assert 'C' == normalize_order('c')
with pytest.raises(ValueError):
normalize_order('foo')
def test_normalize_fill_value():
assert b'' == normalize_fill_value(0, dtype=np.dtype('S1'))
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
def test_guess_chunks():
shapes = (
(100,),
(100, 100),
(1000000,),
(1000000000,),
(10000000000000000000000,),
(10000, 10000),
(10000000, 1000),
(1000, 10000000),
(10000000, 1000, 2),
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (classes, functions, sometimes code) from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | (1000, 10000000, 2), |
Based on the snippet: <|code_start|> )
for shape in shapes:
chunks = guess_chunks(shape, 1)
assert isinstance(chunks, tuple)
assert len(chunks) == len(shape)
# doesn't make any sense to allow chunks to have zero length dimension
assert all(0 < c <= max(s, 1) for c, s in zip(chunks, shape))
# ludicrous itemsize
chunks = guess_chunks((1000000,), 40000000000)
assert isinstance(chunks, tuple)
assert (1,) == chunks
def test_info_text_report():
items = [('foo', 'bar'), ('baz', 'qux')]
expect = "foo : bar\nbaz : qux\n"
assert expect == info_text_report(items)
def test_info_html_report():
items = [('foo', 'bar'), ('baz', 'qux')]
actual = info_html_report(items)
assert '<table' == actual[:6]
assert '</table>' == actual[-8:]
def test_tree_get_icon():
assert tree_get_icon("Array") == tree_array_icon
assert tree_get_icon("Group") == tree_group_icon
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (classes, functions, sometimes code) from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | with pytest.raises(ValueError): |
Continue the code snippet: <|code_start|>
def test_normalize_order():
assert 'F' == normalize_order('F')
assert 'C' == normalize_order('C')
assert 'F' == normalize_order('f')
assert 'C' == normalize_order('c')
with pytest.raises(ValueError):
normalize_order('foo')
def test_normalize_fill_value():
assert b'' == normalize_fill_value(0, dtype=np.dtype('S1'))
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
def test_guess_chunks():
shapes = (
(100,),
(100, 100),
(1000000,),
(1000000000,),
(10000000000000000000000,),
(10000, 10000),
(10000000, 1000),
(1000, 10000000),
(10000000, 1000, 2),
<|code_end|>
. Use current file imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (classes, functions, or code) from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | (1000, 10000000, 2), |
Given the code snippet: <|code_start|> assert '1.0P' == human_readable_size(2**50)
def test_normalize_order():
assert 'F' == normalize_order('F')
assert 'C' == normalize_order('C')
assert 'F' == normalize_order('f')
assert 'C' == normalize_order('c')
with pytest.raises(ValueError):
normalize_order('foo')
def test_normalize_fill_value():
assert b'' == normalize_fill_value(0, dtype=np.dtype('S1'))
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
def test_guess_chunks():
shapes = (
(100,),
(100, 100),
(1000000,),
(1000000000,),
(10000000000000000000000,),
(10000, 10000),
(10000000, 1000),
(1000, 10000000),
<|code_end|>
, generate the next line using the imports in this file:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (functions, classes, or occasionally code) from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | (10000000, 1000, 2), |
Given the following code snippet before the placeholder: <|code_start|>
@mock.patch.dict("sys.modules", {"ipytree": None})
def test_tree_widget_missing_ipytree():
pattern = (
"Run `pip install zarr[jupyter]` or `conda install ipytree`"
"to get the required ipytree dependency for displaying the tree "
"widget. If using jupyterlab<3, you also need to run "
"`jupyter labextension install ipytree`"
)
with pytest.raises(ImportError, match=re.escape(pattern)):
tree_widget(None, None, None)
def test_retry_call():
class Fixture:
def __init__(self, pass_on=1):
self.c = 0
self.pass_on = pass_on
def __call__(self):
self.c += 1
if self.c != self.pass_on:
raise PermissionError()
for x in range(1, 11):
# Any number of failures less than 10 will be accepted.
fixture = Fixture(pass_on=x)
retry_call(fixture, exceptions=(PermissionError,), wait=0)
<|code_end|>
, predict the next line using imports from the current file:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context including class names, function names, and sometimes code from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | assert fixture.c == x |
Using the snippet: <|code_start|> (1000000000, 1000000000, 1000000000),
(0,),
(0, 0),
(10, 0),
(0, 10),
(1, 2, 0, 4, 5),
)
for shape in shapes:
chunks = guess_chunks(shape, 1)
assert isinstance(chunks, tuple)
assert len(chunks) == len(shape)
# doesn't make any sense to allow chunks to have zero length dimension
assert all(0 < c <= max(s, 1) for c, s in zip(chunks, shape))
# ludicrous itemsize
chunks = guess_chunks((1000000,), 40000000000)
assert isinstance(chunks, tuple)
assert (1,) == chunks
def test_info_text_report():
items = [('foo', 'bar'), ('baz', 'qux')]
expect = "foo : bar\nbaz : qux\n"
assert expect == info_text_report(items)
def test_info_html_report():
items = [('foo', 'bar'), ('baz', 'qux')]
actual = info_html_report(items)
assert '<table' == actual[:6]
<|code_end|>
, determine the next line of code. You have imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (class names, function names, or code) available:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | assert '</table>' == actual[-8:] |
Given the following code snippet before the placeholder: <|code_start|> with pytest.raises(ValueError):
normalize_order('foo')
def test_normalize_fill_value():
assert b'' == normalize_fill_value(0, dtype=np.dtype('S1'))
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
def test_guess_chunks():
shapes = (
(100,),
(100, 100),
(1000000,),
(1000000000,),
(10000000000000000000000,),
(10000, 10000),
(10000000, 1000),
(1000, 10000000),
(10000000, 1000, 2),
(1000, 10000000, 2),
(10000, 10000, 10000),
(100000, 100000, 100000),
(1000000000, 1000000000, 1000000000),
(0,),
(0, 0),
(10, 0),
<|code_end|>
, predict the next line using imports from the current file:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context including class names, function names, and sometimes code from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | (0, 10), |
Predict the next line after this snippet: <|code_start|> assert '1.0G' == human_readable_size(2**30)
assert '1.0T' == human_readable_size(2**40)
assert '1.0P' == human_readable_size(2**50)
def test_normalize_order():
assert 'F' == normalize_order('F')
assert 'C' == normalize_order('C')
assert 'F' == normalize_order('f')
assert 'C' == normalize_order('c')
with pytest.raises(ValueError):
normalize_order('foo')
def test_normalize_fill_value():
assert b'' == normalize_fill_value(0, dtype=np.dtype('S1'))
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
def test_guess_chunks():
shapes = (
(100,),
(100, 100),
(1000000,),
(1000000000,),
(10000000000000000000000,),
(10000, 10000),
<|code_end|>
using the current file's imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and any relevant context from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | (10000000, 1000), |
Given the code snippet: <|code_start|>
def test_normalize_dimension_separator():
assert None is normalize_dimension_separator(None)
assert '/' == normalize_dimension_separator('/')
assert '.' == normalize_dimension_separator('.')
<|code_end|>
, generate the next line using the imports in this file:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (functions, classes, or occasionally code) from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | with pytest.raises(ValueError): |
Here is a snippet: <|code_start|>
with pytest.raises(TypeError):
is_total_slice('foo', (100,))
def test_normalize_resize_args():
# 1D
assert (200,) == normalize_resize_args((100,), 200)
assert (200,) == normalize_resize_args((100,), (200,))
# 2D
assert (200, 100) == normalize_resize_args((100, 100), (200, 100))
assert (200, 100) == normalize_resize_args((100, 100), (200, None))
assert (200, 100) == normalize_resize_args((100, 100), 200, 100)
assert (200, 100) == normalize_resize_args((100, 100), 200, None)
with pytest.raises(ValueError):
normalize_resize_args((100,), (200, 100))
def test_human_readable_size():
assert '100' == human_readable_size(100)
assert '1.0K' == human_readable_size(2**10)
assert '1.0M' == human_readable_size(2**20)
assert '1.0G' == human_readable_size(2**30)
assert '1.0T' == human_readable_size(2**40)
assert '1.0P' == human_readable_size(2**50)
<|code_end|>
. Write the next line using the current file imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
, which may include functions, classes, or code. Output only the next line. | def test_normalize_order(): |
Using the snippet: <|code_start|> expect = "foo : bar\nbaz : qux\n"
assert expect == info_text_report(items)
def test_info_html_report():
items = [('foo', 'bar'), ('baz', 'qux')]
actual = info_html_report(items)
assert '<table' == actual[:6]
assert '</table>' == actual[-8:]
def test_tree_get_icon():
assert tree_get_icon("Array") == tree_array_icon
assert tree_get_icon("Group") == tree_group_icon
with pytest.raises(ValueError):
tree_get_icon("Baz")
@mock.patch.dict("sys.modules", {"ipytree": None})
def test_tree_widget_missing_ipytree():
pattern = (
"Run `pip install zarr[jupyter]` or `conda install ipytree`"
"to get the required ipytree dependency for displaying the tree "
"widget. If using jupyterlab<3, you also need to run "
"`jupyter labextension install ipytree`"
)
with pytest.raises(ImportError, match=re.escape(pattern)):
tree_widget(None, None, None)
<|code_end|>
, determine the next line of code. You have imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (class names, function names, or code) available:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | def test_retry_call(): |
Continue the code snippet: <|code_start|> assert all(0 < c <= max(s, 1) for c, s in zip(chunks, shape))
# ludicrous itemsize
chunks = guess_chunks((1000000,), 40000000000)
assert isinstance(chunks, tuple)
assert (1,) == chunks
def test_info_text_report():
items = [('foo', 'bar'), ('baz', 'qux')]
expect = "foo : bar\nbaz : qux\n"
assert expect == info_text_report(items)
def test_info_html_report():
items = [('foo', 'bar'), ('baz', 'qux')]
actual = info_html_report(items)
assert '<table' == actual[:6]
assert '</table>' == actual[-8:]
def test_tree_get_icon():
assert tree_get_icon("Array") == tree_array_icon
assert tree_get_icon("Group") == tree_group_icon
with pytest.raises(ValueError):
tree_get_icon("Baz")
@mock.patch.dict("sys.modules", {"ipytree": None})
def test_tree_widget_missing_ipytree():
<|code_end|>
. Use current file imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context (classes, functions, or code) from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | pattern = ( |
Given the following code snippet before the placeholder: <|code_start|> (1000, 10000000, 2),
(10000, 10000, 10000),
(100000, 100000, 100000),
(1000000000, 1000000000, 1000000000),
(0,),
(0, 0),
(10, 0),
(0, 10),
(1, 2, 0, 4, 5),
)
for shape in shapes:
chunks = guess_chunks(shape, 1)
assert isinstance(chunks, tuple)
assert len(chunks) == len(shape)
# doesn't make any sense to allow chunks to have zero length dimension
assert all(0 < c <= max(s, 1) for c, s in zip(chunks, shape))
# ludicrous itemsize
chunks = guess_chunks((1000000,), 40000000000)
assert isinstance(chunks, tuple)
assert (1,) == chunks
def test_info_text_report():
items = [('foo', 'bar'), ('baz', 'qux')]
expect = "foo : bar\nbaz : qux\n"
assert expect == info_text_report(items)
def test_info_html_report():
<|code_end|>
, predict the next line using imports from the current file:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context including class names, function names, and sometimes code from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | items = [('foo', 'bar'), ('baz', 'qux')] |
Given snippet: <|code_start|> assert (200,) == normalize_resize_args((100,), (200,))
# 2D
assert (200, 100) == normalize_resize_args((100, 100), (200, 100))
assert (200, 100) == normalize_resize_args((100, 100), (200, None))
assert (200, 100) == normalize_resize_args((100, 100), 200, 100)
assert (200, 100) == normalize_resize_args((100, 100), 200, None)
with pytest.raises(ValueError):
normalize_resize_args((100,), (200, 100))
def test_human_readable_size():
assert '100' == human_readable_size(100)
assert '1.0K' == human_readable_size(2**10)
assert '1.0M' == human_readable_size(2**20)
assert '1.0G' == human_readable_size(2**30)
assert '1.0T' == human_readable_size(2**40)
assert '1.0P' == human_readable_size(2**50)
def test_normalize_order():
assert 'F' == normalize_order('F')
assert 'C' == normalize_order('C')
assert 'F' == normalize_order('f')
assert 'C' == normalize_order('c')
with pytest.raises(ValueError):
normalize_order('foo')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget)
and context:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
which might include code, classes, or functions. Output only the next line. | def test_normalize_fill_value(): |
Next line prediction: <|code_start|> assert '1.0K' == human_readable_size(2**10)
assert '1.0M' == human_readable_size(2**20)
assert '1.0G' == human_readable_size(2**30)
assert '1.0T' == human_readable_size(2**40)
assert '1.0P' == human_readable_size(2**50)
def test_normalize_order():
assert 'F' == normalize_order('F')
assert 'C' == normalize_order('C')
assert 'F' == normalize_order('f')
assert 'C' == normalize_order('c')
with pytest.raises(ValueError):
normalize_order('foo')
def test_normalize_fill_value():
assert b'' == normalize_fill_value(0, dtype=np.dtype('S1'))
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
def test_guess_chunks():
shapes = (
(100,),
(100, 100),
(1000000,),
(1000000000,),
<|code_end|>
. Use current file imports:
(import re
import numpy as np
import pytest
from unittest import mock
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
tree_array_icon, tree_group_icon, tree_get_icon,
tree_widget))
and context including class names, function names, or small code snippets from other files:
# Path: zarr/util.py
# def flatten(arg: Iterable) -> Iterable:
# def json_dumps(o: Any) -> bytes:
# def json_loads(s: str) -> Dict[str, Any]:
# def normalize_shape(shape) -> Tuple[int]:
# def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]:
# def normalize_chunks(
# chunks: Any, shape: Tuple[int, ...], typesize: int
# ) -> Tuple[int, ...]:
# def normalize_dtype(dtype: Union[str, np.dtype], object_codec) -> Tuple[np.dtype, Any]:
# def is_total_slice(item, shape: Tuple[int]) -> bool:
# def normalize_resize_args(old_shape, *args):
# def human_readable_size(size) -> str:
# def normalize_order(order: str) -> str:
# def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]:
# def normalize_fill_value(fill_value, dtype: np.dtype):
# def normalize_storage_path(path: Union[str, bytes, None]) -> str:
# def buffer_size(v) -> int:
# def info_text_report(items: Dict[Any, Any]) -> str:
# def info_html_report(items) -> str:
# def __init__(self, obj):
# def __repr__(self):
# def _repr_html_(self):
# def __init__(self, obj, depth=0, level=None):
# def get_children(self):
# def get_text(self):
# def get_type(self):
# def get_children(self, node):
# def get_root(self, tree):
# def get_text(self, node):
# def tree_get_icon(stype: str) -> str:
# def tree_widget_sublist(node, root=False, expand=False):
# def tree_widget(group, expand, level):
# def __init__(self, group, expand=False, level=None):
# def __bytes__(self):
# def __unicode__(self):
# def __repr__(self):
# def _ipython_display_(self):
# def check_array_shape(param, array, shape):
# def is_valid_python_name(name):
# def __enter__(self):
# def __exit__(self, *args):
# def __init__(self, store_key, chunk_store):
# def prepare_chunk(self):
# def read_part(self, start, nitems):
# def read_full(self):
# def retry_call(callabl: Callable,
# args=None,
# kwargs=None,
# exceptions: Tuple[Any, ...] = (),
# retries: int = 10,
# wait: float = 0.1) -> Any:
# def all_equal(value: Any, array: Any):
# CHUNK_BASE = 256*1024 # Multiplier by which chunks are adjusted
# CHUNK_MIN = 128*1024 # Soft lower limit (128k)
# CHUNK_MAX = 64*1024*1024 # Hard upper limit
# class InfoReporter:
# class TreeNode:
# class TreeTraversal(Traversal):
# class TreeViewer:
# class NoLock:
# class PartialReadBuffer:
. Output only the next line. | (10000000000000000000000,), |
Predict the next line for this snippet: <|code_start|> else:
dim_out_sel = self.dim_out_sel[start:stop]
# find region in chunk
dim_offset = dim_chunk_ix * self.dim_chunk_len
dim_chunk_sel = self.dim_sel[start:stop] - dim_offset
yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel)
def slice_to_range(s: slice, l: int): # noqa: E741
return range(*s.indices(l))
def ix_(selection, shape):
"""Convert an orthogonal selection to a numpy advanced (fancy) selection, like numpy.ix_
but with support for slices and single ints."""
# normalisation
selection = replace_ellipsis(selection, shape)
# replace slice and int as these are not supported by numpy.ix_
selection = [slice_to_range(dim_sel, dim_len) if isinstance(dim_sel, slice)
else [dim_sel] if is_integer(dim_sel)
else dim_sel
for dim_sel, dim_len in zip(selection, shape)]
# now get numpy to convert to a coordinate selection
selection = np.ix_(*selection)
<|code_end|>
with the help of current file imports:
import collections
import itertools
import math
import numbers
import numpy as np
from zarr.errors import (
ArrayIndexError,
NegativeStepError,
err_too_many_indices,
VindexInvalidSelectionError,
BoundsCheckError,
)
and context from other files:
# Path: zarr/errors.py
# class ArrayIndexError(IndexError):
# pass
#
# class NegativeStepError(IndexError):
# def __init__(self):
# super().__init__("only slices with step >= 1 are supported")
#
# def err_too_many_indices(selection, shape):
# raise IndexError('too many indices for array; expected {}, got {}'
# .format(len(shape), len(selection)))
#
# class VindexInvalidSelectionError(_BaseZarrIndexError):
# _msg = (
# "unsupported selection type for vectorized indexing; only "
# "coordinate selection (tuple of integer arrays) and mask selection "
# "(single Boolean array) are supported; got {0!r}"
# )
#
# class BoundsCheckError(_BaseZarrIndexError):
# _msg = "index out of bounds for dimension with length {0}"
, which may contain function names, class names, or code. Output only the next line. | return selection |
Given the following code snippet before the placeholder: <|code_start|> # find region in output
if dim_chunk_ix == 0:
start = 0
else:
start = self.chunk_nitems_cumsum[dim_chunk_ix - 1]
stop = self.chunk_nitems_cumsum[dim_chunk_ix]
if self.order == Order.INCREASING:
dim_out_sel = slice(start, stop)
else:
dim_out_sel = self.dim_out_sel[start:stop]
# find region in chunk
dim_offset = dim_chunk_ix * self.dim_chunk_len
dim_chunk_sel = self.dim_sel[start:stop] - dim_offset
yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel)
def slice_to_range(s: slice, l: int): # noqa: E741
return range(*s.indices(l))
def ix_(selection, shape):
"""Convert an orthogonal selection to a numpy advanced (fancy) selection, like numpy.ix_
but with support for slices and single ints."""
# normalisation
selection = replace_ellipsis(selection, shape)
# replace slice and int as these are not supported by numpy.ix_
<|code_end|>
, predict the next line using imports from the current file:
import collections
import itertools
import math
import numbers
import numpy as np
from zarr.errors import (
ArrayIndexError,
NegativeStepError,
err_too_many_indices,
VindexInvalidSelectionError,
BoundsCheckError,
)
and context including class names, function names, and sometimes code from other files:
# Path: zarr/errors.py
# class ArrayIndexError(IndexError):
# pass
#
# class NegativeStepError(IndexError):
# def __init__(self):
# super().__init__("only slices with step >= 1 are supported")
#
# def err_too_many_indices(selection, shape):
# raise IndexError('too many indices for array; expected {}, got {}'
# .format(len(shape), len(selection)))
#
# class VindexInvalidSelectionError(_BaseZarrIndexError):
# _msg = (
# "unsupported selection type for vectorized indexing; only "
# "coordinate selection (tuple of integer arrays) and mask selection "
# "(single Boolean array) are supported; got {0!r}"
# )
#
# class BoundsCheckError(_BaseZarrIndexError):
# _msg = "index out of bounds for dimension with length {0}"
. Output only the next line. | selection = [slice_to_range(dim_sel, dim_len) if isinstance(dim_sel, slice) |
Given the following code snippet before the placeholder: <|code_start|> start = 0
else:
start = self.chunk_nitems_cumsum[dim_chunk_ix - 1]
stop = self.chunk_nitems_cumsum[dim_chunk_ix]
if self.order == Order.INCREASING:
dim_out_sel = slice(start, stop)
else:
dim_out_sel = self.dim_out_sel[start:stop]
# find region in chunk
dim_offset = dim_chunk_ix * self.dim_chunk_len
dim_chunk_sel = self.dim_sel[start:stop] - dim_offset
yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel)
def slice_to_range(s: slice, l: int): # noqa: E741
return range(*s.indices(l))
def ix_(selection, shape):
"""Convert an orthogonal selection to a numpy advanced (fancy) selection, like numpy.ix_
but with support for slices and single ints."""
# normalisation
selection = replace_ellipsis(selection, shape)
# replace slice and int as these are not supported by numpy.ix_
selection = [slice_to_range(dim_sel, dim_len) if isinstance(dim_sel, slice)
else [dim_sel] if is_integer(dim_sel)
<|code_end|>
, predict the next line using imports from the current file:
import collections
import itertools
import math
import numbers
import numpy as np
from zarr.errors import (
ArrayIndexError,
NegativeStepError,
err_too_many_indices,
VindexInvalidSelectionError,
BoundsCheckError,
)
and context including class names, function names, and sometimes code from other files:
# Path: zarr/errors.py
# class ArrayIndexError(IndexError):
# pass
#
# class NegativeStepError(IndexError):
# def __init__(self):
# super().__init__("only slices with step >= 1 are supported")
#
# def err_too_many_indices(selection, shape):
# raise IndexError('too many indices for array; expected {}, got {}'
# .format(len(shape), len(selection)))
#
# class VindexInvalidSelectionError(_BaseZarrIndexError):
# _msg = (
# "unsupported selection type for vectorized indexing; only "
# "coordinate selection (tuple of integer arrays) and mask selection "
# "(single Boolean array) are supported; got {0!r}"
# )
#
# class BoundsCheckError(_BaseZarrIndexError):
# _msg = "index out of bounds for dimension with length {0}"
. Output only the next line. | else dim_sel |
Given the following code snippet before the placeholder: <|code_start|> if self.order == Order.INCREASING:
dim_out_sel = slice(start, stop)
else:
dim_out_sel = self.dim_out_sel[start:stop]
# find region in chunk
dim_offset = dim_chunk_ix * self.dim_chunk_len
dim_chunk_sel = self.dim_sel[start:stop] - dim_offset
yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel)
def slice_to_range(s: slice, l: int): # noqa: E741
return range(*s.indices(l))
def ix_(selection, shape):
"""Convert an orthogonal selection to a numpy advanced (fancy) selection, like numpy.ix_
but with support for slices and single ints."""
# normalisation
selection = replace_ellipsis(selection, shape)
# replace slice and int as these are not supported by numpy.ix_
selection = [slice_to_range(dim_sel, dim_len) if isinstance(dim_sel, slice)
else [dim_sel] if is_integer(dim_sel)
else dim_sel
for dim_sel, dim_len in zip(selection, shape)]
# now get numpy to convert to a coordinate selection
<|code_end|>
, predict the next line using imports from the current file:
import collections
import itertools
import math
import numbers
import numpy as np
from zarr.errors import (
ArrayIndexError,
NegativeStepError,
err_too_many_indices,
VindexInvalidSelectionError,
BoundsCheckError,
)
and context including class names, function names, and sometimes code from other files:
# Path: zarr/errors.py
# class ArrayIndexError(IndexError):
# pass
#
# class NegativeStepError(IndexError):
# def __init__(self):
# super().__init__("only slices with step >= 1 are supported")
#
# def err_too_many_indices(selection, shape):
# raise IndexError('too many indices for array; expected {}, got {}'
# .format(len(shape), len(selection)))
#
# class VindexInvalidSelectionError(_BaseZarrIndexError):
# _msg = (
# "unsupported selection type for vectorized indexing; only "
# "coordinate selection (tuple of integer arrays) and mask selection "
# "(single Boolean array) are supported; got {0!r}"
# )
#
# class BoundsCheckError(_BaseZarrIndexError):
# _msg = "index out of bounds for dimension with length {0}"
. Output only the next line. | selection = np.ix_(*selection) |
Predict the next line after this snippet: <|code_start|>
urlpatterns = patterns('replayswithfriends.sc2match.views',
url(r'^player/$', PlayerList.as_view(), name='player_list'),
url(r'^player/(?P<pk>[\d]+)$', PlayerDetail.as_view(), name='player_detail'),
url(r'^match/$', MatchList.as_view(), name='match_list'),
url(r'^match/(?P<pk>[\d]+)/$', MatchView.as_view(), name='match_detail'),
url(r'^match/upload/$', MatchUpload.as_view(), name='match_upload'),
url(r'^match/upload/done/$', 'match_upload_done', name='match_upload'),
<|code_end|>
using the current file's imports:
from django.conf.urls.defaults import patterns, url
from replayswithfriends.sc2match.views import (MatchView, MatchList, PlayerList,
PlayerDetail, MatchUpload)
and any relevant context from other files:
# Path: replayswithfriends/sc2match/views.py
# class MatchView(DetailView):
# queryset = Match.share.all().select_related('playerresult', 'playerresult__player', 'message')
#
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Match.share.available(self.request.user).select_related('playerresult', 'playerresult__player', 'message')
# else:
# return Match.share.public().select_related('playerresult', 'playerresult__player', 'message')
#
# class MatchList(ListView):
# queryset = Match.share.all()
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Match.share.available(self.request.user)
# else:
# return Match.share.public()
#
# class PlayerList(ListView):
# queryset = Player.objects.all()
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Player.objects.filter(match__in=Match.share.available(self.request.user))
# else:
# return Player.objects.filter(match__in=Match.share.public())
#
# class PlayerDetail(DetailView):
# queryset = Player.objects.all()
# slug_field = 'username'
# slug_url_kwarg = 'username'
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Player.objects.filter(match__in=Match.share.available(self.request.user))
# else:
# return Player.objects.filter(match__in=Match.share.public())
#
# class MatchUpload(CreateView):
# success_url = '/sc2/match/upload/'
# form_class = MatchUploadForm
# template_name = 'sc2match/upload.html'
# queryset = Match.objects.all()
#
# def get_form_kwargs(self):
# kw = super(MatchUpload, self).get_form_kwargs()
# kw.update({'user': self.request.user})
# return kw
#
# @method_decorator(login_required)
# def dispatch(self, *args, **kwargs):
# return super(MatchUpload, self).dispatch(*args, **kwargs)
. Output only the next line. | ) |
Next line prediction: <|code_start|>
urlpatterns = patterns('replayswithfriends.sc2match.views',
url(r'^player/$', PlayerList.as_view(), name='player_list'),
url(r'^player/(?P<pk>[\d]+)$', PlayerDetail.as_view(), name='player_detail'),
url(r'^match/$', MatchList.as_view(), name='match_list'),
url(r'^match/(?P<pk>[\d]+)/$', MatchView.as_view(), name='match_detail'),
url(r'^match/upload/$', MatchUpload.as_view(), name='match_upload'),
url(r'^match/upload/done/$', 'match_upload_done', name='match_upload'),
<|code_end|>
. Use current file imports:
(from django.conf.urls.defaults import patterns, url
from replayswithfriends.sc2match.views import (MatchView, MatchList, PlayerList,
PlayerDetail, MatchUpload))
and context including class names, function names, or small code snippets from other files:
# Path: replayswithfriends/sc2match/views.py
# class MatchView(DetailView):
# queryset = Match.share.all().select_related('playerresult', 'playerresult__player', 'message')
#
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Match.share.available(self.request.user).select_related('playerresult', 'playerresult__player', 'message')
# else:
# return Match.share.public().select_related('playerresult', 'playerresult__player', 'message')
#
# class MatchList(ListView):
# queryset = Match.share.all()
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Match.share.available(self.request.user)
# else:
# return Match.share.public()
#
# class PlayerList(ListView):
# queryset = Player.objects.all()
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Player.objects.filter(match__in=Match.share.available(self.request.user))
# else:
# return Player.objects.filter(match__in=Match.share.public())
#
# class PlayerDetail(DetailView):
# queryset = Player.objects.all()
# slug_field = 'username'
# slug_url_kwarg = 'username'
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Player.objects.filter(match__in=Match.share.available(self.request.user))
# else:
# return Player.objects.filter(match__in=Match.share.public())
#
# class MatchUpload(CreateView):
# success_url = '/sc2/match/upload/'
# form_class = MatchUploadForm
# template_name = 'sc2match/upload.html'
# queryset = Match.objects.all()
#
# def get_form_kwargs(self):
# kw = super(MatchUpload, self).get_form_kwargs()
# kw.update({'user': self.request.user})
# return kw
#
# @method_decorator(login_required)
# def dispatch(self, *args, **kwargs):
# return super(MatchUpload, self).dispatch(*args, **kwargs)
. Output only the next line. | ) |
Using the snippet: <|code_start|>
urlpatterns = patterns('replayswithfriends.sc2match.views',
url(r'^player/$', PlayerList.as_view(), name='player_list'),
url(r'^player/(?P<pk>[\d]+)$', PlayerDetail.as_view(), name='player_detail'),
url(r'^match/$', MatchList.as_view(), name='match_list'),
url(r'^match/(?P<pk>[\d]+)/$', MatchView.as_view(), name='match_detail'),
url(r'^match/upload/$', MatchUpload.as_view(), name='match_upload'),
url(r'^match/upload/done/$', 'match_upload_done', name='match_upload'),
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls.defaults import patterns, url
from replayswithfriends.sc2match.views import (MatchView, MatchList, PlayerList,
PlayerDetail, MatchUpload)
and context (class names, function names, or code) available:
# Path: replayswithfriends/sc2match/views.py
# class MatchView(DetailView):
# queryset = Match.share.all().select_related('playerresult', 'playerresult__player', 'message')
#
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Match.share.available(self.request.user).select_related('playerresult', 'playerresult__player', 'message')
# else:
# return Match.share.public().select_related('playerresult', 'playerresult__player', 'message')
#
# class MatchList(ListView):
# queryset = Match.share.all()
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Match.share.available(self.request.user)
# else:
# return Match.share.public()
#
# class PlayerList(ListView):
# queryset = Player.objects.all()
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Player.objects.filter(match__in=Match.share.available(self.request.user))
# else:
# return Player.objects.filter(match__in=Match.share.public())
#
# class PlayerDetail(DetailView):
# queryset = Player.objects.all()
# slug_field = 'username'
# slug_url_kwarg = 'username'
# def get_queryset(self):
# if self.request.user.is_authenticated():
# return Player.objects.filter(match__in=Match.share.available(self.request.user))
# else:
# return Player.objects.filter(match__in=Match.share.public())
#
# class MatchUpload(CreateView):
# success_url = '/sc2/match/upload/'
# form_class = MatchUploadForm
# template_name = 'sc2match/upload.html'
# queryset = Match.objects.all()
#
# def get_form_kwargs(self):
# kw = super(MatchUpload, self).get_form_kwargs()
# kw.update({'user': self.request.user})
# return kw
#
# @method_decorator(login_required)
# def dispatch(self, *args, **kwargs):
# return super(MatchUpload, self).dispatch(*args, **kwargs)
. Output only the next line. | ) |
Next line prediction: <|code_start|>class PlayerDetail(DetailView):
queryset = Player.objects.all()
slug_field = 'username'
slug_url_kwarg = 'username'
def get_queryset(self):
if self.request.user.is_authenticated():
return Player.objects.filter(match__in=Match.share.available(self.request.user))
else:
return Player.objects.filter(match__in=Match.share.public())
class PlayerList(ListView):
queryset = Player.objects.all()
def get_queryset(self):
if self.request.user.is_authenticated():
return Player.objects.filter(match__in=Match.share.available(self.request.user))
else:
return Player.objects.filter(match__in=Match.share.public())
class MatchView(DetailView):
queryset = Match.share.all().select_related('playerresult', 'playerresult__player', 'message')
def get_queryset(self):
if self.request.user.is_authenticated():
return Match.share.available(self.request.user).select_related('playerresult', 'playerresult__player', 'message')
else:
return Match.share.public().select_related('playerresult', 'playerresult__player', 'message')
class MatchList(ListView):
queryset = Match.share.all()
def get_queryset(self):
<|code_end|>
. Use current file imports:
(from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView
from django.http import HttpResponse
from .models import Match, Player
from .forms import MatchUploadForm
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from sc2reader.events import *
import json)
and context including class names, function names, or small code snippets from other files:
# Path: replayswithfriends/sc2match/models.py
# class Match(models.Model):
# owner = models.ForeignKey(User)
# created = models.DateTimeField(default=timezone.now, editable=False)
# modified = models.DateTimeField(editable=False)
# replay_file = models.FileField(upload_to=generate_filename, storage=storage_engine)
# mapfield = models.ForeignKey(Map, null=True, editable=False)
# duration = models.PositiveIntegerField(null=True, editable=False)
# gateway = models.CharField(max_length=32, default="us")
# processed = models.NullBooleanField(default=None)
# process_error = models.TextField(blank=True, default='', editable=False)
# match_share = models.PositiveSmallIntegerField(choices=SHARE, default=SHARE.FRIENDS)
# matchhash = models.CharField(max_length=512, editable=False, blank=True, default='')
# is_ladder = models.BooleanField(default=True)
# game_played_on = models.DateTimeField(null=True, blank=True)
# game_type = models.CharField(max_length=64, blank=True, default=True)
# game_speed = models.CharField(max_length=64, blank=True, default=True)
# events_json = models.TextField(editable=False, blank=True)
#
# objects = models.Manager()
# share = ShareManager()
# processing = ProcessedManager()
#
# def __init__(self, *args, **kwargs):
# self._replay = None
# super(Match, self).__init__(*args, **kwargs)
#
# def __unicode__(self):
# if self.processed:
# return "%s" % ", ".join(self.players.all().values_list('nick', flat=True).order_by("nick"))
# else:
# return "unprocessed match %s" % self.created
#
# def process_now(self):
# from .tasks import parse_replay
# parse_replay(self.id)
#
# @models.permalink
# def get_absolute_url(self):
# return ('match_detail', [self.id])
#
# @property
# def replay(self):
# if not self._replay:
# self._replay = sc2reader.load_replay(self.replay_file.file, load_map=False)
# return self._replay
#
# @property
# def time_display(self):
# if self.duration:
# minutes = self.duration / 60
# seconds = self.duration % 60
# return '%d:%02d' % (minutes, seconds)
# else:
# return '-'
#
# def make_hash(self, block_size=2**8):
# md5 = hashlib.md5()
# while True:
# data = self.replay_file.read(block_size)
# if not data:
# break
# md5.update(data)
# data = self.replay_file.seek(0)
# self.matchhash = md5.hexdigest()
#
# @property
# def winners(self):
# return self.players.filter(result=True)
#
# @property
# def losers(self):
# return self.players.filter(result=False)
#
# def save(self, *args, **kwargs):
# self.modified = timezone.now()
# if not self.matchhash:
# self.make_hash()
# super(Match, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ['-game_played_on', '-modified']
# unique_together = ['owner', 'matchhash']
#
# class Player(models.Model):
# user = models.ForeignKey(User, null=True)
# username = models.CharField(max_length=64)
# battle_net_url = models.URLField(help_text="Go to http://us.battle.net/sc2/en/ and click on your avatar to go to your profile URL", blank=True)
# region = models.PositiveSmallIntegerField(choices=REGIONS, default=REGIONS.NA)
#
# def __unicode__(self):
# return self.username
#
# class Meta:
# unique_together = ['username', 'battle_net_url']
#
# Path: replayswithfriends/sc2match/forms.py
# class MatchUploadForm(ModelForm):
#
# def __init__(self, *args, **kwargs):
# self.user = kwargs.pop('user', None)
# super(MatchUploadForm, self).__init__(*args, **kwargs)
#
# def save(self, *args, **kwargs):
# commit = kwargs.get('commit', True)
# match = super(MatchUploadForm, self).save(commit=False)
# match.owner = self.user
# if commit:
# match.save()
# print "werp"
# return match
#
# class Meta:
# model = Match
# fields = ['replay_file']
. Output only the next line. | if self.request.user.is_authenticated(): |
Here is a snippet: <|code_start|> def get_queryset(self):
if self.request.user.is_authenticated():
return Player.objects.filter(match__in=Match.share.available(self.request.user))
else:
return Player.objects.filter(match__in=Match.share.public())
class MatchView(DetailView):
queryset = Match.share.all().select_related('playerresult', 'playerresult__player', 'message')
def get_queryset(self):
if self.request.user.is_authenticated():
return Match.share.available(self.request.user).select_related('playerresult', 'playerresult__player', 'message')
else:
return Match.share.public().select_related('playerresult', 'playerresult__player', 'message')
class MatchList(ListView):
queryset = Match.share.all()
def get_queryset(self):
if self.request.user.is_authenticated():
return Match.share.available(self.request.user)
else:
return Match.share.public()
class MatchUpload(CreateView):
success_url = '/sc2/match/upload/'
form_class = MatchUploadForm
template_name = 'sc2match/upload.html'
queryset = Match.objects.all()
<|code_end|>
. Write the next line using the current file imports:
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView
from django.http import HttpResponse
from .models import Match, Player
from .forms import MatchUploadForm
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from sc2reader.events import *
import json
and context from other files:
# Path: replayswithfriends/sc2match/models.py
# class Match(models.Model):
# owner = models.ForeignKey(User)
# created = models.DateTimeField(default=timezone.now, editable=False)
# modified = models.DateTimeField(editable=False)
# replay_file = models.FileField(upload_to=generate_filename, storage=storage_engine)
# mapfield = models.ForeignKey(Map, null=True, editable=False)
# duration = models.PositiveIntegerField(null=True, editable=False)
# gateway = models.CharField(max_length=32, default="us")
# processed = models.NullBooleanField(default=None)
# process_error = models.TextField(blank=True, default='', editable=False)
# match_share = models.PositiveSmallIntegerField(choices=SHARE, default=SHARE.FRIENDS)
# matchhash = models.CharField(max_length=512, editable=False, blank=True, default='')
# is_ladder = models.BooleanField(default=True)
# game_played_on = models.DateTimeField(null=True, blank=True)
# game_type = models.CharField(max_length=64, blank=True, default=True)
# game_speed = models.CharField(max_length=64, blank=True, default=True)
# events_json = models.TextField(editable=False, blank=True)
#
# objects = models.Manager()
# share = ShareManager()
# processing = ProcessedManager()
#
# def __init__(self, *args, **kwargs):
# self._replay = None
# super(Match, self).__init__(*args, **kwargs)
#
# def __unicode__(self):
# if self.processed:
# return "%s" % ", ".join(self.players.all().values_list('nick', flat=True).order_by("nick"))
# else:
# return "unprocessed match %s" % self.created
#
# def process_now(self):
# from .tasks import parse_replay
# parse_replay(self.id)
#
# @models.permalink
# def get_absolute_url(self):
# return ('match_detail', [self.id])
#
# @property
# def replay(self):
# if not self._replay:
# self._replay = sc2reader.load_replay(self.replay_file.file, load_map=False)
# return self._replay
#
# @property
# def time_display(self):
# if self.duration:
# minutes = self.duration / 60
# seconds = self.duration % 60
# return '%d:%02d' % (minutes, seconds)
# else:
# return '-'
#
# def make_hash(self, block_size=2**8):
# md5 = hashlib.md5()
# while True:
# data = self.replay_file.read(block_size)
# if not data:
# break
# md5.update(data)
# data = self.replay_file.seek(0)
# self.matchhash = md5.hexdigest()
#
# @property
# def winners(self):
# return self.players.filter(result=True)
#
# @property
# def losers(self):
# return self.players.filter(result=False)
#
# def save(self, *args, **kwargs):
# self.modified = timezone.now()
# if not self.matchhash:
# self.make_hash()
# super(Match, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ['-game_played_on', '-modified']
# unique_together = ['owner', 'matchhash']
#
# class Player(models.Model):
# user = models.ForeignKey(User, null=True)
# username = models.CharField(max_length=64)
# battle_net_url = models.URLField(help_text="Go to http://us.battle.net/sc2/en/ and click on your avatar to go to your profile URL", blank=True)
# region = models.PositiveSmallIntegerField(choices=REGIONS, default=REGIONS.NA)
#
# def __unicode__(self):
# return self.username
#
# class Meta:
# unique_together = ['username', 'battle_net_url']
#
# Path: replayswithfriends/sc2match/forms.py
# class MatchUploadForm(ModelForm):
#
# def __init__(self, *args, **kwargs):
# self.user = kwargs.pop('user', None)
# super(MatchUploadForm, self).__init__(*args, **kwargs)
#
# def save(self, *args, **kwargs):
# commit = kwargs.get('commit', True)
# match = super(MatchUploadForm, self).save(commit=False)
# match.owner = self.user
# if commit:
# match.save()
# print "werp"
# return match
#
# class Meta:
# model = Match
# fields = ['replay_file']
, which may include functions, classes, or code. Output only the next line. | def get_form_kwargs(self): |
Given snippet: <|code_start|>
class PlayerDetail(DetailView):
queryset = Player.objects.all()
slug_field = 'username'
slug_url_kwarg = 'username'
def get_queryset(self):
if self.request.user.is_authenticated():
return Player.objects.filter(match__in=Match.share.available(self.request.user))
else:
return Player.objects.filter(match__in=Match.share.public())
class PlayerList(ListView):
queryset = Player.objects.all()
def get_queryset(self):
if self.request.user.is_authenticated():
return Player.objects.filter(match__in=Match.share.available(self.request.user))
else:
return Player.objects.filter(match__in=Match.share.public())
class MatchView(DetailView):
queryset = Match.share.all().select_related('playerresult', 'playerresult__player', 'message')
def get_queryset(self):
if self.request.user.is_authenticated():
return Match.share.available(self.request.user).select_related('playerresult', 'playerresult__player', 'message')
else:
return Match.share.public().select_related('playerresult', 'playerresult__player', 'message')
class MatchList(ListView):
queryset = Match.share.all()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView
from django.http import HttpResponse
from .models import Match, Player
from .forms import MatchUploadForm
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from sc2reader.events import *
import json
and context:
# Path: replayswithfriends/sc2match/models.py
# class Match(models.Model):
# owner = models.ForeignKey(User)
# created = models.DateTimeField(default=timezone.now, editable=False)
# modified = models.DateTimeField(editable=False)
# replay_file = models.FileField(upload_to=generate_filename, storage=storage_engine)
# mapfield = models.ForeignKey(Map, null=True, editable=False)
# duration = models.PositiveIntegerField(null=True, editable=False)
# gateway = models.CharField(max_length=32, default="us")
# processed = models.NullBooleanField(default=None)
# process_error = models.TextField(blank=True, default='', editable=False)
# match_share = models.PositiveSmallIntegerField(choices=SHARE, default=SHARE.FRIENDS)
# matchhash = models.CharField(max_length=512, editable=False, blank=True, default='')
# is_ladder = models.BooleanField(default=True)
# game_played_on = models.DateTimeField(null=True, blank=True)
# game_type = models.CharField(max_length=64, blank=True, default=True)
# game_speed = models.CharField(max_length=64, blank=True, default=True)
# events_json = models.TextField(editable=False, blank=True)
#
# objects = models.Manager()
# share = ShareManager()
# processing = ProcessedManager()
#
# def __init__(self, *args, **kwargs):
# self._replay = None
# super(Match, self).__init__(*args, **kwargs)
#
# def __unicode__(self):
# if self.processed:
# return "%s" % ", ".join(self.players.all().values_list('nick', flat=True).order_by("nick"))
# else:
# return "unprocessed match %s" % self.created
#
# def process_now(self):
# from .tasks import parse_replay
# parse_replay(self.id)
#
# @models.permalink
# def get_absolute_url(self):
# return ('match_detail', [self.id])
#
# @property
# def replay(self):
# if not self._replay:
# self._replay = sc2reader.load_replay(self.replay_file.file, load_map=False)
# return self._replay
#
# @property
# def time_display(self):
# if self.duration:
# minutes = self.duration / 60
# seconds = self.duration % 60
# return '%d:%02d' % (minutes, seconds)
# else:
# return '-'
#
# def make_hash(self, block_size=2**8):
# md5 = hashlib.md5()
# while True:
# data = self.replay_file.read(block_size)
# if not data:
# break
# md5.update(data)
# data = self.replay_file.seek(0)
# self.matchhash = md5.hexdigest()
#
# @property
# def winners(self):
# return self.players.filter(result=True)
#
# @property
# def losers(self):
# return self.players.filter(result=False)
#
# def save(self, *args, **kwargs):
# self.modified = timezone.now()
# if not self.matchhash:
# self.make_hash()
# super(Match, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ['-game_played_on', '-modified']
# unique_together = ['owner', 'matchhash']
#
# class Player(models.Model):
# user = models.ForeignKey(User, null=True)
# username = models.CharField(max_length=64)
# battle_net_url = models.URLField(help_text="Go to http://us.battle.net/sc2/en/ and click on your avatar to go to your profile URL", blank=True)
# region = models.PositiveSmallIntegerField(choices=REGIONS, default=REGIONS.NA)
#
# def __unicode__(self):
# return self.username
#
# class Meta:
# unique_together = ['username', 'battle_net_url']
#
# Path: replayswithfriends/sc2match/forms.py
# class MatchUploadForm(ModelForm):
#
# def __init__(self, *args, **kwargs):
# self.user = kwargs.pop('user', None)
# super(MatchUploadForm, self).__init__(*args, **kwargs)
#
# def save(self, *args, **kwargs):
# commit = kwargs.get('commit', True)
# match = super(MatchUploadForm, self).save(commit=False)
# match.owner = self.user
# if commit:
# match.save()
# print "werp"
# return match
#
# class Meta:
# model = Match
# fields = ['replay_file']
which might include code, classes, or functions. Output only the next line. | def get_queryset(self): |
Using the snippet: <|code_start|>
class MatchUploadForm(ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(MatchUploadForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
commit = kwargs.get('commit', True)
match = super(MatchUploadForm, self).save(commit=False)
match.owner = self.user
<|code_end|>
, determine the next line of code. You have imports:
from django.forms import ModelForm
from .models import Match
and context (class names, function names, or code) available:
# Path: replayswithfriends/sc2match/models.py
# class Match(models.Model):
# owner = models.ForeignKey(User)
# created = models.DateTimeField(default=timezone.now, editable=False)
# modified = models.DateTimeField(editable=False)
# replay_file = models.FileField(upload_to=generate_filename, storage=storage_engine)
# mapfield = models.ForeignKey(Map, null=True, editable=False)
# duration = models.PositiveIntegerField(null=True, editable=False)
# gateway = models.CharField(max_length=32, default="us")
# processed = models.NullBooleanField(default=None)
# process_error = models.TextField(blank=True, default='', editable=False)
# match_share = models.PositiveSmallIntegerField(choices=SHARE, default=SHARE.FRIENDS)
# matchhash = models.CharField(max_length=512, editable=False, blank=True, default='')
# is_ladder = models.BooleanField(default=True)
# game_played_on = models.DateTimeField(null=True, blank=True)
# game_type = models.CharField(max_length=64, blank=True, default=True)
# game_speed = models.CharField(max_length=64, blank=True, default=True)
# events_json = models.TextField(editable=False, blank=True)
#
# objects = models.Manager()
# share = ShareManager()
# processing = ProcessedManager()
#
# def __init__(self, *args, **kwargs):
# self._replay = None
# super(Match, self).__init__(*args, **kwargs)
#
# def __unicode__(self):
# if self.processed:
# return "%s" % ", ".join(self.players.all().values_list('nick', flat=True).order_by("nick"))
# else:
# return "unprocessed match %s" % self.created
#
# def process_now(self):
# from .tasks import parse_replay
# parse_replay(self.id)
#
# @models.permalink
# def get_absolute_url(self):
# return ('match_detail', [self.id])
#
# @property
# def replay(self):
# if not self._replay:
# self._replay = sc2reader.load_replay(self.replay_file.file, load_map=False)
# return self._replay
#
# @property
# def time_display(self):
# if self.duration:
# minutes = self.duration / 60
# seconds = self.duration % 60
# return '%d:%02d' % (minutes, seconds)
# else:
# return '-'
#
# def make_hash(self, block_size=2**8):
# md5 = hashlib.md5()
# while True:
# data = self.replay_file.read(block_size)
# if not data:
# break
# md5.update(data)
# data = self.replay_file.seek(0)
# self.matchhash = md5.hexdigest()
#
# @property
# def winners(self):
# return self.players.filter(result=True)
#
# @property
# def losers(self):
# return self.players.filter(result=False)
#
# def save(self, *args, **kwargs):
# self.modified = timezone.now()
# if not self.matchhash:
# self.make_hash()
# super(Match, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ['-game_played_on', '-modified']
# unique_together = ['owner', 'matchhash']
. Output only the next line. | if commit: |
Based on the snippet: <|code_start|>
# assign the cartrographer's CCD to this one
self.camera.cartographer.ccd = self.ccd
# create coordinate object for the stars
stars = self.camera.cartographer.point(ras, decs, 'celestial')
x, y = stars.ccdxy.tuple
# start with targets with centers on the chip
onccd = (np.round(x) > 0) & \
(np.round(x) < self.ccd.xsize) & \
(np.round(y) > 0) & \
(np.round(y) < self.ccd.ysize)
# weight stars inversely to their abundance, to give roughly uniform distribution of magnitudes
weights = \
(1.0 / dndmag(self.camera.catalog.tmag) * (self.camera.catalog.tmag >= 6) * (
self.camera.catalog.tmag <= 16))[
onccd]
weights /= np.sum(weights)
itargets = np.random.choice(onccd.nonzero()[0],
size=np.minimum(nstamps, np.sum(weights != 0)),
replace=False,
p=weights)
# populate position arrays
self.ra = self.camera.catalog.ra[itargets]
self.dec = self.camera.catalog.dec[itargets]
self.radii = np.ones_like(self.ra) * radius
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import Catalogs
import numpy as np
import astropy
import logging
from settings import log_file_handler
and context (classes, functions, sometimes code) from other files:
# Path: settings.py
# def initialize():
. Output only the next line. | self.finishFromStars() |
Using the snippet: <|code_start|> if extreme:
p = [0.1, 30.0]
d = [0.1, 1]
else:
p = [0.1, 30.0]
d = [0.0001, 0.01]
P = 10 ** prng.uniform(*np.log10(p))
E = prng.uniform(0, P)
mass = prng.uniform(0.1, 1.5)
radius = mass
stellar_density = 3 * mass * u.Msun / (4 * np.pi * (radius * u.Rsun) ** 3)
rsovera = (3 * np.pi / u.G / (P * u.day) ** 2 / stellar_density) ** (1.0 / 3.0)
T14 = rsovera * P / np.pi
# noinspection PyTypeChecker
T23 = prng.uniform(0, T14)
D = 10 ** prng.uniform(*np.log10(d))
# noinspection PyTypeChecker
return Trapezoid(P=P, E=E, D=D, T23=T23, T14=T14)
class LightCurve(object):
"""The LightCurve class defines the basics of a light curve object, which can
injected into TESS simulations. It handles basic functionality, like
(importantly), integrating a light curve over a finite exposure time."""
def __init__(self):
super(LightCurve, self).__init__()
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import matplotlib.pyplot as plt
import zachopy.units as u
import logging
import astropy.io.ascii as ascii
import pkgutil
import astropy.io.ascii as ascii
import pkgutil
from settings import log_file_handler
and context (class names, function names, or code) available:
# Path: settings.py
# def initialize():
. Output only the next line. | def demo(self, tmin=0, tmax=27.4, cadence=30.0 / 60.0 / 24.0, offset=0, raw=False, ax=None): |
Based on the snippet: <|code_start|> pmdec[np.isfinite(pmdec) == False] = 0.0
ok = np.isfinite(imag)
if faintlimit is not None:
ok *= imag <= faintlimit
logger.info("found {0} stars with {1} < V < {2}".format(np.sum(ok), np.min(rmag[ok]), np.max(rmag[ok])))
self.ra = ras[ok]
self.dec = decs[ok]
self.pmra = pmra[ok]
self.pmdec = pmdec[ok]
self.tmag = imag[ok]
self.temperature = temperatures[ok]
self.epoch = 2000.0
class Trimmed(Catalog):
"""a trimmed catalog, created by removing elements from another catalog"""
def __init__(self, inputcatalog, keep):
"""inputcatalog = the catalog to start with
keep = an array indices indicating which elements of inputcatalog to use"""
Catalog.__init__(self)
# define the keys to propagate from old catalog to the new one
keystotransfer = ['ra', 'dec', 'pmra', 'pmdec', 'tmag', 'temperature', 'lightcurves']
for k in keystotransfer:
self.__dict__[k] = inputcatalog.__dict__[k][keep]
<|code_end|>
, predict the immediate next line with the help of imports:
import os.path
import logging
import matplotlib.animation
import zachopy.star
import astropy.coordinates
import astropy.units
import zachopy.utils
import numpy as np
import matplotlib.pylab as plt
import settings
import relations
import Lightcurve
from astroquery.vizier import Vizier
from settings import log_file_handler
and context (classes, functions, sometimes code) from other files:
# Path: settings.py
# def initialize():
. Output only the next line. | self.epoch = inputcatalog.epoch |
Here is a snippet: <|code_start|>
# define a filename for this magnitude range
self.note = 'starsbrighterthan{0:02d}'.format(magnitudethreshold)
starsfilename = os.path.join(self.directory, self.note + '.fits')
# load the existing stellar image, if possible
try:
assert (remake == False)
self.starimage = self.loadFromFITS(starsfilename)
except (IOError, AssertionError):
# if this is the smallest threshold, include all the stars brighter than it
# if threshold == np.min(magnitude_thresholds):
minimum = -100
# else:
# minimum = threshold - dthreshold
# pick the stars to add to the image on this pass through
ok = (self.starx + self.camera.psf.dx_pixels_axis[-1] >= self.xmin) * \
(self.starx + self.camera.psf.dx_pixels_axis[0] <= self.xmax) * \
(self.stary + self.camera.psf.dy_pixels_axis[-1] >= self.ymin) * \
(self.stary + self.camera.psf.dy_pixels_axis[0] <= self.ymax) * \
(self.starmag < magnitudethreshold) * (self.starmag >= minimum)
x = self.starx[ok]
y = self.stary[ok]
mag = self.starmag[ok]
temp = self.startemp[ok]
logger.info('adding {0} stars between {1:.1f} and {2:.1f} magnitudes'.format(
len(x), np.min(mag), np.max(mag)))
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import zachopy.utils
import astropy.io.fits
import scipy.ndimage.measurements
import os
import matplotlib.pylab as plt
import matplotlib.gridspec as gridspec
import Cosmics
import Stamper
import logging
from settings import log_file_handler
from zachopy.displays.ds9 import ds9
and context from other files:
# Path: settings.py
# def initialize():
, which may include functions, classes, or code. Output only the next line. | self.currentfocus = self.camera.focus.model(self.camera.counter) |
Using the snippet: <|code_start|>"""Calculate the expected photometric precision for TESS.
(translated from Josh Winn's IDL TESS signal-to-noise calculator
on the TESS wiki and updated to include calculations
published with Peter Sullivan's simulation paper)."""
logger = logging.getLogger(__name__)
logger.addHandler(log_file_handler)
# create a cartographer for managing conversions between ecliptic and galactic coordinates
carto = Cartographer.Cartographer()
# create an interpolator to estimate the best number of pixels in a photometric aperture
<|code_end|>
, determine the next line of code. You have imports:
import pkgutil
import numpy as np
import matplotlib.pyplot as plt
import astropy.io.ascii
import scipy.interpolate
import logging
import Cartographer
from settings import log_file_handler
and context (class names, function names, or code) available:
# Path: settings.py
# def initialize():
. Output only the next line. | optimalpixelsdata = astropy.io.ascii.read(pkgutil.get_data(__name__, 'relations/optimalnumberofpixels.txt')) |
Predict the next line for this snippet: <|code_start|> ax.plot(time, what, **kw)
ax.set_ylabel(['dRA (arcsec)', 'dDec (arcsec)'][i])
if i == 0:
ax.set_title('Jitter Timeseries from\n{}'.format(self.basename))
plt.xlabel('Time from Observation Start (days)')
plt.xlim(np.min(time), np.max(time))
plt.draw()
plt.savefig(outfile.replace('.txt', '.pdf'))
data = [counters, bjds, self.x, self.y]
names = ['imagenumber', 'bjd', 'arcsecnudge_ra', 'arcsecnudge_dec']
t = astropy.table.Table(data=data, names=names)
t.write(outfile.replace('.txt', '_amplifiedby{}.txt'.format(self.amplifyinterexposurejitter)),
format='ascii.fixed_width', delimiter=' ')
logger.info("save jitter nudge timeseries to {0}".format(outfile))
def applyNudge(self,
counter=None, # which row to use from jitterball?
dx=None, dy=None, # custom nudges, in arcsec
header=None, # the FITS header in which to record nudges
):
"""jitter the camera by a little bit,
by introducing nudges draw from a
(cadence-appropriate) jitterball timeseries."""
# make sure the jitterball has been populated
self.load()
<|code_end|>
with the help of current file imports:
import settings
import numpy as np
import astropy.table
import os.path
import zachopy.utils
import matplotlib.pylab as plt
import scipy.interpolate
import logging
import matplotlib.gridspec as gridspec
from settings import log_file_handler
and context from other files:
# Path: settings.py
# def initialize():
, which may contain function names, class names, or code. Output only the next line. | n = len(self.x) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger(__name__)
logger.addHandler(log_file_handler)
class Cartographer(object):
"""An object to handle all conversions between coordinate systems."""
def __init__(self, camera=None, ccd=None):
"""Initialize Cartographer, telling it where it is and how to act."""
# These will be necessary for more complicated conversions
self.camera, self.ccd = None, None
self.setCamera(camera)
self.setCCD(ccd)
def updatePossibilities(self):
"""Update which kinds of cartographic coordinates are valid.
Should be run every time camera or ccd are updated."""
# no matter what, Cartographer should be able to deal with these
possibilities = ['focalxy', 'focalrtheta']
# if possible, figure out how to convert between focal plane coordinates and the sky
if self.camera is not None:
<|code_end|>
with the help of current file imports:
import numpy as np
import astropy.coordinates
import zachopy.borrowed.crossfield as crossfield
import logging
from settings import log_file_handler
and context from other files:
# Path: settings.py
# def initialize():
, which may contain function names, class names, or code. Output only the next line. | possibilities.extend(['celestial', 'ecliptic', 'galactic']) |
Continue the code snippet: <|code_start|># Copyright (c) 2011-2014, Alexander Todorov <atodorov@nospam.dif.io>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
try:
FQDN = settings.FQDN
except:
FQDN=""
try:
RUBYGEMS_API_KEY = settings.RUBYGEMS_API_KEY
except:
RUBYGEMS_API_KEY = False
# legacy table names
<|code_end|>
. Use current file imports:
import cpan
import pypi
import pear
import pear2
import nodejs
import github
import rubygems
import packagist
import mavencentral
import os
import sys
import bugs
import utils
from django.db import models
from datetime import datetime
from django.conf import settings
from utils import URL_ADVISORIES
from django.db.models import Manager
from django.contrib.auth.models import User
from managers import SkinnyManager
and context (classes, functions, or code) from other files:
# Path: utils.py
# URL_ADVISORIES = 'updates'
#
# Path: managers.py
# class SkinnyManager(Manager):
# def get_query_set(self):
# return SkinnyQuerySet(self.model, using=self._db)
. Output only the next line. | try: |
Continue the code snippet: <|code_start|>
# used in Django Admin and in
# application dashboard
VENDOR_TYPES = (
(VENDOR_OPENSHIFT_EXPRESS, 'OpenShift'),
(VENDOR_DOTCLOUD, 'dotCloud'),
(VENDOR_HEROKU, 'Heroku'),
(VENDOR_CLOUDCONTROL, 'cloudControl'),
(VENDOR_APPFOG, 'AppFog'),
(VENDOR_VIRTUALENV, 'virtualenv'),
(VENDOR_MANUAL_IMPORT, 'Manual import'),
)
APP_STATUS_REMOVED=-10
APP_STATUS_IMPORTING=-5
APP_STATUS_PENDING=0
# NB: Always keep working states > 0
# since the UI hard codes this
APP_STATUS_SUSPENDED=5
APP_STATUS_APPROVED=10
APP_STATUS_UPTODATE=20
APP_STATUS_NEEDSUPDATE=30
STATUS_TYPES = (
(APP_STATUS_REMOVED, 'Removed'),
(APP_STATUS_IMPORTING, 'Importing'),
(APP_STATUS_PENDING, 'Pending'),
(APP_STATUS_SUSPENDED, 'Suspended'),
(APP_STATUS_APPROVED, 'Approved'),
<|code_end|>
. Use current file imports:
import cpan
import pypi
import pear
import pear2
import nodejs
import github
import rubygems
import packagist
import mavencentral
import os
import sys
import bugs
import utils
from django.db import models
from datetime import datetime
from django.conf import settings
from utils import URL_ADVISORIES
from django.db.models import Manager
from django.contrib.auth.models import User
from managers import SkinnyManager
and context (classes, functions, or code) from other files:
# Path: utils.py
# URL_ADVISORIES = 'updates'
#
# Path: managers.py
# class SkinnyManager(Manager):
# def get_query_set(self):
# return SkinnyQuerySet(self.model, using=self._db)
. Output only the next line. | (APP_STATUS_UPTODATE, 'Up to date'), |
Here is a snippet: <|code_start|>#
# Copyright (c) 2011-2014, Alexander Todorov <atodorov@nospam.dif.io>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
logger = logging.getLogger(__name__)
URL_ADVISORIES = 'updates'
VIEW_PAGINATOR = 100
TAG_NOT_FOUND="TAG-NOT-FOUND"
INFO_NOT_AVAILABLE="We're sorry! This information is not available."
MYSQL_MAX_PACKET_SIZE = 3*1024*1024 # 3 MB. The actual is 5 MB but we need some more room for additional messages
INFO_DATA_TOO_BIG = """
We're sorry! This data is too big to be displayed in a browser.
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import tar
import json
import shutil
import urllib
import httplib
import logging
import tempfile
import grabber
from bugs import BUG_TYPE_UNKNOWN
from xml.dom.minidom import parse
from htmlmin.minify import html_minify
from BeautifulSoup import BeautifulSoup
from datetime import datetime, timedelta
from github import get_files as github_get_files
from metacpan import get_files as metacpan_get_files
from bitbucket import get_files as bitbucket_get_files
from django.contrib.messages import constants as message_levels
from models import STATUS_VERIFIED, STATUS_ASSIGNED
from django.contrib.messages import constants as message_levels
from difio import grabber
from django.contrib import messages
from difio.models import Bug
from difio.models import Advisory
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.models import AnonymousUser
and context from other files:
# Path: bugs.py
# BUG_TYPE_UNKNOWN = -1
, which may include functions, classes, or code. Output only the next line. | Below you can see a truncated part of it. If you still need everything |
Using the snippet: <|code_start|># Copyright (c) 2011-2012, Alexander Todorov <atodorov@nospam.dif.io>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
logger = logging.getLogger(__name__)
_twisted_mappings = {
'Twisted-Conch' : 'Twisted Conch',
'Twisted-Core' : 'Twisted Core',
'Twisted-Lore' : 'Twisted Lore',
'Twisted-Mail' : 'Twisted Mail',
'Twisted-Names' : 'Twisted Names',
'Twisted-News' : 'Twisted News',
'Twisted-Pair' : 'Twisted Pair',
'Twisted-Runner' : 'Twisted Runner',
'Twisted-Web' : 'Twisted Web',
<|code_end|>
, determine the next line of code. You have imports:
import json
import logging
from datetime import datetime
from xml.dom.minidom import parseString
from pip.commands.search import highest_version
from utils import fetch_page, SUPPORTED_ARCHIVES
from pip.commands.search import compare_versions as pypi_compare_versions
from pprint import pprint
and context (class names, function names, or code) available:
# Path: utils.py
# def fetch_page(url, decode=True, last_modified=None, extra_headers={}, method='GET', body=None):
# """
# @url - URL of resource to fetch
# @decode - if True will try to decode as UTF8
# @last_modified - datetime - if specified will try a conditional GET
# @extra_headers - dict - headers to pass to the server
# @method - string - HTTP verb
# @body - string - HTTP request body if available. Used for POST/PUT
#
# @return - string - the contents from this URL. If None then we probably hit 304 Not Modified
# """
#
# (proto, host_path) = url.split('//')
# (host_port, path) = host_path.split('/', 1)
# path = '/' + path
#
# if url.startswith('https'):
# conn = httplib.HTTPSConnection(host_port)
# else:
# conn = httplib.HTTPConnection(host_port)
#
# # some servers, notably logilab.org returns 404 if not a browser
# # GitHub also requires a valid UA string
# headers = {
# 'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0.5) Gecko/20120601 Firefox/10.0.5',
# }
#
# # workaround for https://code.google.com/p/support/issues/detail?id=660
# real_method = method
# if (method == "HEAD") and ((url.find('googlecode.com') > -1) or (url.find('search.maven.org') > -1)):
# real_method = "GET"
# headers['Range'] = 'bytes=0-9'
#
# # add additional headers
# for h in extra_headers.keys():
# headers[h] = extra_headers[h]
#
# if last_modified:
# # If-Modified-Since: Thu, 28 Jun 2012 12:02:45 GMT
# headers['If-Modified-Since'] = last_modified.strftime('%a, %d %b %Y %H:%M:%S GMT')
#
# # print "DEBUG fetch_page - before send", method, path, headers
#
# conn.request(real_method, path, body=body, headers=headers)
# response = conn.getresponse()
#
# # print "DEBUG fetch_page - after send", response.getheaders(), response.status
#
# if (response.status == 404):
# raise Exception("404 - %s not found" % url)
#
# if response.status in [301, 302]:
# location = response.getheader('Location')
# logger.info("URL Redirect %d from %s to %s" % (response.status, url, location))
# return fetch_page(location, decode, last_modified, extra_headers, method)
#
# # not modified
# if response.status == 304:
# print "DEBUG: 304 %s" % url
# return None
#
# if (method == "HEAD"):
# if response.status == 200:
# return response.getheader('Content-Length')
# elif response.status == 206: # partial content
# return response.getheader('Content-Range').strip().split(' ')[1].split('/')[1]
#
#
# if decode:
# return response.read().decode('UTF-8', 'replace')
# else:
# return response.read()
#
# SUPPORTED_ARCHIVES = ['.tar.gz', 'tgz', '.tar.bz2', 'tbz2', '.zip', '.jar', '.gem']
. Output only the next line. | 'Twisted-Words' : 'Twisted Words', |
Continue the code snippet: <|code_start|>#
# Copyright (c) 2011-2012, Alexander Todorov <atodorov@nospam.dif.io>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
logger = logging.getLogger(__name__)
_twisted_mappings = {
'Twisted-Conch' : 'Twisted Conch',
'Twisted-Core' : 'Twisted Core',
'Twisted-Lore' : 'Twisted Lore',
'Twisted-Mail' : 'Twisted Mail',
'Twisted-Names' : 'Twisted Names',
'Twisted-News' : 'Twisted News',
'Twisted-Pair' : 'Twisted Pair',
'Twisted-Runner' : 'Twisted Runner',
<|code_end|>
. Use current file imports:
import json
import logging
from datetime import datetime
from xml.dom.minidom import parseString
from pip.commands.search import highest_version
from utils import fetch_page, SUPPORTED_ARCHIVES
from pip.commands.search import compare_versions as pypi_compare_versions
from pprint import pprint
and context (classes, functions, or code) from other files:
# Path: utils.py
# def fetch_page(url, decode=True, last_modified=None, extra_headers={}, method='GET', body=None):
# """
# @url - URL of resource to fetch
# @decode - if True will try to decode as UTF8
# @last_modified - datetime - if specified will try a conditional GET
# @extra_headers - dict - headers to pass to the server
# @method - string - HTTP verb
# @body - string - HTTP request body if available. Used for POST/PUT
#
# @return - string - the contents from this URL. If None then we probably hit 304 Not Modified
# """
#
# (proto, host_path) = url.split('//')
# (host_port, path) = host_path.split('/', 1)
# path = '/' + path
#
# if url.startswith('https'):
# conn = httplib.HTTPSConnection(host_port)
# else:
# conn = httplib.HTTPConnection(host_port)
#
# # some servers, notably logilab.org returns 404 if not a browser
# # GitHub also requires a valid UA string
# headers = {
# 'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0.5) Gecko/20120601 Firefox/10.0.5',
# }
#
# # workaround for https://code.google.com/p/support/issues/detail?id=660
# real_method = method
# if (method == "HEAD") and ((url.find('googlecode.com') > -1) or (url.find('search.maven.org') > -1)):
# real_method = "GET"
# headers['Range'] = 'bytes=0-9'
#
# # add additional headers
# for h in extra_headers.keys():
# headers[h] = extra_headers[h]
#
# if last_modified:
# # If-Modified-Since: Thu, 28 Jun 2012 12:02:45 GMT
# headers['If-Modified-Since'] = last_modified.strftime('%a, %d %b %Y %H:%M:%S GMT')
#
# # print "DEBUG fetch_page - before send", method, path, headers
#
# conn.request(real_method, path, body=body, headers=headers)
# response = conn.getresponse()
#
# # print "DEBUG fetch_page - after send", response.getheaders(), response.status
#
# if (response.status == 404):
# raise Exception("404 - %s not found" % url)
#
# if response.status in [301, 302]:
# location = response.getheader('Location')
# logger.info("URL Redirect %d from %s to %s" % (response.status, url, location))
# return fetch_page(location, decode, last_modified, extra_headers, method)
#
# # not modified
# if response.status == 304:
# print "DEBUG: 304 %s" % url
# return None
#
# if (method == "HEAD"):
# if response.status == 200:
# return response.getheader('Content-Length')
# elif response.status == 206: # partial content
# return response.getheader('Content-Range').strip().split(' ')[1].split('/')[1]
#
#
# if decode:
# return response.read().decode('UTF-8', 'replace')
# else:
# return response.read()
#
# SUPPORTED_ARCHIVES = ['.tar.gz', 'tgz', '.tar.bz2', 'tbz2', '.zip', '.jar', '.gem']
. Output only the next line. | 'Twisted-Web' : 'Twisted Web', |
Predict the next line for this snippet: <|code_start|> if request.user.has_perm('difio.packageversion_modify_all'):
return super(PackageVersionAdmin, self).get_fieldsets(request, obj)
else:
return [
(None, {
'fields': ( ('package_status'),
('released_on', 'scmid', 'download_url', 'download_link'),
'github_iframe',
)
}
),
]
search_fields = ['package__name', 'version', 'scmid']
save_on_top = True
def name_version(self, obj):
return "%s-%s" % (obj.package, obj.version)
name_version.short_description = 'Name-Version'
name_version.admin_order_field = 'package__name'
def package_status(self, obj):
url = reverse('admin:%s_%s_change' %(obj.package._meta.app_label, obj.package._meta.module_name), args=[obj.package_id])
text = """
<strong>%s</strong>
%s-%s,
<a href='%s'>%s - <strong>%s</strong></a>,
<strong>%s</strong> bytes,
ASSIGNED TO %s""" % (obj.get_status_display(), obj.package.name,
obj.version, url, obj.package.get_type_display(),
<|code_end|>
with the help of current file imports:
import re
import sys
import bugs
import utils
import difio.tasks
from models import *
from django.contrib import admin
from django.contrib import messages
from django.shortcuts import render
from buttons import ButtonableModelAdmin
from datetime import datetime, timedelta
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.core.files.base import ContentFile
from django.contrib.admin import SimpleListFilter
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.models import AnonymousUser
from github import _get_user_repo as github_get_user_repo
from django.contrib.messages import constants as message_levels
and context from other files:
# Path: buttons.py
# class ButtonableModelAdmin(admin.ModelAdmin):
# """
# A subclass of this admin will let you add buttons (like history) in the
# change view of an entry.
# """
# buttons = []
#
# def change_view(self, request, object_id, form_url='', extra_context=None):
# if not extra_context:
# extra_context = {'buttons' : []}
#
# for b in self.buttons:
# extra_context['buttons'].append({'name' : b.short_description, 'url' : b.func_name})
#
# return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
#
# def get_urls(self):
# urls = super(ButtonableModelAdmin, self).get_urls()
#
# my_urls = patterns('',)
# for b in self.buttons:
# my_urls += patterns('',
# url(r'^(?P<id>\d+)/%s/$' % b.func_name, self.admin_site.admin_view(b))
# )
#
# return my_urls + urls
#
# def __call__(self, request, url):
# if url is not None:
# res=re.match('(.*/)?(?P<id>\d+)/(?P<command>.*)/', url)
# if res:
# if res.group('command') in [b.func_name for b in self.buttons]:
# obj = self.model._default_manager.get(pk=res.group('id'))
# getattr(self, res.group('command'))(obj)
# return HttpResponseRedirect(request.META['HTTP_REFERER'])
#
# return super(ButtonableModelAdmin, self).__call__(request, url)
#
# Path: github.py
# def _get_user_repo(url):
# """
# Return the :user/:repo/ from a github.com url
# """
# if url.find('://github.com/') > -1: # toplevel GitHub page
# p = url.split('/')
# return '%s/%s' % (p[3], p[4].replace('.git', ''))
# elif url.find('.github.com/') > -1: # GitHub project pages
# p = url.split('/')
# u = p[2].split('.')[0]
# return '%s/%s' % (u, p[3])
#
# return None
, which may contain function names, class names, or code. Output only the next line. | obj.package.get_status_display(), obj.size, |
Using the snippet: <|code_start|> if request.user.has_perm('difio.packageversion_modify_all'):
return super(PackageVersionAdmin, self).get_fieldsets(request, obj)
else:
return [
(None, {
'fields': ( ('package_status'),
('released_on', 'scmid', 'download_url', 'download_link'),
'github_iframe',
)
}
),
]
search_fields = ['package__name', 'version', 'scmid']
save_on_top = True
def name_version(self, obj):
return "%s-%s" % (obj.package, obj.version)
name_version.short_description = 'Name-Version'
name_version.admin_order_field = 'package__name'
def package_status(self, obj):
url = reverse('admin:%s_%s_change' %(obj.package._meta.app_label, obj.package._meta.module_name), args=[obj.package_id])
text = """
<strong>%s</strong>
%s-%s,
<a href='%s'>%s - <strong>%s</strong></a>,
<strong>%s</strong> bytes,
ASSIGNED TO %s""" % (obj.get_status_display(), obj.package.name,
obj.version, url, obj.package.get_type_display(),
<|code_end|>
, determine the next line of code. You have imports:
import re
import sys
import bugs
import utils
import difio.tasks
from models import *
from django.contrib import admin
from django.contrib import messages
from django.shortcuts import render
from buttons import ButtonableModelAdmin
from datetime import datetime, timedelta
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.core.files.base import ContentFile
from django.contrib.admin import SimpleListFilter
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.models import AnonymousUser
from github import _get_user_repo as github_get_user_repo
from django.contrib.messages import constants as message_levels
and context (class names, function names, or code) available:
# Path: buttons.py
# class ButtonableModelAdmin(admin.ModelAdmin):
# """
# A subclass of this admin will let you add buttons (like history) in the
# change view of an entry.
# """
# buttons = []
#
# def change_view(self, request, object_id, form_url='', extra_context=None):
# if not extra_context:
# extra_context = {'buttons' : []}
#
# for b in self.buttons:
# extra_context['buttons'].append({'name' : b.short_description, 'url' : b.func_name})
#
# return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
#
# def get_urls(self):
# urls = super(ButtonableModelAdmin, self).get_urls()
#
# my_urls = patterns('',)
# for b in self.buttons:
# my_urls += patterns('',
# url(r'^(?P<id>\d+)/%s/$' % b.func_name, self.admin_site.admin_view(b))
# )
#
# return my_urls + urls
#
# def __call__(self, request, url):
# if url is not None:
# res=re.match('(.*/)?(?P<id>\d+)/(?P<command>.*)/', url)
# if res:
# if res.group('command') in [b.func_name for b in self.buttons]:
# obj = self.model._default_manager.get(pk=res.group('id'))
# getattr(self, res.group('command'))(obj)
# return HttpResponseRedirect(request.META['HTTP_REFERER'])
#
# return super(ButtonableModelAdmin, self).__call__(request, url)
#
# Path: github.py
# def _get_user_repo(url):
# """
# Return the :user/:repo/ from a github.com url
# """
# if url.find('://github.com/') > -1: # toplevel GitHub page
# p = url.split('/')
# return '%s/%s' % (p[3], p[4].replace('.git', ''))
# elif url.find('.github.com/') > -1: # GitHub project pages
# p = url.split('/')
# u = p[2].split('.')[0]
# return '%s/%s' % (u, p[3])
#
# return None
. Output only the next line. | obj.package.get_status_display(), obj.size, |
Given the code snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
admin.autodiscover()
URL_INDEX = ''
URL_SEARCH = 'search'
URL_ANALYTICS = 'analytics'
urlpatterns = patterns('',
url(r'^%s$' % URL_INDEX, 'difio.views.index', name='index'),
url(r'^%s/$' % URL_SEARCH, 'difio.views.search_results', name='search_results'),
url(r'^%s/$' % URL_ANALYTICS, 'difio.views.analytics', name='analytics'),
# /updates/django-1.3/django-1.3.1/245
url(r'^%s/(?P<old>.*)/(?P<new>.*)/(?P<id>\d+)/$' % URL_ADVISORIES, 'difio.views.advisory', name='advisory'),
url(r'^analytics/(?P<package>.*)/(?P<id>\d+)/$', 'difio.views.previous_analytics', name='previous_analytics'),
# AJAX API
url(r'^ajax/update/app/name/$', 'difio.views.ajax_update_app_name', name='ajax_update_app_name'),
url(r'^ajax/update/app/url/$', 'difio.views.ajax_update_app_url', name='ajax_update_app_url'),
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.conf.urls import patterns, include, url
from utils import URL_ADVISORIES
and context (functions, classes, or occasionally code) from other files:
# Path: utils.py
# URL_ADVISORIES = 'updates'
. Output only the next line. | url(r'^ajax/delete/InstalledPackage/$', 'difio.views.ajax_delete_inst_pkg', name='ajax_delete_inst_pkg'), |
Based on the snippet: <|code_start|> self.app.settings.save()
self.app.scene.save()
def populate_networking_clients_table(self):
clients = self.app.settings['networking']['clients']
self.tbl_networking_clients.setRowCount(len(clients))
for i, client in enumerate(clients):
item_host = QtWidgets.QTableWidgetItem(client["host"])
item_port = QtWidgets.QTableWidgetItem(str(client["port"]))
item_enabled = QtWidgets.QCheckBox()
item_ignore_dimming = QtWidgets.QCheckBox()
item_color_mode = QtWidgets.QComboBox()
for mode in color_modes.modes:
item_color_mode.addItem(mode)
item_color_mode.setCurrentIndex(color_modes.modes.index(client["color-mode"]))
if client["enabled"]:
item_enabled.setCheckState(QtCore.Qt.Checked)
if client.get("ignore-dimming", False):
item_ignore_dimming.setCheckState(QtCore.Qt.Checked)
item_protocol = QtWidgets.QComboBox()
for proto in PROTOCOLS:
item_protocol.addItem(proto)
item_protocol.setCurrentIndex(PROTOCOLS.index(client["protocol"]))
<|code_end|>
, predict the immediate next line with the help of imports:
from builtins import str
from builtins import range
from PyQt5 import QtCore, QtGui, QtWidgets
from ui.ui_dlg_settings import Ui_DlgSettings
from lib import color_modes
and context (classes, functions, sometimes code) from other files:
# Path: lib/color_modes.py
. Output only the next line. | self.tbl_networking_clients.setItem(i, 0, item_host) |
Next line prediction: <|code_start|> except yaml.YAMLError as yea:
ExceptionCollector.appendException(ValueError(yea))
else:
if tpl is None:
tpl = {}
return tpl
def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
class OrderedLoader(Loader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
return yaml.load(stream, OrderedLoader)
def simple_ordered_parse(tmpl_str):
try:
tpl = ordered_load(tmpl_str)
except yaml.YAMLError as yea:
ExceptionCollector.appendException(ValueError(yea))
else:
if tpl is None:
tpl = {}
<|code_end|>
. Use current file imports:
(import codecs
import urllib
import yaml
from collections import OrderedDict
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import URLException
from toscaparser.utils.gettextutils import _)
and context including class names, function names, or small code snippets from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class URLException(TOSCAException):
# msg_fmt = _('%(what)s')
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
. Output only the next line. | return tpl |
Given the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
if hasattr(yaml, 'CSafeLoader'):
yaml_loader = yaml.CSafeLoader
else:
yaml_loader = yaml.SafeLoader
def load_yaml(path, a_file=True):
f = None
try:
if a_file:
f = codecs.open(path, encoding='utf-8', errors='strict')
else:
f = urllib.request.urlopen(path)
contents = f.read()
<|code_end|>
, generate the next line using the imports in this file:
import codecs
import urllib
import yaml
from collections import OrderedDict
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import URLException
from toscaparser.utils.gettextutils import _
and context (functions, classes, or occasionally code) from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class URLException(TOSCAException):
# msg_fmt = _('%(what)s')
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
. Output only the next line. | f.close() |
Given snippet: <|code_start|>if hasattr(yaml, 'CSafeLoader'):
yaml_loader = yaml.CSafeLoader
else:
yaml_loader = yaml.SafeLoader
def load_yaml(path, a_file=True):
f = None
try:
if a_file:
f = codecs.open(path, encoding='utf-8', errors='strict')
else:
f = urllib.request.urlopen(path)
contents = f.read()
f.close()
return yaml.load(contents, Loader=yaml_loader)
except urllib.error.URLError as e:
if hasattr(e, 'reason'):
msg = (_('Failed to reach server "%(path)s". Reason is: '
'%(reason)s.')
% {'path': path, 'reason': e.reason})
ExceptionCollector.appendException(URLException(what=msg))
return
elif hasattr(e, 'code'):
msg = (_('The server "%(path)s" couldn\'t fulfill the request. '
'Error code: "%(code)s".')
% {'path': path, 'code': e.code})
ExceptionCollector.appendException(URLException(what=msg))
return
except Exception:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import codecs
import urllib
import yaml
from collections import OrderedDict
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import URLException
from toscaparser.utils.gettextutils import _
and context:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class URLException(TOSCAException):
# msg_fmt = _('%(what)s')
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
which might include code, classes, or functions. Output only the next line. | raise |
Here is a snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class TOSCAVersionPropertyTest(TestCase):
def test_tosca_version_property(self):
version = '18.0.3.beta-1'
expected_output = '18.0.3.beta-1'
output = TOSCAVersionProperty(version).get_version()
self.assertEqual(output, expected_output)
version = 18
expected_output = '18.0'
output = TOSCAVersionProperty(version).get_version()
self.assertEqual(output, expected_output)
version = 18.0
<|code_end|>
. Write the next line using the current file imports:
from toscaparser.common.exception import (
InvalidTOSCAVersionPropertyException)
from toscaparser.tests.base import TestCase
from toscaparser.utils.gettextutils import _
from toscaparser.utils.validateutils import TOSCAVersionProperty
and context from other files:
# Path: toscaparser/common/exception.py
# class InvalidTOSCAVersionPropertyException(TOSCAException):
# msg_fmt = _('Value of TOSCA version property "%(what)s" is invalid.')
#
# Path: toscaparser/tests/base.py
# class TestCase(testscenarios.TestWithScenarios, testtools.TestCase):
#
# """Test case base class for all unit tests."""
#
# def setUp(self):
# """Run before each test method to initialize test environment."""
#
# super(TestCase, self).setUp()
# test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
# try:
# test_timeout = int(test_timeout)
# except ValueError:
# # If timeout value is invalid do not set a timeout.
# test_timeout = 0
# if test_timeout > 0:
# self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
#
# self.useFixture(fixtures.NestedTempfile())
# self.useFixture(fixtures.TempHomeDir())
#
# if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
# stdout = self.useFixture(fixtures.StringStream('stdout')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
# if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
# stderr = self.useFixture(fixtures.StringStream('stderr')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
#
# self.log_fixture = self.useFixture(fixtures.FakeLogger())
#
# def _load_template(self, filename):
# """Load a Tosca template from tests data folder.
#
# :param filename: Tosca template file name to load.
# :return: ToscaTemplate
# """
# return ToscaTemplate(os.path.join(
# os.path.dirname(os.path.abspath(__file__)),
# 'data',
# filename))
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
#
# Path: toscaparser/utils/validateutils.py
# class TOSCAVersionProperty(object):
#
# VERSION_RE = re.compile(r'^(?P<major_version>([0-9][0-9]*))'
# r'(\.(?P<minor_version>([0-9][0-9]*)))?'
# r'(\.(?P<fix_version>([0-9][0-9]*)))?'
# r'(\.(?P<qualifier>([0-9A-Za-z]+)))?'
# r'(\-(?P<build_version>[0-9])*)?$')
#
# def __init__(self, version):
# self.version = str(version)
# match = self.VERSION_RE.match(self.version)
# if not match:
# ExceptionCollector.appendException(
# InvalidTOSCAVersionPropertyException(what=(self.version)))
# return
# ver = match.groupdict()
# if self.version in ['0', '0.0', '0.0.0']:
# log.warning('Version assumed as not provided')
# self.version = None
# self.minor_version = ver['minor_version']
# self.major_version = ver['major_version']
# self.fix_version = ver['fix_version']
# self.qualifier = self._validate_qualifier(ver['qualifier'])
# self.build_version = self._validate_build(ver['build_version'])
# self._validate_major_version(self.major_version)
#
# def _validate_major_version(self, value):
# """Validate major version
#
# Checks if only major version is provided and assumes
# minor version as 0.
# Eg: If version = 18, then it returns version = '18.0'
# """
#
# if self.minor_version is None and self.build_version is None and \
# value != '0':
# log.warning('Minor version assumed "0".')
# self.version = '.'.join([value, '0'])
# return value
#
# def _validate_qualifier(self, value):
# """Validate qualifier
#
# TOSCA version is invalid if a qualifier is present without the
# fix version or with all of major, minor and fix version 0s.
#
# For example, the following versions are invalid
# 18.0.abc
# 0.0.0.abc
# """
# if (self.fix_version is None and value) or \
# (self.minor_version == self.major_version ==
# self.fix_version == '0' and value):
# ExceptionCollector.appendException(
# InvalidTOSCAVersionPropertyException(what=(self.version)))
# return value
#
# def _validate_build(self, value):
# """Validate build version
#
# TOSCA version is invalid if build version is present without the
# qualifier.
# Eg: version = 18.0.0-1 is invalid.
# """
# if not self.qualifier and value:
# ExceptionCollector.appendException(
# InvalidTOSCAVersionPropertyException(what=(self.version)))
# return value
#
# def get_version(self):
# return self.version
, which may include functions, classes, or code. Output only the next line. | expected_output = '18.0' |
Here is a snippet: <|code_start|>
class TOSCAVersionPropertyTest(TestCase):
def test_tosca_version_property(self):
version = '18.0.3.beta-1'
expected_output = '18.0.3.beta-1'
output = TOSCAVersionProperty(version).get_version()
self.assertEqual(output, expected_output)
version = 18
expected_output = '18.0'
output = TOSCAVersionProperty(version).get_version()
self.assertEqual(output, expected_output)
version = 18.0
expected_output = '18.0'
output = TOSCAVersionProperty(version).get_version()
self.assertEqual(output, expected_output)
version = '18.0.3'
expected_output = '18.0.3'
output = TOSCAVersionProperty(version).get_version()
self.assertEqual(output, expected_output)
version = 0
expected_output = None
output = TOSCAVersionProperty(version).get_version()
self.assertEqual(output, expected_output)
version = 00
<|code_end|>
. Write the next line using the current file imports:
from toscaparser.common.exception import (
InvalidTOSCAVersionPropertyException)
from toscaparser.tests.base import TestCase
from toscaparser.utils.gettextutils import _
from toscaparser.utils.validateutils import TOSCAVersionProperty
and context from other files:
# Path: toscaparser/common/exception.py
# class InvalidTOSCAVersionPropertyException(TOSCAException):
# msg_fmt = _('Value of TOSCA version property "%(what)s" is invalid.')
#
# Path: toscaparser/tests/base.py
# class TestCase(testscenarios.TestWithScenarios, testtools.TestCase):
#
# """Test case base class for all unit tests."""
#
# def setUp(self):
# """Run before each test method to initialize test environment."""
#
# super(TestCase, self).setUp()
# test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
# try:
# test_timeout = int(test_timeout)
# except ValueError:
# # If timeout value is invalid do not set a timeout.
# test_timeout = 0
# if test_timeout > 0:
# self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
#
# self.useFixture(fixtures.NestedTempfile())
# self.useFixture(fixtures.TempHomeDir())
#
# if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
# stdout = self.useFixture(fixtures.StringStream('stdout')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
# if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
# stderr = self.useFixture(fixtures.StringStream('stderr')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
#
# self.log_fixture = self.useFixture(fixtures.FakeLogger())
#
# def _load_template(self, filename):
# """Load a Tosca template from tests data folder.
#
# :param filename: Tosca template file name to load.
# :return: ToscaTemplate
# """
# return ToscaTemplate(os.path.join(
# os.path.dirname(os.path.abspath(__file__)),
# 'data',
# filename))
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
#
# Path: toscaparser/utils/validateutils.py
# class TOSCAVersionProperty(object):
#
# VERSION_RE = re.compile(r'^(?P<major_version>([0-9][0-9]*))'
# r'(\.(?P<minor_version>([0-9][0-9]*)))?'
# r'(\.(?P<fix_version>([0-9][0-9]*)))?'
# r'(\.(?P<qualifier>([0-9A-Za-z]+)))?'
# r'(\-(?P<build_version>[0-9])*)?$')
#
# def __init__(self, version):
# self.version = str(version)
# match = self.VERSION_RE.match(self.version)
# if not match:
# ExceptionCollector.appendException(
# InvalidTOSCAVersionPropertyException(what=(self.version)))
# return
# ver = match.groupdict()
# if self.version in ['0', '0.0', '0.0.0']:
# log.warning('Version assumed as not provided')
# self.version = None
# self.minor_version = ver['minor_version']
# self.major_version = ver['major_version']
# self.fix_version = ver['fix_version']
# self.qualifier = self._validate_qualifier(ver['qualifier'])
# self.build_version = self._validate_build(ver['build_version'])
# self._validate_major_version(self.major_version)
#
# def _validate_major_version(self, value):
# """Validate major version
#
# Checks if only major version is provided and assumes
# minor version as 0.
# Eg: If version = 18, then it returns version = '18.0'
# """
#
# if self.minor_version is None and self.build_version is None and \
# value != '0':
# log.warning('Minor version assumed "0".')
# self.version = '.'.join([value, '0'])
# return value
#
# def _validate_qualifier(self, value):
# """Validate qualifier
#
# TOSCA version is invalid if a qualifier is present without the
# fix version or with all of major, minor and fix version 0s.
#
# For example, the following versions are invalid
# 18.0.abc
# 0.0.0.abc
# """
# if (self.fix_version is None and value) or \
# (self.minor_version == self.major_version ==
# self.fix_version == '0' and value):
# ExceptionCollector.appendException(
# InvalidTOSCAVersionPropertyException(what=(self.version)))
# return value
#
# def _validate_build(self, value):
# """Validate build version
#
# TOSCA version is invalid if build version is present without the
# qualifier.
# Eg: version = 18.0.0-1 is invalid.
# """
# if not self.qualifier and value:
# ExceptionCollector.appendException(
# InvalidTOSCAVersionPropertyException(what=(self.version)))
# return value
#
# def get_version(self):
# return self.version
, which may include functions, classes, or code. Output only the next line. | expected_output = None |
Given the following code snippet before the placeholder: <|code_start|># not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ExceptionTest(TestCase):
def setUp(self):
super(TestCase, self).setUp()
exception.TOSCAException.set_fatal_format_exception(False)
def test_message(self):
ex = exception.MissingRequiredFieldError(what='Template',
required='type')
self.assertEqual(_('Template is missing required field "type".'),
ex.__str__())
def test_set_flag(self):
exception.TOSCAException.set_fatal_format_exception('True')
self.assertFalse(
exception.TOSCAException._FATAL_EXCEPTION_FORMAT_ERRORS)
<|code_end|>
, predict the next line using imports from the current file:
from toscaparser.common import exception
from toscaparser.tests.base import TestCase
from toscaparser.utils.gettextutils import _
and context including class names, function names, and sometimes code from other files:
# Path: toscaparser/common/exception.py
# class TOSCAException(Exception):
# class UnsupportedTypeError(TOSCAException):
# class MissingRequiredFieldError(TOSCAException):
# class UnknownFieldError(TOSCAException):
# class TypeMismatchError(TOSCAException):
# class InvalidNodeTypeError(TOSCAException):
# class InvalidTypeError(TOSCAException):
# class InvalidTypeAdditionalRequirementsError(TOSCAException):
# class RangeValueError(TOSCAException):
# class InvalidSchemaError(TOSCAException):
# class ValidationError(TOSCAException):
# class UnknownInputError(TOSCAException):
# class UnknownOutputError(TOSCAException):
# class MissingRequiredInputError(TOSCAException):
# class MissingRequiredParameterError(TOSCAException):
# class MissingDefaultValueError(TOSCAException):
# class MissingRequiredOutputError(TOSCAException):
# class InvalidPropertyValueError(TOSCAException):
# class InvalidTemplateVersion(TOSCAException):
# class InvalidTOSCAVersionPropertyException(TOSCAException):
# class URLException(TOSCAException):
# class ToscaExtImportError(TOSCAException):
# class ToscaExtAttributeError(TOSCAException):
# class InvalidGroupTargetException(TOSCAException):
# class ExceptionCollector(object):
# _FATAL_EXCEPTION_FORMAT_ERRORS = False
# def __init__(self, **kwargs):
# def __str__(self):
# def generate_inv_schema_property_error(self, attr, value, valid_values):
# def set_fatal_format_exception(flag):
# def clear():
# def start():
# def stop():
# def contains(exception):
# def appendException(exception):
# def exceptionsCaught():
# def getTraceString(traceList):
# def getExceptionReportEntry(exception, full=True):
# def getExceptions():
# def getExceptionsReport(full=True):
# def assertExceptionMessage(exception, message):
#
# Path: toscaparser/tests/base.py
# class TestCase(testscenarios.TestWithScenarios, testtools.TestCase):
#
# """Test case base class for all unit tests."""
#
# def setUp(self):
# """Run before each test method to initialize test environment."""
#
# super(TestCase, self).setUp()
# test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
# try:
# test_timeout = int(test_timeout)
# except ValueError:
# # If timeout value is invalid do not set a timeout.
# test_timeout = 0
# if test_timeout > 0:
# self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
#
# self.useFixture(fixtures.NestedTempfile())
# self.useFixture(fixtures.TempHomeDir())
#
# if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
# stdout = self.useFixture(fixtures.StringStream('stdout')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
# if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
# stderr = self.useFixture(fixtures.StringStream('stderr')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
#
# self.log_fixture = self.useFixture(fixtures.FakeLogger())
#
# def _load_template(self, filename):
# """Load a Tosca template from tests data folder.
#
# :param filename: Tosca template file name to load.
# :return: ToscaTemplate
# """
# return ToscaTemplate(os.path.join(
# os.path.dirname(os.path.abspath(__file__)),
# 'data',
# filename))
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
. Output only the next line. | def test_format_error(self): |
Given snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ExceptionTest(TestCase):
def setUp(self):
super(TestCase, self).setUp()
exception.TOSCAException.set_fatal_format_exception(False)
def test_message(self):
ex = exception.MissingRequiredFieldError(what='Template',
required='type')
self.assertEqual(_('Template is missing required field "type".'),
ex.__str__())
def test_set_flag(self):
exception.TOSCAException.set_fatal_format_exception('True')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from toscaparser.common import exception
from toscaparser.tests.base import TestCase
from toscaparser.utils.gettextutils import _
and context:
# Path: toscaparser/common/exception.py
# class TOSCAException(Exception):
# class UnsupportedTypeError(TOSCAException):
# class MissingRequiredFieldError(TOSCAException):
# class UnknownFieldError(TOSCAException):
# class TypeMismatchError(TOSCAException):
# class InvalidNodeTypeError(TOSCAException):
# class InvalidTypeError(TOSCAException):
# class InvalidTypeAdditionalRequirementsError(TOSCAException):
# class RangeValueError(TOSCAException):
# class InvalidSchemaError(TOSCAException):
# class ValidationError(TOSCAException):
# class UnknownInputError(TOSCAException):
# class UnknownOutputError(TOSCAException):
# class MissingRequiredInputError(TOSCAException):
# class MissingRequiredParameterError(TOSCAException):
# class MissingDefaultValueError(TOSCAException):
# class MissingRequiredOutputError(TOSCAException):
# class InvalidPropertyValueError(TOSCAException):
# class InvalidTemplateVersion(TOSCAException):
# class InvalidTOSCAVersionPropertyException(TOSCAException):
# class URLException(TOSCAException):
# class ToscaExtImportError(TOSCAException):
# class ToscaExtAttributeError(TOSCAException):
# class InvalidGroupTargetException(TOSCAException):
# class ExceptionCollector(object):
# _FATAL_EXCEPTION_FORMAT_ERRORS = False
# def __init__(self, **kwargs):
# def __str__(self):
# def generate_inv_schema_property_error(self, attr, value, valid_values):
# def set_fatal_format_exception(flag):
# def clear():
# def start():
# def stop():
# def contains(exception):
# def appendException(exception):
# def exceptionsCaught():
# def getTraceString(traceList):
# def getExceptionReportEntry(exception, full=True):
# def getExceptions():
# def getExceptionsReport(full=True):
# def assertExceptionMessage(exception, message):
#
# Path: toscaparser/tests/base.py
# class TestCase(testscenarios.TestWithScenarios, testtools.TestCase):
#
# """Test case base class for all unit tests."""
#
# def setUp(self):
# """Run before each test method to initialize test environment."""
#
# super(TestCase, self).setUp()
# test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
# try:
# test_timeout = int(test_timeout)
# except ValueError:
# # If timeout value is invalid do not set a timeout.
# test_timeout = 0
# if test_timeout > 0:
# self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
#
# self.useFixture(fixtures.NestedTempfile())
# self.useFixture(fixtures.TempHomeDir())
#
# if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
# stdout = self.useFixture(fixtures.StringStream('stdout')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
# if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
# stderr = self.useFixture(fixtures.StringStream('stderr')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
#
# self.log_fixture = self.useFixture(fixtures.FakeLogger())
#
# def _load_template(self, filename):
# """Load a Tosca template from tests data folder.
#
# :param filename: Tosca template file name to load.
# :return: ToscaTemplate
# """
# return ToscaTemplate(os.path.join(
# os.path.dirname(os.path.abspath(__file__)),
# 'data',
# filename))
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
which might include code, classes, or functions. Output only the next line. | self.assertFalse( |
Given the following code snippet before the placeholder: <|code_start|># not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ExceptionTest(TestCase):
def setUp(self):
super(TestCase, self).setUp()
exception.TOSCAException.set_fatal_format_exception(False)
def test_message(self):
ex = exception.MissingRequiredFieldError(what='Template',
required='type')
self.assertEqual(_('Template is missing required field "type".'),
ex.__str__())
def test_set_flag(self):
exception.TOSCAException.set_fatal_format_exception('True')
self.assertFalse(
exception.TOSCAException._FATAL_EXCEPTION_FORMAT_ERRORS)
<|code_end|>
, predict the next line using imports from the current file:
from toscaparser.common import exception
from toscaparser.tests.base import TestCase
from toscaparser.utils.gettextutils import _
and context including class names, function names, and sometimes code from other files:
# Path: toscaparser/common/exception.py
# class TOSCAException(Exception):
# class UnsupportedTypeError(TOSCAException):
# class MissingRequiredFieldError(TOSCAException):
# class UnknownFieldError(TOSCAException):
# class TypeMismatchError(TOSCAException):
# class InvalidNodeTypeError(TOSCAException):
# class InvalidTypeError(TOSCAException):
# class InvalidTypeAdditionalRequirementsError(TOSCAException):
# class RangeValueError(TOSCAException):
# class InvalidSchemaError(TOSCAException):
# class ValidationError(TOSCAException):
# class UnknownInputError(TOSCAException):
# class UnknownOutputError(TOSCAException):
# class MissingRequiredInputError(TOSCAException):
# class MissingRequiredParameterError(TOSCAException):
# class MissingDefaultValueError(TOSCAException):
# class MissingRequiredOutputError(TOSCAException):
# class InvalidPropertyValueError(TOSCAException):
# class InvalidTemplateVersion(TOSCAException):
# class InvalidTOSCAVersionPropertyException(TOSCAException):
# class URLException(TOSCAException):
# class ToscaExtImportError(TOSCAException):
# class ToscaExtAttributeError(TOSCAException):
# class InvalidGroupTargetException(TOSCAException):
# class ExceptionCollector(object):
# _FATAL_EXCEPTION_FORMAT_ERRORS = False
# def __init__(self, **kwargs):
# def __str__(self):
# def generate_inv_schema_property_error(self, attr, value, valid_values):
# def set_fatal_format_exception(flag):
# def clear():
# def start():
# def stop():
# def contains(exception):
# def appendException(exception):
# def exceptionsCaught():
# def getTraceString(traceList):
# def getExceptionReportEntry(exception, full=True):
# def getExceptions():
# def getExceptionsReport(full=True):
# def assertExceptionMessage(exception, message):
#
# Path: toscaparser/tests/base.py
# class TestCase(testscenarios.TestWithScenarios, testtools.TestCase):
#
# """Test case base class for all unit tests."""
#
# def setUp(self):
# """Run before each test method to initialize test environment."""
#
# super(TestCase, self).setUp()
# test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
# try:
# test_timeout = int(test_timeout)
# except ValueError:
# # If timeout value is invalid do not set a timeout.
# test_timeout = 0
# if test_timeout > 0:
# self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
#
# self.useFixture(fixtures.NestedTempfile())
# self.useFixture(fixtures.TempHomeDir())
#
# if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
# stdout = self.useFixture(fixtures.StringStream('stdout')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
# if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
# stderr = self.useFixture(fixtures.StringStream('stderr')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
#
# self.log_fixture = self.useFixture(fixtures.FakeLogger())
#
# def _load_template(self, filename):
# """Load a Tosca template from tests data folder.
#
# :param filename: Tosca template file name to load.
# :return: ToscaTemplate
# """
# return ToscaTemplate(os.path.join(
# os.path.dirname(os.path.abspath(__file__)),
# 'data',
# filename))
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
. Output only the next line. | def test_format_error(self): |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class TypeValidation(object):
ALLOWED_TYPE_SECTIONS = (DEFINITION_VERSION, DESCRIPTION, IMPORTS,
DSL_DEFINITIONS, NODE_TYPES, REPOSITORIES,
DATA_TYPES, ARTIFACT_TYPES, GROUP_TYPES,
RELATIONSHIP_TYPES, CAPABILITY_TYPES,
INTERFACE_TYPES, POLICY_TYPES,
TOPOLOGY_TEMPLATE, METADATA) = \
('tosca_definitions_version', 'description', 'imports',
<|code_end|>
. Use current file imports:
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import InvalidTemplateVersion
from toscaparser.common.exception import UnknownFieldError
from toscaparser.extensions.exttools import ExtTools
and context (classes, functions, or code) from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class InvalidTemplateVersion(TOSCAException):
# msg_fmt = _('The template version "%(what)s" is invalid. '
# 'Valid versions are "%(valid_versions)s".')
#
# Path: toscaparser/common/exception.py
# class UnknownFieldError(TOSCAException):
# msg_fmt = _('%(what)s contains unknown field "%(field)s". Refer to the '
# 'definition to verify valid values.')
#
# Path: toscaparser/extensions/exttools.py
# class ExtTools(object):
# def __init__(self):
# self.EXTENSION_INFO = self._load_extensions()
#
# def _load_extensions(self):
# '''Dynamically load all the extensions .'''
# extensions = collections.OrderedDict()
#
# extns = extension.ExtensionManager(namespace='toscaparser.extensions',
# invoke_on_load=True).extensions
#
# for e in extns:
# try:
# extinfo = importlib.import_module(e.plugin.__module__)
# base_path = os.path.dirname(extinfo.__file__)
# version = e.plugin().VERSION
# defs_file = base_path + '/' + e.plugin().DEFS_FILE
#
# # Sections is an optional attribute
# sections = getattr(e.plugin(), 'SECTIONS', ())
#
# extensions[version] = {'sections': sections,
# 'defs_file': defs_file}
# except ImportError:
# raise ToscaExtImportError(ext_name=e.name)
# except AttributeError:
# attrs = ', '.join(REQUIRED_ATTRIBUTES)
# raise ToscaExtAttributeError(ext_name=e.name, attrs=attrs)
#
# return extensions
#
# def get_versions(self):
# return sorted(self.EXTENSION_INFO.keys())
#
# def get_sections(self):
# sections = {}
# for version in self.EXTENSION_INFO.keys():
# sections[version] = self.EXTENSION_INFO[version]['sections']
#
# return sections
#
# def get_defs_file(self, version):
# versiondata = self.EXTENSION_INFO.get(version)
#
# if versiondata:
# return versiondata.get('defs_file')
# else:
# return None
. Output only the next line. | 'dsl_definitions', 'node_types', 'repositories', |
Here is a snippet: <|code_start|> 'interface_types', 'policy_types', 'topology_template',
'metadata')
VALID_TEMPLATE_VERSIONS = ['tosca_simple_yaml_1_0',
'tosca_simple_yaml_1_2']
exttools = ExtTools()
VALID_TEMPLATE_VERSIONS.extend(exttools.get_versions())
def __init__(self, custom_types, import_def):
self.import_def = import_def
self._validate_type_keys(custom_types)
def _validate_type_keys(self, custom_type):
version = custom_type[self.DEFINITION_VERSION] \
if self.DEFINITION_VERSION in custom_type \
else None
if version:
self._validate_type_version(version)
self.version = version
for name in custom_type:
if name not in self.ALLOWED_TYPE_SECTIONS:
ExceptionCollector.appendException(
UnknownFieldError(what='Template ' + str(self.import_def),
field=name))
def _validate_type_version(self, version):
if version not in self.VALID_TEMPLATE_VERSIONS:
ExceptionCollector.appendException(
InvalidTemplateVersion(
what=version + ' in ' + str(self.import_def),
<|code_end|>
. Write the next line using the current file imports:
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import InvalidTemplateVersion
from toscaparser.common.exception import UnknownFieldError
from toscaparser.extensions.exttools import ExtTools
and context from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class InvalidTemplateVersion(TOSCAException):
# msg_fmt = _('The template version "%(what)s" is invalid. '
# 'Valid versions are "%(valid_versions)s".')
#
# Path: toscaparser/common/exception.py
# class UnknownFieldError(TOSCAException):
# msg_fmt = _('%(what)s contains unknown field "%(field)s". Refer to the '
# 'definition to verify valid values.')
#
# Path: toscaparser/extensions/exttools.py
# class ExtTools(object):
# def __init__(self):
# self.EXTENSION_INFO = self._load_extensions()
#
# def _load_extensions(self):
# '''Dynamically load all the extensions .'''
# extensions = collections.OrderedDict()
#
# extns = extension.ExtensionManager(namespace='toscaparser.extensions',
# invoke_on_load=True).extensions
#
# for e in extns:
# try:
# extinfo = importlib.import_module(e.plugin.__module__)
# base_path = os.path.dirname(extinfo.__file__)
# version = e.plugin().VERSION
# defs_file = base_path + '/' + e.plugin().DEFS_FILE
#
# # Sections is an optional attribute
# sections = getattr(e.plugin(), 'SECTIONS', ())
#
# extensions[version] = {'sections': sections,
# 'defs_file': defs_file}
# except ImportError:
# raise ToscaExtImportError(ext_name=e.name)
# except AttributeError:
# attrs = ', '.join(REQUIRED_ATTRIBUTES)
# raise ToscaExtAttributeError(ext_name=e.name, attrs=attrs)
#
# return extensions
#
# def get_versions(self):
# return sorted(self.EXTENSION_INFO.keys())
#
# def get_sections(self):
# sections = {}
# for version in self.EXTENSION_INFO.keys():
# sections[version] = self.EXTENSION_INFO[version]['sections']
#
# return sections
#
# def get_defs_file(self, version):
# versiondata = self.EXTENSION_INFO.get(version)
#
# if versiondata:
# return versiondata.get('defs_file')
# else:
# return None
, which may include functions, classes, or code. Output only the next line. | valid_versions='", "'. join(self.VALID_TEMPLATE_VERSIONS))) |
Predict the next line after this snippet: <|code_start|># WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class TypeValidation(object):
ALLOWED_TYPE_SECTIONS = (DEFINITION_VERSION, DESCRIPTION, IMPORTS,
DSL_DEFINITIONS, NODE_TYPES, REPOSITORIES,
DATA_TYPES, ARTIFACT_TYPES, GROUP_TYPES,
RELATIONSHIP_TYPES, CAPABILITY_TYPES,
INTERFACE_TYPES, POLICY_TYPES,
TOPOLOGY_TEMPLATE, METADATA) = \
('tosca_definitions_version', 'description', 'imports',
'dsl_definitions', 'node_types', 'repositories',
'data_types', 'artifact_types', 'group_types',
'relationship_types', 'capability_types',
'interface_types', 'policy_types', 'topology_template',
'metadata')
VALID_TEMPLATE_VERSIONS = ['tosca_simple_yaml_1_0',
'tosca_simple_yaml_1_2']
exttools = ExtTools()
VALID_TEMPLATE_VERSIONS.extend(exttools.get_versions())
def __init__(self, custom_types, import_def):
self.import_def = import_def
self._validate_type_keys(custom_types)
def _validate_type_keys(self, custom_type):
<|code_end|>
using the current file's imports:
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import InvalidTemplateVersion
from toscaparser.common.exception import UnknownFieldError
from toscaparser.extensions.exttools import ExtTools
and any relevant context from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class InvalidTemplateVersion(TOSCAException):
# msg_fmt = _('The template version "%(what)s" is invalid. '
# 'Valid versions are "%(valid_versions)s".')
#
# Path: toscaparser/common/exception.py
# class UnknownFieldError(TOSCAException):
# msg_fmt = _('%(what)s contains unknown field "%(field)s". Refer to the '
# 'definition to verify valid values.')
#
# Path: toscaparser/extensions/exttools.py
# class ExtTools(object):
# def __init__(self):
# self.EXTENSION_INFO = self._load_extensions()
#
# def _load_extensions(self):
# '''Dynamically load all the extensions .'''
# extensions = collections.OrderedDict()
#
# extns = extension.ExtensionManager(namespace='toscaparser.extensions',
# invoke_on_load=True).extensions
#
# for e in extns:
# try:
# extinfo = importlib.import_module(e.plugin.__module__)
# base_path = os.path.dirname(extinfo.__file__)
# version = e.plugin().VERSION
# defs_file = base_path + '/' + e.plugin().DEFS_FILE
#
# # Sections is an optional attribute
# sections = getattr(e.plugin(), 'SECTIONS', ())
#
# extensions[version] = {'sections': sections,
# 'defs_file': defs_file}
# except ImportError:
# raise ToscaExtImportError(ext_name=e.name)
# except AttributeError:
# attrs = ', '.join(REQUIRED_ATTRIBUTES)
# raise ToscaExtAttributeError(ext_name=e.name, attrs=attrs)
#
# return extensions
#
# def get_versions(self):
# return sorted(self.EXTENSION_INFO.keys())
#
# def get_sections(self):
# sections = {}
# for version in self.EXTENSION_INFO.keys():
# sections[version] = self.EXTENSION_INFO[version]['sections']
#
# return sections
#
# def get_defs_file(self, version):
# versiondata = self.EXTENSION_INFO.get(version)
#
# if versiondata:
# return versiondata.get('defs_file')
# else:
# return None
. Output only the next line. | version = custom_type[self.DEFINITION_VERSION] \ |
Given the code snippet: <|code_start|># not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
YAML_LOADER = toscaparser.utils.yamlparser.load_yaml
class UrlUtilsTest(TestCase):
url_utils = toscaparser.utils.urlutils.UrlUtils
def test_urlutils_validate_url(self):
self.assertTrue(self.url_utils.validate_url("http://www.github.com/"))
self.assertTrue(
self.url_utils.validate_url("https://github.com:81/a/2/a.b"))
self.assertTrue(self.url_utils.validate_url("ftp://github.com"))
self.assertFalse(self.url_utils.validate_url("github.com"))
self.assertFalse(self.url_utils.validate_url("123"))
self.assertFalse(self.url_utils.validate_url("a/b/c"))
self.assertTrue(self.url_utils.validate_url("file:///dir/file.ext"))
def test_urlutils_join_url(self):
<|code_end|>
, generate the next line using the imports in this file:
from toscaparser.tests.base import TestCase
import toscaparser.utils.urlutils
import toscaparser.utils.yamlparser
and context (functions, classes, or occasionally code) from other files:
# Path: toscaparser/tests/base.py
# class TestCase(testscenarios.TestWithScenarios, testtools.TestCase):
#
# """Test case base class for all unit tests."""
#
# def setUp(self):
# """Run before each test method to initialize test environment."""
#
# super(TestCase, self).setUp()
# test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
# try:
# test_timeout = int(test_timeout)
# except ValueError:
# # If timeout value is invalid do not set a timeout.
# test_timeout = 0
# if test_timeout > 0:
# self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
#
# self.useFixture(fixtures.NestedTempfile())
# self.useFixture(fixtures.TempHomeDir())
#
# if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
# stdout = self.useFixture(fixtures.StringStream('stdout')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
# if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
# stderr = self.useFixture(fixtures.StringStream('stderr')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
#
# self.log_fixture = self.useFixture(fixtures.FakeLogger())
#
# def _load_template(self, filename):
# """Load a Tosca template from tests data folder.
#
# :param filename: Tosca template file name to load.
# :return: ToscaTemplate
# """
# return ToscaTemplate(os.path.join(
# os.path.dirname(os.path.abspath(__file__)),
# 'data',
# filename))
. Output only the next line. | self.assertEqual( |
Based on the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ShellTest(TestCase):
tosca_helloworld = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"data/tosca_helloworld.yaml")
errornous_template = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"data/test_multiple_validation_errors.yaml")
def test_missing_arg(self):
self.assertRaises(SystemExit, shell.main, '')
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import toscaparser.shell as shell
from toscaparser.common import exception
from toscaparser.tests.base import TestCase
from toscaparser.utils.gettextutils import _
and context (classes, functions, sometimes code) from other files:
# Path: toscaparser/common/exception.py
# class TOSCAException(Exception):
# class UnsupportedTypeError(TOSCAException):
# class MissingRequiredFieldError(TOSCAException):
# class UnknownFieldError(TOSCAException):
# class TypeMismatchError(TOSCAException):
# class InvalidNodeTypeError(TOSCAException):
# class InvalidTypeError(TOSCAException):
# class InvalidTypeAdditionalRequirementsError(TOSCAException):
# class RangeValueError(TOSCAException):
# class InvalidSchemaError(TOSCAException):
# class ValidationError(TOSCAException):
# class UnknownInputError(TOSCAException):
# class UnknownOutputError(TOSCAException):
# class MissingRequiredInputError(TOSCAException):
# class MissingRequiredParameterError(TOSCAException):
# class MissingDefaultValueError(TOSCAException):
# class MissingRequiredOutputError(TOSCAException):
# class InvalidPropertyValueError(TOSCAException):
# class InvalidTemplateVersion(TOSCAException):
# class InvalidTOSCAVersionPropertyException(TOSCAException):
# class URLException(TOSCAException):
# class ToscaExtImportError(TOSCAException):
# class ToscaExtAttributeError(TOSCAException):
# class InvalidGroupTargetException(TOSCAException):
# class ExceptionCollector(object):
# _FATAL_EXCEPTION_FORMAT_ERRORS = False
# def __init__(self, **kwargs):
# def __str__(self):
# def generate_inv_schema_property_error(self, attr, value, valid_values):
# def set_fatal_format_exception(flag):
# def clear():
# def start():
# def stop():
# def contains(exception):
# def appendException(exception):
# def exceptionsCaught():
# def getTraceString(traceList):
# def getExceptionReportEntry(exception, full=True):
# def getExceptions():
# def getExceptionsReport(full=True):
# def assertExceptionMessage(exception, message):
#
# Path: toscaparser/tests/base.py
# class TestCase(testscenarios.TestWithScenarios, testtools.TestCase):
#
# """Test case base class for all unit tests."""
#
# def setUp(self):
# """Run before each test method to initialize test environment."""
#
# super(TestCase, self).setUp()
# test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
# try:
# test_timeout = int(test_timeout)
# except ValueError:
# # If timeout value is invalid do not set a timeout.
# test_timeout = 0
# if test_timeout > 0:
# self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
#
# self.useFixture(fixtures.NestedTempfile())
# self.useFixture(fixtures.TempHomeDir())
#
# if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
# stdout = self.useFixture(fixtures.StringStream('stdout')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
# if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
# stderr = self.useFixture(fixtures.StringStream('stderr')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
#
# self.log_fixture = self.useFixture(fixtures.FakeLogger())
#
# def _load_template(self, filename):
# """Load a Tosca template from tests data folder.
#
# :param filename: Tosca template file name to load.
# :return: ToscaTemplate
# """
# return ToscaTemplate(os.path.join(
# os.path.dirname(os.path.abspath(__file__)),
# 'data',
# filename))
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
. Output only the next line. | def test_invalid_arg(self): |
Predict the next line for this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ShellTest(TestCase):
tosca_helloworld = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"data/tosca_helloworld.yaml")
errornous_template = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"data/test_multiple_validation_errors.yaml")
def test_missing_arg(self):
self.assertRaises(SystemExit, shell.main, '')
<|code_end|>
with the help of current file imports:
import os
import toscaparser.shell as shell
from toscaparser.common import exception
from toscaparser.tests.base import TestCase
from toscaparser.utils.gettextutils import _
and context from other files:
# Path: toscaparser/common/exception.py
# class TOSCAException(Exception):
# class UnsupportedTypeError(TOSCAException):
# class MissingRequiredFieldError(TOSCAException):
# class UnknownFieldError(TOSCAException):
# class TypeMismatchError(TOSCAException):
# class InvalidNodeTypeError(TOSCAException):
# class InvalidTypeError(TOSCAException):
# class InvalidTypeAdditionalRequirementsError(TOSCAException):
# class RangeValueError(TOSCAException):
# class InvalidSchemaError(TOSCAException):
# class ValidationError(TOSCAException):
# class UnknownInputError(TOSCAException):
# class UnknownOutputError(TOSCAException):
# class MissingRequiredInputError(TOSCAException):
# class MissingRequiredParameterError(TOSCAException):
# class MissingDefaultValueError(TOSCAException):
# class MissingRequiredOutputError(TOSCAException):
# class InvalidPropertyValueError(TOSCAException):
# class InvalidTemplateVersion(TOSCAException):
# class InvalidTOSCAVersionPropertyException(TOSCAException):
# class URLException(TOSCAException):
# class ToscaExtImportError(TOSCAException):
# class ToscaExtAttributeError(TOSCAException):
# class InvalidGroupTargetException(TOSCAException):
# class ExceptionCollector(object):
# _FATAL_EXCEPTION_FORMAT_ERRORS = False
# def __init__(self, **kwargs):
# def __str__(self):
# def generate_inv_schema_property_error(self, attr, value, valid_values):
# def set_fatal_format_exception(flag):
# def clear():
# def start():
# def stop():
# def contains(exception):
# def appendException(exception):
# def exceptionsCaught():
# def getTraceString(traceList):
# def getExceptionReportEntry(exception, full=True):
# def getExceptions():
# def getExceptionsReport(full=True):
# def assertExceptionMessage(exception, message):
#
# Path: toscaparser/tests/base.py
# class TestCase(testscenarios.TestWithScenarios, testtools.TestCase):
#
# """Test case base class for all unit tests."""
#
# def setUp(self):
# """Run before each test method to initialize test environment."""
#
# super(TestCase, self).setUp()
# test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
# try:
# test_timeout = int(test_timeout)
# except ValueError:
# # If timeout value is invalid do not set a timeout.
# test_timeout = 0
# if test_timeout > 0:
# self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
#
# self.useFixture(fixtures.NestedTempfile())
# self.useFixture(fixtures.TempHomeDir())
#
# if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
# stdout = self.useFixture(fixtures.StringStream('stdout')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
# if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
# stderr = self.useFixture(fixtures.StringStream('stderr')).stream
# self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
#
# self.log_fixture = self.useFixture(fixtures.FakeLogger())
#
# def _load_template(self, filename):
# """Load a Tosca template from tests data folder.
#
# :param filename: Tosca template file name to load.
# :return: ToscaTemplate
# """
# return ToscaTemplate(os.path.join(
# os.path.dirname(os.path.abspath(__file__)),
# 'data',
# filename))
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
, which may contain function names, class names, or code. Output only the next line. | def test_invalid_arg(self): |
Given snippet: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
log = logging.getLogger("tosca.model")
REQUIRED_ATTRIBUTES = ['VERSION', 'DEFS_FILE']
class ExtTools(object):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import collections
import importlib
import logging
import os
from stevedore import extension
from toscaparser.common.exception import ToscaExtAttributeError
from toscaparser.common.exception import ToscaExtImportError
and context:
# Path: toscaparser/common/exception.py
# class ToscaExtAttributeError(TOSCAException):
# msg_fmt = _('Missing attribute in extension "%(ext_name)s". '
# 'Check to see that it has required attributes '
# '"%(attrs)s" defined.')
#
# Path: toscaparser/common/exception.py
# class ToscaExtImportError(TOSCAException):
# msg_fmt = _('Unable to import extension "%(ext_name)s". '
# 'Check to see that it exists and has no '
# 'language definition errors.')
which might include code, classes, or functions. Output only the next line. | def __init__(self): |
Here is a snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
SECTIONS = (DESCRIPTION, URL, CREDENTIAL) = \
('description', 'url', 'credential')
class Repository(object):
def __init__(self, repositories, values):
self.name = repositories
self.reposit = values
if isinstance(self.reposit, dict):
if 'url' not in self.reposit.keys():
ExceptionCollector.appendException(
MissingRequiredFieldError(what=_('Repository "%s"')
% self.name, required='url'))
self.url = self.reposit['url']
self.load_and_validate(self.name, self.reposit)
def load_and_validate(self, val, reposit_def):
<|code_end|>
. Write the next line using the current file imports:
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import MissingRequiredFieldError
from toscaparser.common.exception import UnknownFieldError
from toscaparser.common.exception import URLException
from toscaparser.utils.gettextutils import _
import toscaparser.utils.urlutils
and context from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class MissingRequiredFieldError(TOSCAException):
# msg_fmt = _('%(what)s is missing required field "%(required)s".')
#
# Path: toscaparser/common/exception.py
# class UnknownFieldError(TOSCAException):
# msg_fmt = _('%(what)s contains unknown field "%(field)s". Refer to the '
# 'definition to verify valid values.')
#
# Path: toscaparser/common/exception.py
# class URLException(TOSCAException):
# msg_fmt = _('%(what)s')
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
, which may include functions, classes, or code. Output only the next line. | self.keyname = val |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
SECTIONS = (DESCRIPTION, URL, CREDENTIAL) = \
('description', 'url', 'credential')
class Repository(object):
def __init__(self, repositories, values):
<|code_end|>
. Use current file imports:
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import MissingRequiredFieldError
from toscaparser.common.exception import UnknownFieldError
from toscaparser.common.exception import URLException
from toscaparser.utils.gettextutils import _
import toscaparser.utils.urlutils
and context (classes, functions, or code) from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class MissingRequiredFieldError(TOSCAException):
# msg_fmt = _('%(what)s is missing required field "%(required)s".')
#
# Path: toscaparser/common/exception.py
# class UnknownFieldError(TOSCAException):
# msg_fmt = _('%(what)s contains unknown field "%(field)s". Refer to the '
# 'definition to verify valid values.')
#
# Path: toscaparser/common/exception.py
# class URLException(TOSCAException):
# msg_fmt = _('%(what)s')
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
. Output only the next line. | self.name = repositories |
Given the code snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
SECTIONS = (DESCRIPTION, URL, CREDENTIAL) = \
('description', 'url', 'credential')
class Repository(object):
def __init__(self, repositories, values):
self.name = repositories
self.reposit = values
if isinstance(self.reposit, dict):
if 'url' not in self.reposit.keys():
ExceptionCollector.appendException(
MissingRequiredFieldError(what=_('Repository "%s"')
% self.name, required='url'))
self.url = self.reposit['url']
self.load_and_validate(self.name, self.reposit)
def load_and_validate(self, val, reposit_def):
self.keyname = val
if isinstance(reposit_def, dict):
for key in reposit_def.keys():
if key not in SECTIONS:
ExceptionCollector.appendException(
UnknownFieldError(what=_('repositories "%s"')
<|code_end|>
, generate the next line using the imports in this file:
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import MissingRequiredFieldError
from toscaparser.common.exception import UnknownFieldError
from toscaparser.common.exception import URLException
from toscaparser.utils.gettextutils import _
import toscaparser.utils.urlutils
and context (functions, classes, or occasionally code) from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class MissingRequiredFieldError(TOSCAException):
# msg_fmt = _('%(what)s is missing required field "%(required)s".')
#
# Path: toscaparser/common/exception.py
# class UnknownFieldError(TOSCAException):
# msg_fmt = _('%(what)s contains unknown field "%(field)s". Refer to the '
# 'definition to verify valid values.')
#
# Path: toscaparser/common/exception.py
# class URLException(TOSCAException):
# msg_fmt = _('%(what)s')
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
. Output only the next line. | % self.keyname, field=key)) |
Given the code snippet: <|code_start|># License for the specific language governing permissions and limitations
# under the License.
SECTIONS = (DESCRIPTION, URL, CREDENTIAL) = \
('description', 'url', 'credential')
class Repository(object):
def __init__(self, repositories, values):
self.name = repositories
self.reposit = values
if isinstance(self.reposit, dict):
if 'url' not in self.reposit.keys():
ExceptionCollector.appendException(
MissingRequiredFieldError(what=_('Repository "%s"')
% self.name, required='url'))
self.url = self.reposit['url']
self.load_and_validate(self.name, self.reposit)
def load_and_validate(self, val, reposit_def):
self.keyname = val
if isinstance(reposit_def, dict):
for key in reposit_def.keys():
if key not in SECTIONS:
ExceptionCollector.appendException(
UnknownFieldError(what=_('repositories "%s"')
% self.keyname, field=key))
if URL in reposit_def.keys():
<|code_end|>
, generate the next line using the imports in this file:
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import MissingRequiredFieldError
from toscaparser.common.exception import UnknownFieldError
from toscaparser.common.exception import URLException
from toscaparser.utils.gettextutils import _
import toscaparser.utils.urlutils
and context (functions, classes, or occasionally code) from other files:
# Path: toscaparser/common/exception.py
# class ExceptionCollector(object):
#
# exceptions = []
# collecting = False
#
# @staticmethod
# def clear():
# del ExceptionCollector.exceptions[:]
#
# @staticmethod
# def start():
# ExceptionCollector.clear()
# ExceptionCollector.collecting = True
#
# @staticmethod
# def stop():
# ExceptionCollector.collecting = False
#
# @staticmethod
# def contains(exception):
# for ex in ExceptionCollector.exceptions:
# if str(ex) == str(exception):
# return True
# return False
#
# @staticmethod
# def appendException(exception):
# if ExceptionCollector.collecting:
# if not ExceptionCollector.contains(exception):
# exception.trace = traceback.extract_stack()[:-1]
# ExceptionCollector.exceptions.append(exception)
# else:
# raise exception
#
# @staticmethod
# def exceptionsCaught():
# return len(ExceptionCollector.exceptions) > 0
#
# @staticmethod
# def getTraceString(traceList):
# traceString = ''
# for entry in traceList:
# f, l, m, c = entry[0], entry[1], entry[2], entry[3]
# traceString += (_('\t\tFile %(file)s, line %(line)s, in '
# '%(method)s\n\t\t\t%(call)s\n')
# % {'file': f, 'line': l, 'method': m, 'call': c})
# return traceString
#
# @staticmethod
# def getExceptionReportEntry(exception, full=True):
# entry = exception.__class__.__name__ + ': ' + str(exception)
# if full:
# entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
# return entry
#
# @staticmethod
# def getExceptions():
# return ExceptionCollector.exceptions
#
# @staticmethod
# def getExceptionsReport(full=True):
# report = []
# for exception in ExceptionCollector.exceptions:
# report.append(
# ExceptionCollector.getExceptionReportEntry(exception, full))
# return report
#
# @staticmethod
# def assertExceptionMessage(exception, message):
# err_msg = exception.__name__ + ': ' + message
# report = ExceptionCollector.getExceptionsReport(False)
# assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
# % {'rep': report.__str__(), 'msg': err_msg})
#
# Path: toscaparser/common/exception.py
# class MissingRequiredFieldError(TOSCAException):
# msg_fmt = _('%(what)s is missing required field "%(required)s".')
#
# Path: toscaparser/common/exception.py
# class UnknownFieldError(TOSCAException):
# msg_fmt = _('%(what)s contains unknown field "%(field)s". Refer to the '
# 'definition to verify valid values.')
#
# Path: toscaparser/common/exception.py
# class URLException(TOSCAException):
# msg_fmt = _('%(what)s')
#
# Path: toscaparser/utils/gettextutils.py
# def _(msg):
# # type: (object) -> object
# return _t.gettext(msg)
. Output only the next line. | reposit_url = reposit_def.get(URL) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
PICKLE_FILENAME = "trontagger-0.1.0.pickle"
class MissingCorpusException(Exception):
<|code_end|>
, generate the next line using the imports in this file:
import os
import random
import pickle
import logging
from collections import defaultdict
from scan import settings
from external.tagger._perceptron import AveragedPerceptron
and context (functions, classes, or occasionally code) from other files:
# Path: scan/settings.py
# DB_URL = 'sqlite:///scan.db'
# DEBUG = True
# ROOT_PATH = path(__file__).dirname()
# REPO_PATH = ROOT_PATH.dirname()
# ENV_ROOT = REPO_PATH.dirname()
# DATA_PATH = os.path.join(REPO_PATH, "data")
# TEST_DATA_PATH = os.path.join(DATA_PATH, "test")
# MODEL_PATH = os.path.join(DATA_PATH, "models")
# SECRET_KEY = "30y^$e7henbp@#_w+z9)o9f8tovjrhoq(%vw=%#*(1-1esrh!_"
# USERNAME = "test"
# EMAIL = "test@test.com"
# PASSWORD = "test"
# SQLALCHEMY_DATABASE_URI = DB_URL
# SECURITY_REGISTERABLE = True
# SECURITY_RECOVERABLE = True
# SECURITY_SEND_REGISTER_EMAIL = False
# SECURITY_PASSWORD_HASH = "bcrypt"
# SECURITY_PASSWORD_SALT = SECRET_KEY
# BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600}
# BROKER_URL = 'redis://localhost:6379/3'
# CELERY_RESULT_BACKEND = 'redis://localhost:6379/3'
# CELERY_IMPORTS = ('core.tasks.tasks',)
# CACHE_TYPE = 'redis'
# CACHE_REDIS_URL = 'redis://localhost:6379/4'
# CACHE_REDIS_DB = 4
# MAX_FEATURES = 500
# MODEL_VERSION = 1
. Output only the next line. | pass |
Given the following code snippet before the placeholder: <|code_start|>
class QuestionForm(Form):
name = StringField('Name', [Required()], description="The name you want to give this question.", )
prompt = TextAreaField('Prompt', [Optional()], description="The prompt for this question (optional).")
def save(self):
q = Question(user=current_user)
self.populate_obj(q)
db.session.add(q)
db.session.commit()
class EssayForm(Form):
text = TextAreaField('Text', [Required()], description="The text of the essay.")
actual_score = FloatField('Score (optional)', [Optional()], description="The score the essay got, if it has a score.")
info = TextAreaField("Additional Info (optional)", [Optional()], description="Any additional info you want to store with this essay.")
def save(self, question):
e = Essay(question=question)
<|code_end|>
, predict the next line using imports from the current file:
from flask_wtf import Form
from werkzeug import secure_filename
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import FloatField, IntegerField, TextField, StringField, TextAreaField
from wtforms.validators import Required, Optional
from core.database.models import Question, Essay
from flask.ext.login import current_user
from app import db
from app import db
from app import db
import csv
and context including class names, function names, and sometimes code from other files:
# Path: core/database/models.py
# class Question(db.Model):
# __tablename__ = 'questions'
#
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(STRING_MAX))
# description = db.Column(db.Text)
# prompt = db.Column(db.Text)
# user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#
# user = db.relationship("User", backref=db.backref('questions', order_by=id))
#
# created = db.Column(db.DateTime(timezone=True), default=datetime.utcnow)
# updated = db.Column(db.DateTime(timezone=True), onupdate=datetime.utcnow)
#
# class Essay(db.Model):
# __tablename__ = 'essays'
#
# id = db.Column(db.Integer, primary_key=True)
# text = db.Column(db.Text)
# actual_score = db.Column(db.Float)
# info = db.Column(db.Text)
#
# predicted_score = db.Column(db.Float)
# model_id = db.Column(db.Integer, db.ForeignKey('models.id'))
# model = db.relationship("Model", backref=db.backref('essays', order_by=id))
#
# question_id = db.Column(db.Integer, db.ForeignKey('questions.id'))
# question = db.relationship("Question", backref=db.backref('essays', order_by=id))
#
# created = db.Column(db.DateTime(timezone=True), default=datetime.utcnow)
# updated = db.Column(db.DateTime(timezone=True), onupdate=datetime.utcnow)
. Output only the next line. | self.populate_obj(e) |
Using the snippet: <|code_start|> actual_score = FloatField('Score (optional)', [Optional()], description="The score the essay got, if it has a score.")
info = TextAreaField("Additional Info (optional)", [Optional()], description="Any additional info you want to store with this essay.")
def save(self, question):
e = Essay(question=question)
self.populate_obj(e)
db.session.add(e)
db.session.commit()
class EssayDialect(csv.Dialect):
quoting = csv.QUOTE_MINIMAL
delimiter = ","
quotechar = "\""
lineterminator = "\n"
class EssayUploadForm(Form):
upload = FileField('File', [FileRequired(), FileAllowed(['csv'], 'CSV files only!')], description="The csv file with essays you want to upload.")
def save(self, question, csvfile):
csvfile.seek(0)
reader = csv.reader(csvfile, EssayDialect)
for i, row in enumerate(reader):
if i == 0:
continue
score = row[-1]
text = ",".join(row[:-1])
if len(score) == 0:
<|code_end|>
, determine the next line of code. You have imports:
from flask_wtf import Form
from werkzeug import secure_filename
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import FloatField, IntegerField, TextField, StringField, TextAreaField
from wtforms.validators import Required, Optional
from core.database.models import Question, Essay
from flask.ext.login import current_user
from app import db
from app import db
from app import db
import csv
and context (class names, function names, or code) available:
# Path: core/database/models.py
# class Question(db.Model):
# __tablename__ = 'questions'
#
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(STRING_MAX))
# description = db.Column(db.Text)
# prompt = db.Column(db.Text)
# user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#
# user = db.relationship("User", backref=db.backref('questions', order_by=id))
#
# created = db.Column(db.DateTime(timezone=True), default=datetime.utcnow)
# updated = db.Column(db.DateTime(timezone=True), onupdate=datetime.utcnow)
#
# class Essay(db.Model):
# __tablename__ = 'essays'
#
# id = db.Column(db.Integer, primary_key=True)
# text = db.Column(db.Text)
# actual_score = db.Column(db.Float)
# info = db.Column(db.Text)
#
# predicted_score = db.Column(db.Float)
# model_id = db.Column(db.Integer, db.ForeignKey('models.id'))
# model = db.relationship("Model", backref=db.backref('essays', order_by=id))
#
# question_id = db.Column(db.Integer, db.ForeignKey('questions.id'))
# question = db.relationship("Question", backref=db.backref('essays', order_by=id))
#
# created = db.Column(db.DateTime(timezone=True), default=datetime.utcnow)
# updated = db.Column(db.DateTime(timezone=True), onupdate=datetime.utcnow)
. Output only the next line. | score = None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.