Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
class DispatcherClient:
def __init__(self, redis: Redis):
self._redis = redis
self._q = asyncio.Queue()
async def run(self):
"""
Run the dispatcher.
Continually publishes enqueued changes to a Redis channel.
"""
try:
while True:
json_string = await self._q.get()
await self._redis.publish("channel:dispatch", json_string)
except CancelledError:
pass
def enqueue_change(
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import json
from asyncio import CancelledError
from typing import Sequence, Union
from aioredis import Redis
from virtool.dispatcher.operations import Operation
and context (functions, classes, or occasionally code) from other files:
# Path: virtool/dispatcher/operations.py
# INSERT: Operation = "insert"
# UPDATE: Operation = "update"
# DELETE: Operation = "delete"
. Output only the next line. | self, interface: str, operation: Operation, id_list: Sequence[Union[str, int]] |
Given snippet: <|code_start|> test_dir = tmp_path / "samples" / "foo" / "analysis" / "bar"
test_dir.mkdir(parents=True, exist_ok=True)
test_dir.joinpath("assembly.fa").write_text("FASTA file")
test_dir.joinpath("hmm.tsv").write_text("HMM file")
test_dir.joinpath("unmapped_otus.fq").write_text("FASTQ file")
client.app["config"].data_path = tmp_path
await dbi.analyses.insert_one(
{"_id": "bar", "workflow": "nuvs", "sample": {"id": "foo"}}
)
task = Task(
id=1,
complete=False,
context={},
count=0,
progress=0,
step="store_nuvs_files",
type="store_nuvs_file_task",
created_at=static_time.datetime,
)
async with pg_session as session:
session.add(task)
await session.commit()
store_nuvs_task = StoreNuvsFilesTask(client.app, 1)
await store_nuvs_task.run()
async with pg_session as session:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from sqlalchemy import select
from virtool.analyses.models import AnalysisFile
from virtool.analyses.tasks import StoreNuvsFilesTask
from virtool.tasks.models import Task
and context:
# Path: virtool/analyses/models.py
# class AnalysisFile(Base):
# """
# SQL model to store new analysis files
#
# """
#
# __tablename__ = "analysis_files"
#
# id = Column(Integer, primary_key=True)
# analysis = Column(String)
# description = Column(String)
# format = Column(Enum(AnalysisFormat))
# name = Column(String)
# name_on_disk = Column(String, unique=True)
# size = Column(BigInteger)
# uploaded_at = Column(DateTime)
which might include code, classes, or functions. Output only the next line. | assert (await session.execute(select(AnalysisFile))).scalars().all() == snapshot |
Based on the snippet: <|code_start|>
MINIMUM_MONGO_VERSION = "3.6.0"
logger = getLogger("mongo")
async def connect(
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from logging import getLogger
from typing import Callable, List
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import ASCENDING, DESCENDING
from pymongo.errors import ServerSelectionTimeoutError
from semver import VersionInfo
from virtool.config.cls import Config
from virtool.db.core import DB
and context (classes, functions, sometimes code) from other files:
# Path: virtool/config/cls.py
# class Config:
# db_connection_string: str
# db_name: str
# dev: bool
# postgres_connection_string: str
# redis_connection_string: str
# b2c_client_id: str = None
# b2c_client_secret: str = None
# b2c_tenant: str = None
# b2c_user_flow: str = None
# base_url: str = ""
# data_path: Path = None
# fake: bool = False
# fake_path: Path = None
# force_version: str = None
# host: str = None
# no_check_files: bool = False
# no_check_db: bool = False
# no_fetching: bool = False
# no_sentry: bool = False
# port: int = 9950
# proxy: str = None
# use_b2c: bool = False
# verbose: bool = False
# sentry_dsn: str = "https://9a2f8d1a3f7a431e873207a70ef3d44d:ca6db07b82934005beceae93560a6794@sentry.io/220532"
. Output only the next line. | config: Config, enqueue_change: Callable[[str, str, List[str]], None] |
Predict the next line for this snippet: <|code_start|> self.db = app["db"]
self.pg = app["pg"]
self.settings: Settings = app["settings"]
self.data_path = app["config"].data_path
async def analysis(
self,
index_id: str = None,
ref_id: str = None,
subtractions: List[str] = None,
sample_id: str = None,
workflow: str = "test",
ready=False,
):
id_ = self.fake.get_mongo_id()
document = {
"_id": id_,
"workflow": workflow,
"created_at": timestamp(),
"ready": ready,
"job": {"id": self.job_id},
"index": {"id": index_id},
"user": {"id": self.user_id},
"sample": {"id": sample_id},
"reference": {"id": ref_id},
"subtractions": subtractions,
}
if ready:
<|code_end|>
with the help of current file imports:
import logging
import shutil
import aiofiles
import virtool.indexes.db
import virtool.jobs.db
import virtool.subtractions.db
import yaml
from dataclasses import dataclass
from operator import itemgetter
from types import SimpleNamespace
from typing import List
from virtool.analyses.files import create_analysis_file
from virtool.example import example_path
from virtool.fake.wrapper import FakerWrapper
from virtool.hmm.fake import create_fake_hmms
from virtool.indexes.files import create_index_file
from virtool.jobs.utils import JobRights
from virtool.otus.fake import create_fake_otus
from virtool.references.db import create_document
from virtool.samples.fake import create_fake_sample
from virtool.settings.db import Settings
from virtool.subtractions.fake import (
create_fake_fasta_upload,
create_fake_finalized_subtraction,
)
from virtool.types import App
from virtool.utils import timestamp
and context from other files:
# Path: virtool/analyses/files.py
# async def create_analysis_file(
# pg: AsyncEngine, analysis_id: str, analysis_format: str, name: str, size: int = None
# ) -> Dict[str, any]:
# """
# Create a row in the `analysis_files` SQL table that represents an analysis result file.
#
# :param pg: PostgreSQL AsyncEngine object
# :param analysis_id: ID that corresponds to a parent analysis
# :param analysis_format: Format of the analysis result file
# :param name: Name of the analysis result file
# :param size: Size of the analysis result file
# :return: A dictionary representation of the newly created row
# """
# async with AsyncSession(pg) as session:
# analysis_file = AnalysisFile(
# name=name, analysis=analysis_id, format=analysis_format, size=size
# )
#
# session.add(analysis_file)
#
# await session.flush()
#
# analysis_file.name_on_disk = f"{analysis_file.id}-{analysis_file.name}"
#
# analysis_file = analysis_file.to_dict()
#
# await session.commit()
#
# return analysis_file
#
# Path: virtool/fake/wrapper.py
# class FakerWrapper:
# def __init__(self):
# self.fake = Faker()
# self.fake.seed_instance(0)
# self.fake.add_provider(address)
# self.fake.add_provider(misc)
# self.fake.add_provider(lorem)
# self.fake.add_provider(python)
# self.fake.add_provider(date_time)
# self.fake.add_provider(profile)
#
# self.country = self.fake.country
#
# self.text = self.fake.text
# self.word = self.fake.word
# self.words = self.fake.words
#
# self.integer = self.fake.pyint
# self.list = self.fake.pylist
# self.boolean = self.fake.pybool
# self.profile = self.fake.profile
# self.date_time = self.fake.date_time
# self.random_element = self.fake.random_element
#
# def get_mongo_id(self) -> str:
# """
# Create a predictable, fake ID for MongoDB that imitates Virtool IDs.
#
# :return: a fake MongoDB ID
#
# """
# return self.fake.password(length=8, special_chars=False)
#
# Path: virtool/types.py
, which may contain function names, class names, or code. Output only the next line. | file_ = await create_analysis_file( |
Given snippet: <|code_start|>
INDEX_FILES = (
"reference.fa.gz",
"reference.1.bt2",
"reference.2.bt2",
"reference.3.bt2",
"reference.4.bt2",
"reference.rev.1.bt2",
"reference.rev.2.bt2",
)
@dataclass
class WorkflowTestCase:
"""A collection of records required for a particular workflow run."""
job: SimpleNamespace
workflow: str
analysis: SimpleNamespace = None
index: SimpleNamespace = None
reference: SimpleNamespace = None
sample: SimpleNamespace = None
subtractions: List[SimpleNamespace] = None
class TestCaseDataFactory:
"""Initialize the database with fake data for a test case."""
def __init__(self, app: App, user_id: str, job_id: str = None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import shutil
import aiofiles
import virtool.indexes.db
import virtool.jobs.db
import virtool.subtractions.db
import yaml
from dataclasses import dataclass
from operator import itemgetter
from types import SimpleNamespace
from typing import List
from virtool.analyses.files import create_analysis_file
from virtool.example import example_path
from virtool.fake.wrapper import FakerWrapper
from virtool.hmm.fake import create_fake_hmms
from virtool.indexes.files import create_index_file
from virtool.jobs.utils import JobRights
from virtool.otus.fake import create_fake_otus
from virtool.references.db import create_document
from virtool.samples.fake import create_fake_sample
from virtool.settings.db import Settings
from virtool.subtractions.fake import (
create_fake_fasta_upload,
create_fake_finalized_subtraction,
)
from virtool.types import App
from virtool.utils import timestamp
and context:
# Path: virtool/analyses/files.py
# async def create_analysis_file(
# pg: AsyncEngine, analysis_id: str, analysis_format: str, name: str, size: int = None
# ) -> Dict[str, any]:
# """
# Create a row in the `analysis_files` SQL table that represents an analysis result file.
#
# :param pg: PostgreSQL AsyncEngine object
# :param analysis_id: ID that corresponds to a parent analysis
# :param analysis_format: Format of the analysis result file
# :param name: Name of the analysis result file
# :param size: Size of the analysis result file
# :return: A dictionary representation of the newly created row
# """
# async with AsyncSession(pg) as session:
# analysis_file = AnalysisFile(
# name=name, analysis=analysis_id, format=analysis_format, size=size
# )
#
# session.add(analysis_file)
#
# await session.flush()
#
# analysis_file.name_on_disk = f"{analysis_file.id}-{analysis_file.name}"
#
# analysis_file = analysis_file.to_dict()
#
# await session.commit()
#
# return analysis_file
#
# Path: virtool/fake/wrapper.py
# class FakerWrapper:
# def __init__(self):
# self.fake = Faker()
# self.fake.seed_instance(0)
# self.fake.add_provider(address)
# self.fake.add_provider(misc)
# self.fake.add_provider(lorem)
# self.fake.add_provider(python)
# self.fake.add_provider(date_time)
# self.fake.add_provider(profile)
#
# self.country = self.fake.country
#
# self.text = self.fake.text
# self.word = self.fake.word
# self.words = self.fake.words
#
# self.integer = self.fake.pyint
# self.list = self.fake.pylist
# self.boolean = self.fake.pybool
# self.profile = self.fake.profile
# self.date_time = self.fake.date_time
# self.random_element = self.fake.random_element
#
# def get_mongo_id(self) -> str:
# """
# Create a predictable, fake ID for MongoDB that imitates Virtool IDs.
#
# :return: a fake MongoDB ID
#
# """
# return self.fake.password(length=8, special_chars=False)
#
# Path: virtool/types.py
which might include code, classes, or functions. Output only the next line. | self.fake = app["fake"] if "fake" in app else FakerWrapper() |
Using the snippet: <|code_start|>logger = logging.getLogger(__name__)
INDEX_FILES = (
"reference.fa.gz",
"reference.1.bt2",
"reference.2.bt2",
"reference.3.bt2",
"reference.4.bt2",
"reference.rev.1.bt2",
"reference.rev.2.bt2",
)
@dataclass
class WorkflowTestCase:
"""A collection of records required for a particular workflow run."""
job: SimpleNamespace
workflow: str
analysis: SimpleNamespace = None
index: SimpleNamespace = None
reference: SimpleNamespace = None
sample: SimpleNamespace = None
subtractions: List[SimpleNamespace] = None
class TestCaseDataFactory:
"""Initialize the database with fake data for a test case."""
<|code_end|>
, determine the next line of code. You have imports:
import logging
import shutil
import aiofiles
import virtool.indexes.db
import virtool.jobs.db
import virtool.subtractions.db
import yaml
from dataclasses import dataclass
from operator import itemgetter
from types import SimpleNamespace
from typing import List
from virtool.analyses.files import create_analysis_file
from virtool.example import example_path
from virtool.fake.wrapper import FakerWrapper
from virtool.hmm.fake import create_fake_hmms
from virtool.indexes.files import create_index_file
from virtool.jobs.utils import JobRights
from virtool.otus.fake import create_fake_otus
from virtool.references.db import create_document
from virtool.samples.fake import create_fake_sample
from virtool.settings.db import Settings
from virtool.subtractions.fake import (
create_fake_fasta_upload,
create_fake_finalized_subtraction,
)
from virtool.types import App
from virtool.utils import timestamp
and context (class names, function names, or code) available:
# Path: virtool/analyses/files.py
# async def create_analysis_file(
# pg: AsyncEngine, analysis_id: str, analysis_format: str, name: str, size: int = None
# ) -> Dict[str, any]:
# """
# Create a row in the `analysis_files` SQL table that represents an analysis result file.
#
# :param pg: PostgreSQL AsyncEngine object
# :param analysis_id: ID that corresponds to a parent analysis
# :param analysis_format: Format of the analysis result file
# :param name: Name of the analysis result file
# :param size: Size of the analysis result file
# :return: A dictionary representation of the newly created row
# """
# async with AsyncSession(pg) as session:
# analysis_file = AnalysisFile(
# name=name, analysis=analysis_id, format=analysis_format, size=size
# )
#
# session.add(analysis_file)
#
# await session.flush()
#
# analysis_file.name_on_disk = f"{analysis_file.id}-{analysis_file.name}"
#
# analysis_file = analysis_file.to_dict()
#
# await session.commit()
#
# return analysis_file
#
# Path: virtool/fake/wrapper.py
# class FakerWrapper:
# def __init__(self):
# self.fake = Faker()
# self.fake.seed_instance(0)
# self.fake.add_provider(address)
# self.fake.add_provider(misc)
# self.fake.add_provider(lorem)
# self.fake.add_provider(python)
# self.fake.add_provider(date_time)
# self.fake.add_provider(profile)
#
# self.country = self.fake.country
#
# self.text = self.fake.text
# self.word = self.fake.word
# self.words = self.fake.words
#
# self.integer = self.fake.pyint
# self.list = self.fake.pylist
# self.boolean = self.fake.pybool
# self.profile = self.fake.profile
# self.date_time = self.fake.date_time
# self.random_element = self.fake.random_element
#
# def get_mongo_id(self) -> str:
# """
# Create a predictable, fake ID for MongoDB that imitates Virtool IDs.
#
# :return: a fake MongoDB ID
#
# """
# return self.fake.password(length=8, special_chars=False)
#
# Path: virtool/types.py
. Output only the next line. | def __init__(self, app: App, user_id: str, job_id: str = None): |
Predict the next line after this snippet: <|code_start|> mocker.patch("virtool.references.tasks.UpdateRemoteReferenceTask")
m_add_task = mocker.patch(
"virtool.tasks.client.TasksClient.add", make_mocked_coro({"id": "task"})
)
mocker.patch("aiojobs.aiohttp.spawn", make_mocked_coro())
m_update = mocker.patch(
"virtool.references.db.update",
make_mocked_coro(({"id": "bar"}, {"id": "update", "created_at": "time"})),
)
resp = await client.post("/refs/foo/updates")
id_exists.assert_called_with(client.db.references, "foo")
if not id_exists:
await resp_is.not_found(resp)
return
if not check_ref_right:
await resp_is.insufficient_rights(resp)
return
if error == "400":
await resp_is.bad_request(resp, "Target release does not exist")
return
m_add_task.assert_called_with(
<|code_end|>
using the current file's imports:
import pytest
from aiohttp.test_utils import make_mocked_coro
from aiohttp.web import Request
from virtool.references.tasks import UpdateRemoteReferenceTask
and any relevant context from other files:
# Path: virtool/references/tasks.py
# class UpdateRemoteReferenceTask(Task):
# task_type = "update_remote_reference"
#
# def __init__(self, *args):
# super().__init__(*args)
#
# self.steps = [
# self.download_and_extract,
# self.update_otus,
# self.create_history,
# self.remove_otus,
# self.update_reference,
# ]
#
# async def download_and_extract(self):
# url = self.context["release"]["download_url"]
# file_size = self.context["release"]["size"]
#
# tracker = await self.get_tracker(file_size)
#
# try:
# with get_temp_dir() as tempdir:
# download_path = Path(tempdir) / "reference.tar.gz"
#
# await download_file(self.app, url, download_path, tracker.add)
#
# self.intermediate["update_data"] = await self.run_in_thread(
# load_reference_file, download_path
# )
#
# except (aiohttp.ClientConnectorError, virtool.errors.GitHubError):
# return await self.error("Could not download reference data")
#
# await virtool.tasks.pg.update(self.pg, self.id, step="download_and_extract")
#
# async def update_otus(self):
# update_data = self.intermediate["update_data"]
#
# tracker = await self.get_tracker(len(update_data["otus"]))
#
# # The remote ids in the update otus.
# otu_ids_in_update = {otu["_id"] for otu in update_data["otus"]}
#
# updated_list = list()
#
# for otu in update_data["otus"]:
# old_or_id = await update_joined_otu(
# self.db,
# otu,
# self.context["created_at"],
# self.context["ref_id"],
# self.context["user_id"],
# )
#
# if old_or_id is not None:
# updated_list.append(old_or_id)
#
# await tracker.add(1)
#
# self.intermediate.update(
# {"otu_ids_in_update": otu_ids_in_update, "updated_list": updated_list}
# )
#
# await virtool.tasks.pg.update(self.pg, self.id, step="update_otus")
#
# async def create_history(self):
# updated_list = self.intermediate["updated_list"]
#
# tracker = await self.get_tracker(len(updated_list))
#
# for old_or_id in updated_list:
# try:
# otu_id = old_or_id["_id"]
# old = old_or_id
# except TypeError:
# otu_id = old_or_id
# old = None
#
# await insert_change(
# self.app,
# otu_id,
# "update" if old else "remote",
# self.context["user_id"],
# old,
# )
#
# await tracker.add(1)
#
# await virtool.tasks.pg.update(self.pg, self.id, step="create_history")
#
# async def remove_otus(self):
# # Delete OTUs with remote ids that were not in the update.
# to_delete = await self.db.otus.distinct(
# "_id",
# {
# "reference.id": self.context["ref_id"],
# "remote.id": {"$nin": list(self.intermediate["otu_ids_in_update"])},
# },
# )
#
# tracker = await self.get_tracker(len(to_delete))
#
# for otu_id in to_delete:
# await virtool.otus.db.remove(self.app, otu_id, self.context["user_id"])
#
# await tracker.add(1)
#
# await virtool.tasks.pg.update(self.pg, self.id, step="remove_otus")
#
# async def update_reference(self):
# tracker = await self.get_tracker()
# ref_id = self.context["ref_id"]
# release = self.context["release"]
#
# await self.db.references.update_one(
# {"_id": ref_id, "updates.id": release["id"]},
# {
# "$set": {
# "installed": create_update_subdocument(
# release, True, self.context["user_id"]
# ),
# "updates.$.ready": True,
# }
# },
# )
#
# await fetch_and_update_release(self.app, ref_id)
#
# await self.db.references.update_one(
# {"_id": ref_id}, {"$set": {"updating": False}}
# )
#
# await virtool.tasks.pg.update(
# self.pg, self.id, progress=tracker.step_completed, step="update_reference"
# )
. Output only the next line. | UpdateRemoteReferenceTask, |
Next line prediction: <|code_start|>
assert await dbi.jobs.find_one() == snapshot
@pytest.mark.parametrize("with_job_id", [False, True])
async def test_create(
with_job_id, mocker, snapshot, dbi, test_random_alphanumeric, static_time
):
mocker.patch("virtool.utils.generate_key", return_value=("key", "hashed"))
rights = JobRights()
rights.samples.can_read("foo")
rights.samples.can_modify("foo")
rights.samples.can_remove("foo")
if with_job_id:
await create(
dbi, "create_sample", {"sample_id": "foo"}, "bob", rights, job_id="bar"
)
else:
await create(dbi, "create_sample", {"sample_id": "foo"}, "bob", rights)
assert await dbi.jobs.find_one() == snapshot
async def test_acquire(dbi, mocker):
mocker.patch("virtool.utils.generate_key", return_value=("key", "hashed"))
await dbi.jobs.insert_one({"_id": "foo", "acquired": False, "key": None})
<|code_end|>
. Use current file imports:
(from unittest.mock import call
from virtool.jobs.client import JobsClient
from virtool.jobs.db import acquire, create, force_delete_jobs
from virtool.jobs.utils import JobRights
import pytest
import virtool.jobs.db)
and context including class names, function names, or small code snippets from other files:
# Path: virtool/jobs/db.py
# async def acquire(db, job_id: str) -> Dict[str, Any]:
# """
# Set the `started` field on a job to `True` and return the complete document.
#
# :param db: the application database object
# :param job_id: the ID of the job to start
# :return: the complete job document
#
# """
# key, hashed = virtool.utils.generate_key()
#
# document = await db.jobs.find_one_and_update(
# {"_id": job_id},
# {"$set": {"acquired": True, "key": hashed}},
# projection=PROJECTION,
# )
#
# document["key"] = key
#
# return virtool.utils.base_processor(document)
#
# async def create(
# db,
# workflow: str,
# job_args: Dict[str, Any],
# user_id: str,
# rights: JobRights,
# job_id: Optional[str] = None,
# ) -> Dict[str, Any]:
# """
# Create, insert, and return a job document.
#
# :param db: the application database object
# :param workflow: the name of the workflow to run
# :param job_args: the arguments required to run the job
# :param user_id: the user that started the job
# :param rights: the rights the job will have on Virtool resources
# :param job_id: an optional ID to use for the new job
#
# """
# document = {
# "acquired": False,
# "workflow": workflow,
# "args": job_args,
# "key": None,
# "rights": rights.as_dict(),
# "state": "waiting",
# "status": [
# {
# "state": "waiting",
# "stage": None,
# "error": None,
# "progress": 0,
# "timestamp": virtool.utils.timestamp(),
# }
# ],
# "user": {"id": user_id},
# }
#
# if job_id:
# document["_id"] = job_id
#
# document = await db.jobs.insert_one(document)
#
# return document
#
# async def force_delete_jobs(app: App):
# """
# Force cancellation and deletion of all jobs.
#
# :param app: the application object
#
# """
# job_ids = await app["db"].jobs.distinct("_id")
#
# await gather(*[app["jobs"].cancel(job_id) for job_id in job_ids])
# await gather(*[delete(app, job_id) for job_id in job_ids])
. Output only the next line. | result = await acquire(dbi, "foo") |
Given the code snippet: <|code_start|> "state": "waiting",
"status": [
{
"state": "running",
"stage": "foo",
"error": None,
"progress": 0.33,
"timestamp": static_time.datetime,
}
],
}
)
await virtool.jobs.db.cancel(dbi, "foo")
assert await dbi.jobs.find_one() == snapshot
@pytest.mark.parametrize("with_job_id", [False, True])
async def test_create(
with_job_id, mocker, snapshot, dbi, test_random_alphanumeric, static_time
):
mocker.patch("virtool.utils.generate_key", return_value=("key", "hashed"))
rights = JobRights()
rights.samples.can_read("foo")
rights.samples.can_modify("foo")
rights.samples.can_remove("foo")
if with_job_id:
<|code_end|>
, generate the next line using the imports in this file:
from unittest.mock import call
from virtool.jobs.client import JobsClient
from virtool.jobs.db import acquire, create, force_delete_jobs
from virtool.jobs.utils import JobRights
import pytest
import virtool.jobs.db
and context (functions, classes, or occasionally code) from other files:
# Path: virtool/jobs/db.py
# async def acquire(db, job_id: str) -> Dict[str, Any]:
# """
# Set the `started` field on a job to `True` and return the complete document.
#
# :param db: the application database object
# :param job_id: the ID of the job to start
# :return: the complete job document
#
# """
# key, hashed = virtool.utils.generate_key()
#
# document = await db.jobs.find_one_and_update(
# {"_id": job_id},
# {"$set": {"acquired": True, "key": hashed}},
# projection=PROJECTION,
# )
#
# document["key"] = key
#
# return virtool.utils.base_processor(document)
#
# async def create(
# db,
# workflow: str,
# job_args: Dict[str, Any],
# user_id: str,
# rights: JobRights,
# job_id: Optional[str] = None,
# ) -> Dict[str, Any]:
# """
# Create, insert, and return a job document.
#
# :param db: the application database object
# :param workflow: the name of the workflow to run
# :param job_args: the arguments required to run the job
# :param user_id: the user that started the job
# :param rights: the rights the job will have on Virtool resources
# :param job_id: an optional ID to use for the new job
#
# """
# document = {
# "acquired": False,
# "workflow": workflow,
# "args": job_args,
# "key": None,
# "rights": rights.as_dict(),
# "state": "waiting",
# "status": [
# {
# "state": "waiting",
# "stage": None,
# "error": None,
# "progress": 0,
# "timestamp": virtool.utils.timestamp(),
# }
# ],
# "user": {"id": user_id},
# }
#
# if job_id:
# document["_id"] = job_id
#
# document = await db.jobs.insert_one(document)
#
# return document
#
# async def force_delete_jobs(app: App):
# """
# Force cancellation and deletion of all jobs.
#
# :param app: the application object
#
# """
# job_ids = await app["db"].jobs.distinct("_id")
#
# await gather(*[app["jobs"].cancel(job_id) for job_id in job_ids])
# await gather(*[delete(app, job_id) for job_id in job_ids])
. Output only the next line. | await create( |
Using the snippet: <|code_start|> await create(
dbi, "create_sample", {"sample_id": "foo"}, "bob", rights, job_id="bar"
)
else:
await create(dbi, "create_sample", {"sample_id": "foo"}, "bob", rights)
assert await dbi.jobs.find_one() == snapshot
async def test_acquire(dbi, mocker):
mocker.patch("virtool.utils.generate_key", return_value=("key", "hashed"))
await dbi.jobs.insert_one({"_id": "foo", "acquired": False, "key": None})
result = await acquire(dbi, "foo")
assert await dbi.jobs.find_one() == {
"_id": "foo",
"acquired": True,
"key": "hashed",
}
assert result == {"id": "foo", "acquired": True, "key": "key"}
async def test_force_delete_jobs(dbi, mocker, tmp_path):
app = {"db": dbi, "jobs": mocker.Mock(spec=JobsClient)}
await dbi.jobs.insert_many([{"_id": "foo"}, {"_id": "bar"}])
<|code_end|>
, determine the next line of code. You have imports:
from unittest.mock import call
from virtool.jobs.client import JobsClient
from virtool.jobs.db import acquire, create, force_delete_jobs
from virtool.jobs.utils import JobRights
import pytest
import virtool.jobs.db
and context (class names, function names, or code) available:
# Path: virtool/jobs/db.py
# async def acquire(db, job_id: str) -> Dict[str, Any]:
# """
# Set the `started` field on a job to `True` and return the complete document.
#
# :param db: the application database object
# :param job_id: the ID of the job to start
# :return: the complete job document
#
# """
# key, hashed = virtool.utils.generate_key()
#
# document = await db.jobs.find_one_and_update(
# {"_id": job_id},
# {"$set": {"acquired": True, "key": hashed}},
# projection=PROJECTION,
# )
#
# document["key"] = key
#
# return virtool.utils.base_processor(document)
#
# async def create(
# db,
# workflow: str,
# job_args: Dict[str, Any],
# user_id: str,
# rights: JobRights,
# job_id: Optional[str] = None,
# ) -> Dict[str, Any]:
# """
# Create, insert, and return a job document.
#
# :param db: the application database object
# :param workflow: the name of the workflow to run
# :param job_args: the arguments required to run the job
# :param user_id: the user that started the job
# :param rights: the rights the job will have on Virtool resources
# :param job_id: an optional ID to use for the new job
#
# """
# document = {
# "acquired": False,
# "workflow": workflow,
# "args": job_args,
# "key": None,
# "rights": rights.as_dict(),
# "state": "waiting",
# "status": [
# {
# "state": "waiting",
# "stage": None,
# "error": None,
# "progress": 0,
# "timestamp": virtool.utils.timestamp(),
# }
# ],
# "user": {"id": user_id},
# }
#
# if job_id:
# document["_id"] = job_id
#
# document = await db.jobs.insert_one(document)
#
# return document
#
# async def force_delete_jobs(app: App):
# """
# Force cancellation and deletion of all jobs.
#
# :param app: the application object
#
# """
# job_ids = await app["db"].jobs.distinct("_id")
#
# await gather(*[app["jobs"].cancel(job_id) for job_id in job_ids])
# await gather(*[delete(app, job_id) for job_id in job_ids])
. Output only the next line. | await force_delete_jobs(app) |
Given the following code snippet before the placeholder: <|code_start|>
class UpdateUserDocumentsTask(Task):
"""
Update user documents that don't contain a "handle" field.
For B2C users with b2c_given_name and b2c_family_name included in their user document, generate handle.
For all other users use existing _id values as handle.
"""
task_type = "update_user_documents"
<|code_end|>
, predict the next line using imports from the current file:
from virtool.tasks.pg import update
from virtool.tasks.task import Task
from virtool.types import App
from virtool.users.db import PROJECTION
import virtool.users.db
and context including class names, function names, and sometimes code from other files:
# Path: virtool/types.py
. Output only the next line. | def __init__(self, app: App, task_id: int): |
Given the code snippet: <|code_start|> Create a NuVs BLAST record for the sequence associated with a specific analysis
ID and sequence index.
A BLAST task will be spawned that runs a BLAST search against NCBI and
populates the database with result. The analysis and BLAST records are
updated as the task proceeds.
:param analysis_id: the ID for the analysis to create BLAST for
:param sequence_index: the index of the sequence being BLASTed.
:return: the dictionary representation of the BLAST record.
"""
timestamp = virtool.utils.timestamp()
async with AsyncSession(self._pg) as session:
await self._remove_nuvs_blast(session, analysis_id, sequence_index)
await session.flush()
blast = NuVsBlast(
analysis_id=analysis_id,
created_at=timestamp,
last_checked_at=timestamp,
ready=False,
sequence_index=sequence_index,
updated_at=timestamp,
)
session.add(blast)
await session.flush()
await self._tasks.add(
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from typing import List, Optional
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from virtool.blast.models import NuVsBlast
from virtool.blast.task import BLASTTask
from virtool.tasks.client import TasksClient
from virtool.types import Document
import virtool.utils
and context (functions, classes, or occasionally code) from other files:
# Path: virtool/blast/task.py
# class BLASTTask(Task):
#
# """Run a BLAST search against NCBI."""
#
# task_type = "blast"
#
# def __init__(self, app, task_id: str):
# super().__init__(app, task_id)
#
# self.analysis_id = None
# self.sequence_index = None
#
# self.error = None
# self.interval = 3
# self.ready = False
# self.result = None
# self.rid = None
# self.steps = [self.request, self.wait]
#
# async def init_db(self):
# await super().init_db()
#
# self.analysis_id = self.context["analysis_id"]
# self.sequence_index = self.context["sequence_index"]
#
# async def request(self):
# document = await get_data_from_app(self.app).analyses.get_by_id(
# self.analysis_id
# )
#
# sequence = find_nuvs_sequence_by_index(document, self.sequence_index)
#
# rid, _ = await virtool.blast.utils.initialize_ncbi_blast(
# self.app["config"], sequence
# )
#
# self.rid = rid
#
# await self._update(False, None, None)
#
# async def wait(self):
# try:
# while not self.ready:
# await self._sleep()
#
# self.ready = await virtool.blast.utils.check_rid(
# self.app["config"], self.rid
# )
#
# logger.debug(f"Checked BLAST {self.rid} ({self.interval}s)")
#
# if self.ready:
# try:
# result_json = await virtool.blast.utils.get_ncbi_blast_result(
# self.app["config"], self.app["run_in_process"], self.rid
# )
# except BadZipFile:
# await self._update(
# False, None, error="Unable to interpret NCBI result"
# )
# return
#
# logger.info(f"Retrieved result for BLAST {self.rid}")
# result = virtool.blast.utils.format_blast_content(result_json)
#
# return await self._update(True, result, None)
#
# await self._update(False, None, None)
#
# except asyncio.CancelledError:
# await get_data_from_app(self.app).blast.remove_nuvs_blast(
# self.analysis_id, self.sequence_index
# )
#
# logger.info(f"Removed BLAST due to cancellation: {self.rid}")
#
# async def _sleep(self):
# """
# Sleep for the current interval and increase the interval by 5 seconds after
# sleeping.
#
# """
# await asyncio.sleep(self.interval)
# self.interval += 5
#
# async def _update(self, ready: bool, result: Optional[dict], error: Optional[str]):
# """
# Update the BLAST data. Returns the BLAST data and the complete analysis
# document.
#
# :param ready: indicates whether the BLAST request is complete
# :param result: the formatted result of a successful BLAST request
# :param error: and error message to add to the BLAST record
# :return: the BLAST data and the complete analysis document
#
# """
# self.result = result
#
# if ready is None:
# self.ready = await virtool.blast.utils.check_rid(
# self.app["config"], self.rid
# )
# else:
# self.ready = ready
#
# await get_data_from_app(self.app).blast.update_nuvs_blast(
# self.analysis_id,
# self.sequence_index,
# self.error,
# virtool.utils.timestamp(),
# self.rid,
# self.ready,
# self.result,
# )
#
# Path: virtool/types.py
. Output only the next line. | BLASTTask, |
Predict the next line after this snippet: <|code_start|>
class BLASTData:
"""
A data layer domain for NuVs BLAST data.
"""
def __init__(self, db, pg: AsyncEngine, tasks: TasksClient):
self._db = db
self._pg = pg
self._tasks = tasks
async def create_nuvs_blast(
self, analysis_id: str, sequence_index: int
<|code_end|>
using the current file's imports:
from datetime import datetime
from typing import List, Optional
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from virtool.blast.models import NuVsBlast
from virtool.blast.task import BLASTTask
from virtool.tasks.client import TasksClient
from virtool.types import Document
import virtool.utils
and any relevant context from other files:
# Path: virtool/blast/task.py
# class BLASTTask(Task):
#
# """Run a BLAST search against NCBI."""
#
# task_type = "blast"
#
# def __init__(self, app, task_id: str):
# super().__init__(app, task_id)
#
# self.analysis_id = None
# self.sequence_index = None
#
# self.error = None
# self.interval = 3
# self.ready = False
# self.result = None
# self.rid = None
# self.steps = [self.request, self.wait]
#
# async def init_db(self):
# await super().init_db()
#
# self.analysis_id = self.context["analysis_id"]
# self.sequence_index = self.context["sequence_index"]
#
# async def request(self):
# document = await get_data_from_app(self.app).analyses.get_by_id(
# self.analysis_id
# )
#
# sequence = find_nuvs_sequence_by_index(document, self.sequence_index)
#
# rid, _ = await virtool.blast.utils.initialize_ncbi_blast(
# self.app["config"], sequence
# )
#
# self.rid = rid
#
# await self._update(False, None, None)
#
# async def wait(self):
# try:
# while not self.ready:
# await self._sleep()
#
# self.ready = await virtool.blast.utils.check_rid(
# self.app["config"], self.rid
# )
#
# logger.debug(f"Checked BLAST {self.rid} ({self.interval}s)")
#
# if self.ready:
# try:
# result_json = await virtool.blast.utils.get_ncbi_blast_result(
# self.app["config"], self.app["run_in_process"], self.rid
# )
# except BadZipFile:
# await self._update(
# False, None, error="Unable to interpret NCBI result"
# )
# return
#
# logger.info(f"Retrieved result for BLAST {self.rid}")
# result = virtool.blast.utils.format_blast_content(result_json)
#
# return await self._update(True, result, None)
#
# await self._update(False, None, None)
#
# except asyncio.CancelledError:
# await get_data_from_app(self.app).blast.remove_nuvs_blast(
# self.analysis_id, self.sequence_index
# )
#
# logger.info(f"Removed BLAST due to cancellation: {self.rid}")
#
# async def _sleep(self):
# """
# Sleep for the current interval and increase the interval by 5 seconds after
# sleeping.
#
# """
# await asyncio.sleep(self.interval)
# self.interval += 5
#
# async def _update(self, ready: bool, result: Optional[dict], error: Optional[str]):
# """
# Update the BLAST data. Returns the BLAST data and the complete analysis
# document.
#
# :param ready: indicates whether the BLAST request is complete
# :param result: the formatted result of a successful BLAST request
# :param error: and error message to add to the BLAST record
# :return: the BLAST data and the complete analysis document
#
# """
# self.result = result
#
# if ready is None:
# self.ready = await virtool.blast.utils.check_rid(
# self.app["config"], self.rid
# )
# else:
# self.ready = ready
#
# await get_data_from_app(self.app).blast.update_nuvs_blast(
# self.analysis_id,
# self.sequence_index,
# self.error,
# virtool.utils.timestamp(),
# self.rid,
# self.ready,
# self.result,
# )
#
# Path: virtool/types.py
. Output only the next line. | ) -> Document: |
Here is a snippet: <|code_start|> "results": {
"hits": [1, 2, 3, 4, 5],
"read_count": 1209,
"subtracted_count": 231,
},
"workflow": "pathoscope_bowtie",
},
{
"_id": "bar",
"read_count": 7982,
"results": [9, 8, 7, 6, 5],
"subtracted_count": 112,
"workflow": "pathoscope_bowtie",
},
{
"_id": "baz",
"results": [9, 8, 7, 6, 5],
"workflow": "nuvs",
},
{
"_id": "bad",
"join_histogram": [1, 2, 3, 4, 5],
"joined_pair_count": 12345,
"remainder_pair_count": 54321,
"results": [9, 8, 7, 6, 5],
"workflow": "aodp",
},
]
)
<|code_end|>
. Write the next line using the current file imports:
from virtool.analyses.migrate import nest_results
and context from other files:
# Path: virtool/analyses/migrate.py
# async def nest_results(db):
# """
# Move the ``subtracted_count`` and ``read_count`` fields from the document to the ``results`` subdocument.
#
# This supports the new jobs API model where only a ``results`` field can be set on the analysis document by a
# workflow job.
#
# :param db: the application database object
#
# """
# async with buffered_bulk_writer(db.analyses) as writer:
# async for document in db.analyses.find({"results.hits": {"$exists": False}}):
# _id = document["_id"]
#
# results = {
# "hits": document["results"],
# }
#
# if document["workflow"] == "pathoscope_bowtie":
# await writer.add(
# UpdateOne(
# {"_id": document["_id"]},
# {
# "$set": {
# "results": {
# **results,
# "read_count": document["read_count"],
# "subtracted_count": document["subtracted_count"],
# }
# },
# "$unset": {"read_count": "", "subtracted_count": ""},
# },
# )
# )
#
# elif document["workflow"] == "nuvs":
# await writer.add(
# UpdateOne({"_id": document["_id"]}, {"$set": {"results": results}})
# )
#
# elif document["workflow"] == "aodp":
# await writer.add(
# UpdateOne(
# {"_id": document["_id"]},
# {
# "$set": {
# "results": {
# **results,
# "join_histogram": document["join_histogram"],
# "joined_pair_count": document["joined_pair_count"],
# "remainder_pair_count": document[
# "remainder_pair_count"
# ],
# }
# },
# "$unset": {
# "join_histogram": "",
# "joined_pair_count": "",
# "remainder_pair_count": "",
# },
# },
# )
# )
, which may include functions, classes, or code. Output only the next line. | await nest_results(dbi) |
Given the code snippet: <|code_start|>
assert await dbi.analyses.find().to_list(None) == [{"_id": 1, "ready": True}]
async def test_check_missing_ids(dbi):
await dbi.subtraction.insert_many(
[
{
"_id": "foo",
"name": "Foo",
},
{
"_id": "bar",
"name": "Bar",
},
]
)
non_existent_subtractions = await virtool.db.utils.check_missing_ids(
dbi.subtraction, ["foo", "bar", "baz"]
)
assert non_existent_subtractions == {"baz"}
@pytest.mark.parametrize("batch_size", (60, 100))
async def test_buffered_bulk_writer(batch_size, data_regression, snapshot, mocker):
collection = mocker.Mock()
collection.bulk_write = mocker.AsyncMock()
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import virtool.db
import virtool.db.utils
from virtool.db.utils import buffered_bulk_writer
and context (functions, classes, or occasionally code) from other files:
# Path: virtool/db/utils.py
# @asynccontextmanager
# async def buffered_bulk_writer(collection, batch_size=100):
# """
# A context manager for bulk writing to MongoDB.
#
# Returns a :class:``BufferedBulkWriter`` object. Automatically flushes the buffer
# when the context manager exits.
#
# :param collection: the MongoDB collection to write against
# :param batch_size: the number of requests to be sent in each bulk operation
#
# """
# writer = BufferedBulkWriter(collection, batch_size)
#
# try:
# yield writer
# finally:
# await writer.flush()
. Output only the next line. | async with buffered_bulk_writer(collection, batch_size=batch_size) as writer: |
Continue the code snippet: <|code_start|>@routes.get("/groups")
async def find(req: Request) -> Response:
"""
Get a list of all existing group documents.
"""
cursor = req.app["db"].groups.find()
return json_response([base_processor(d) async for d in cursor])
@routes.post("/groups", admin=True)
@schema(
{
"group_id": {
"type": "string",
"coerce": virtool.validators.strip,
"empty": False,
"required": True,
}
}
)
async def create(req: Request) -> Response:
"""
Adds a new user group.
"""
db, data = req.app["db"], req["data"]
document = {
"_id": data["group_id"].lower(),
<|code_end|>
. Use current file imports:
import pymongo.errors
import virtool.groups.db
import virtool.http.routes
import virtool.validators
from aiohttp.web import Request, Response
from aiohttp.web_exceptions import HTTPBadRequest, HTTPNoContent
from virtool.api.response import NotFound, json_response
from virtool.http.schema import schema
from virtool.users.utils import generate_base_permissions
from virtool.utils import base_processor
and context (classes, functions, or code) from other files:
# Path: virtool/users/utils.py
# def generate_base_permissions() -> dict:
# """
# Return a `dict` keyed with all Virtool permissions where all the values are `False`.
#
# :return: all-false permissions
# """
# return {p: False for p in PERMISSIONS}
. Output only the next line. | "permissions": generate_base_permissions(), |
Given snippet: <|code_start|> document = await db.samples.find_one(sample_id, ["user"])
if document:
return document["user"]["id"]
return None
async def recalculate_workflow_tags(db, sample_id: str) -> dict:
"""
Recalculate and apply workflow tags (eg. "ip", True) for a given sample.
:param db: the application database client
:param sample_id: the id of the sample to recalculate tags for
:return: the updated sample document
"""
analyses = await asyncio.shield(
db.analyses.find({"sample.id": sample_id}, ["ready", "workflow"]).to_list(None)
)
update = virtool.samples.utils.calculate_workflow_tags(analyses)
document = await db.samples.find_one_and_update(
{"_id": sample_id}, {"$set": update}, projection=LIST_PROJECTION
)
return document
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import logging
import os
import virtool.db.utils
import virtool.errors
import virtool.samples.utils
import virtool.utils
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Optional
from multidict import MultiDictProxy
from pymongo.results import DeleteResult
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from virtool.config.cls import Config
from virtool.db.transforms import AbstractTransform, apply_transforms
from virtool.labels.db import AttachLabelsTransform
from virtool.samples.models import SampleArtifact, SampleReads
from virtool.samples.utils import join_legacy_read_paths
from virtool.settings.db import Settings
from virtool.subtractions.db import AttachSubtractionTransform
from virtool.types import App, Document
from virtool.uploads.models import Upload
from virtool.users.db import AttachUserTransform
from virtool.utils import base_processor, compress_file, file_stats
and context:
# Path: virtool/config/cls.py
# class Config:
# db_connection_string: str
# db_name: str
# dev: bool
# postgres_connection_string: str
# redis_connection_string: str
# b2c_client_id: str = None
# b2c_client_secret: str = None
# b2c_tenant: str = None
# b2c_user_flow: str = None
# base_url: str = ""
# data_path: Path = None
# fake: bool = False
# fake_path: Path = None
# force_version: str = None
# host: str = None
# no_check_files: bool = False
# no_check_db: bool = False
# no_fetching: bool = False
# no_sentry: bool = False
# port: int = 9950
# proxy: str = None
# use_b2c: bool = False
# verbose: bool = False
# sentry_dsn: str = "https://9a2f8d1a3f7a431e873207a70ef3d44d:ca6db07b82934005beceae93560a6794@sentry.io/220532"
#
# Path: virtool/types.py
which might include code, classes, or functions. Output only the next line. | async def remove_samples(db, config: Config, id_list: List[str]) -> DeleteResult: |
Given snippet: <|code_start|> all(file.get("raw", False) is False for file in files)
and files[0]["name"] == "reads_1.fastq"
and (sample["paired"] is False or files[1]["name"] == "reads_2.fastq")
)
async def update_is_compressed(db, sample: Dict[str, Any]):
"""
Update the ``is_compressed`` field for the passed ``sample`` in the database if all
of its files are compressed.
:param db: the application database
:param sample: the sample document
"""
files = sample["files"]
names = [file["name"] for file in files]
is_compressed = names == ["reads_1.fq.gz"] or names == [
"reads_1.fq.gz",
"reads_2.fq.gz",
]
if is_compressed:
await db.samples.update_one(
{"_id": sample["_id"]}, {"$set": {"is_compressed": True}}
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import logging
import os
import virtool.db.utils
import virtool.errors
import virtool.samples.utils
import virtool.utils
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Optional
from multidict import MultiDictProxy
from pymongo.results import DeleteResult
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from virtool.config.cls import Config
from virtool.db.transforms import AbstractTransform, apply_transforms
from virtool.labels.db import AttachLabelsTransform
from virtool.samples.models import SampleArtifact, SampleReads
from virtool.samples.utils import join_legacy_read_paths
from virtool.settings.db import Settings
from virtool.subtractions.db import AttachSubtractionTransform
from virtool.types import App, Document
from virtool.uploads.models import Upload
from virtool.users.db import AttachUserTransform
from virtool.utils import base_processor, compress_file, file_stats
and context:
# Path: virtool/config/cls.py
# class Config:
# db_connection_string: str
# db_name: str
# dev: bool
# postgres_connection_string: str
# redis_connection_string: str
# b2c_client_id: str = None
# b2c_client_secret: str = None
# b2c_tenant: str = None
# b2c_user_flow: str = None
# base_url: str = ""
# data_path: Path = None
# fake: bool = False
# fake_path: Path = None
# force_version: str = None
# host: str = None
# no_check_files: bool = False
# no_check_db: bool = False
# no_fetching: bool = False
# no_sentry: bool = False
# port: int = 9950
# proxy: str = None
# use_b2c: bool = False
# verbose: bool = False
# sentry_dsn: str = "https://9a2f8d1a3f7a431e873207a70ef3d44d:ca6db07b82934005beceae93560a6794@sentry.io/220532"
#
# Path: virtool/types.py
which might include code, classes, or functions. Output only the next line. | async def compress_sample_reads(app: App, sample: Dict[str, Any]): |
Given the following code snippet before the placeholder: <|code_start|> "labels",
"is_legacy",
"library_type",
"name",
"pathoscope",
"nuvs",
"group",
"group_read",
"group_write",
"all_read",
"all_write",
"ready",
"user",
]
RIGHTS_PROJECTION = {
"_id": False,
"group": True,
"group_read": True,
"group_write": True,
"all_read": True,
"all_write": True,
"user": True,
}
class ArtifactsAndReadsTransform(AbstractTransform):
def __init__(self, pg):
self._pg = pg
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import logging
import os
import virtool.db.utils
import virtool.errors
import virtool.samples.utils
import virtool.utils
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Optional
from multidict import MultiDictProxy
from pymongo.results import DeleteResult
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from virtool.config.cls import Config
from virtool.db.transforms import AbstractTransform, apply_transforms
from virtool.labels.db import AttachLabelsTransform
from virtool.samples.models import SampleArtifact, SampleReads
from virtool.samples.utils import join_legacy_read_paths
from virtool.settings.db import Settings
from virtool.subtractions.db import AttachSubtractionTransform
from virtool.types import App, Document
from virtool.uploads.models import Upload
from virtool.users.db import AttachUserTransform
from virtool.utils import base_processor, compress_file, file_stats
and context including class names, function names, and sometimes code from other files:
# Path: virtool/config/cls.py
# class Config:
# db_connection_string: str
# db_name: str
# dev: bool
# postgres_connection_string: str
# redis_connection_string: str
# b2c_client_id: str = None
# b2c_client_secret: str = None
# b2c_tenant: str = None
# b2c_user_flow: str = None
# base_url: str = ""
# data_path: Path = None
# fake: bool = False
# fake_path: Path = None
# force_version: str = None
# host: str = None
# no_check_files: bool = False
# no_check_db: bool = False
# no_fetching: bool = False
# no_sentry: bool = False
# port: int = 9950
# proxy: str = None
# use_b2c: bool = False
# verbose: bool = False
# sentry_dsn: str = "https://9a2f8d1a3f7a431e873207a70ef3d44d:ca6db07b82934005beceae93560a6794@sentry.io/220532"
#
# Path: virtool/types.py
. Output only the next line. | async def attach_one(self, document: Document, prepared: Any) -> Document: |
Given the code snippet: <|code_start|> holder_id, key = decode_authorization(req.headers.get("AUTHORIZATION"))
except virtool.errors.AuthError:
raise HTTPUnauthorized(text="Malformed Authorization header")
return await authenticate_with_api_key(req, handler, holder_id, key)
async def authenticate_with_api_key(
req: Request, handler: Callable, user_id: str, key: str
) -> Response:
db = req.app["db"]
document = await db.keys.find_one(
{
"_id": virtool.utils.hash_key(key),
"user.id": user_id
},
["permissions"]
)
if not document:
raise HTTPUnauthorized(text="Invalid authorization header")
user = db.users.find_one(
{
"_id": user_id
},
AUTHORIZATION_PROJECTION
)
<|code_end|>
, generate the next line using the imports in this file:
from typing import Callable, Tuple
from aiohttp import BasicAuth, web
from aiohttp.web import HTTPFound, Request, Response
from aiohttp.web_exceptions import HTTPUnauthorized
from jose import ExpiredSignatureError
from jose.exceptions import JWTClaimsError, JWTError
from virtool.http.client import UserClient
from virtool.http.utils import set_session_id_cookie
from virtool.oidc.utils import update_jwk_args, validate_token
from virtool.users.db import B2CUserAttributes, find_or_create_b2c_user
from virtool.users.sessions import clear_reset_code, create_session, get_session
from virtool.utils import random_alphanumeric
import virtool.errors
import virtool.utils
and context (functions, classes, or occasionally code) from other files:
# Path: virtool/http/client.py
# class UserClient(AbstractClient):
# def __init__(
# self,
# db,
# administrator: bool,
# force_reset: bool,
# groups: Sequence[str],
# permissions: Dict[str, bool],
# user_id: Union[str, None],
# authenticated: bool,
# session_id: Optional[str] = None,
# ):
# self._db = db
# self._force_reset = force_reset
# self._administrator = administrator
# self._authenticated = authenticated
# self.groups = groups
# self.permissions = permissions
# self.user_id = user_id
# self.session_id = session_id
#
# @property
# def authenticated(self) -> bool:
# return self._authenticated
#
# @property
# def administrator(self) -> bool:
# return self._administrator
#
# @property
# def force_reset(self) -> bool:
# return self._force_reset
#
# def has_permission(self, permission: str) -> bool:
# return self.permissions.get(permission, False)
#
# async def has_right_on_analysis(self, analysis_id: str, right: Right) -> bool:
# return True
#
# async def has_right_on_hmms(self, right: Right):
# if right == READ:
# return True
#
# if right == MODIFY or right == REMOVE:
# return self.has_permission("modify_hmm")
#
# async def has_right_on_index(self, index_id: str, right: Right) -> bool:
# return True if right == READ else False
#
# async def has_right_on_sample(self, sample_id: str, right: Right) -> bool:
# if self.administrator:
# return True
#
# sample = await self._db.find_one(sample_id, {"quality": False})
#
# if self.user_id == sample["user"]["id"]:
# return True
#
# is_group_member = sample["group"] and sample["group"] in self.groups
#
# if right == READ:
# return sample["all_read"] or (is_group_member and sample["group_read"])
#
# if right == MODIFY or right == REMOVE:
# return sample["all_write"] or (is_group_member and sample["group_write"])
#
# async def has_right_on_reference(self, reference_id: str, right: Right):
# return False
#
# async def has_right_on_subtraction(self, subtraction_id: str, right: Right):
# """
# Check whether the authenticated user has the passed ``right`` on a subtraction.
#
# User rights on subtractions are based on group permissions.
#
# """
# if right == READ:
# return True
#
# if right == MODIFY:
# return self.has_permission("modify_subtraction")
#
# if right == REMOVE:
# return self.has_permission("delete_subtraction")
#
# async def has_right_on_upload(self, upload_id: str, right: Right) -> bool:
# if right == REMOVE:
# return self.has_permission("remove_file")
#
# if right == MODIFY:
# return False
#
# return True
#
# Path: virtool/oidc/utils.py
# async def update_jwk_args(app: Application, token: jwt) -> JWKArgs:
# """
# Update jwk_args and store in environment variable
#
# :param token: JWT token to validate and decode
# :param app: the app object
# :return: jwk_args
# """
# header = await app["run_in_thread"](get_unverified_header, token)
# authority = app["b2c"].authority
# resp = await app["client"].get(
# f"{authority}/discovery/v2.0/keys", allow_redirects=True
# )
# jwks = json.loads(await resp.text())
#
# jwk = await get_matching_jwk(jwks, header["kid"])
#
# jwk_args = JWKArgs(
# kty=jwk["kty"], kid=jwk["kid"], use=jwk["use"], n=jwk["n"], e=jwk["e"]
# )
#
# app["b2c"].jwk_args = jwk_args
#
# return jwk_args
#
# async def validate_token(app: Application, token: jwt) -> dict:
# """
# Validate token and return claims using JWK_ARGS environment variable.
#
# :param token: JWT token to validate
# :param app: the application object
# :return: JWT claims
# """
#
# jwk_args = app["b2c"].jwk_args or await update_jwk_args(app, token)
#
# return decode(
# token,
# asdict(jwk_args),
# algorithms=["RS256"],
# audience=app["config"].b2c_client_id,
# )
. Output only the next line. | req["client"] = UserClient( |
Using the snippet: <|code_start|>
def get_interface_from_model(obj: Base) -> str:
"""
Transform the passed model object into an dispatcher interface name.
For example, a :class:``Label`` model will result in a string with the value `labels` being
returned.
:param obj: the model object
:return: the interface string
"""
try:
return obj.__tablename__
except AttributeError:
raise TypeError("Not a transformable model: ", obj)
class DispatcherSQLEvents:
"""
Listens on SQLAlchemy session events to know what models have changes on transaction commits.
Calls enqueue change with the correct dispatcher interface and list of modified IDs when a
transaction is committed. Gracefully handles rollbacks.
Inspired by signalling in [Flask-SQLAlchemy](https://github.com/pallets/flask-sqlalchemy).
"""
def __init__(
<|code_end|>
, determine the next line of code. You have imports:
from collections import defaultdict
from typing import Callable, List, Union
from sqlalchemy import event, inspect
from sqlalchemy.orm import Session
from virtool.dispatcher.operations import Operation
from virtool.pg.base import Base
and context (class names, function names, or code) available:
# Path: virtool/dispatcher/operations.py
# INSERT: Operation = "insert"
# UPDATE: Operation = "update"
# DELETE: Operation = "delete"
. Output only the next line. | self, enqueue_change: Callable[[str, Operation, List[Union[str, int]]], None] |
Predict the next line after this snippet: <|code_start|> "masking": result.get("query_masking"),
}
def format_blast_hit(hit: dict) -> dict:
"""
Format a BLAST hit from NCBI into a format more usable by Virtool.
:param hit: the BLAST hit
:return: the formatted hit
"""
cleaned = {
key: hit["description"][0].get(key, "")
for key in ["accession", "taxid", "title"]
}
hsps = {
key: hit["hsps"][0][key]
for key in ["identity", "evalue", "align_len", "score", "bit_score", "gaps"]
}
return {
**cleaned,
**hsps,
"name": hit["description"][0].get("sciname", "No name"),
"len": hit["len"],
}
<|code_end|>
using the current file's imports:
import io
import json
import re
import aiohttp
import virtool.errors
from logging import getLogger
from typing import Tuple
from zipfile import ZipFile
from virtool.config.cls import Config
from virtool.http.proxy import ProxyRequest
and any relevant context from other files:
# Path: virtool/config/cls.py
# class Config:
# db_connection_string: str
# db_name: str
# dev: bool
# postgres_connection_string: str
# redis_connection_string: str
# b2c_client_id: str = None
# b2c_client_secret: str = None
# b2c_tenant: str = None
# b2c_user_flow: str = None
# base_url: str = ""
# data_path: Path = None
# fake: bool = False
# fake_path: Path = None
# force_version: str = None
# host: str = None
# no_check_files: bool = False
# no_check_db: bool = False
# no_fetching: bool = False
# no_sentry: bool = False
# port: int = 9950
# proxy: str = None
# use_b2c: bool = False
# verbose: bool = False
# sentry_dsn: str = "https://9a2f8d1a3f7a431e873207a70ef3d44d:ca6db07b82934005beceae93560a6794@sentry.io/220532"
. Output only the next line. | async def check_rid(config: Config, rid: str) -> bool: |
Predict the next line after this snippet: <|code_start|>
async def test_migrate_subtractions_list(dbi):
await dbi.samples.insert_many(
[
{"_id": "foo", "subtraction": {"id": "prunus"}},
{"_id": "bar", "subtraction": {"id": "malus"}},
{"_id": "baz", "subtraction": None},
]
)
<|code_end|>
using the current file's imports:
from virtool.db.migrate_shared import add_subtractions_field
and any relevant context from other files:
# Path: virtool/db/migrate_shared.py
# async def add_subtractions_field(collection: AsyncIOMotorCollection):
# """
# Transform `subtraction` field to a list and rename it as `subtractions`.
#
# :param collection: the Mongo collection to perform the operation on
#
# """
# updates = list()
#
# async for document in collection.find({"subtraction": {"$exists": True}}):
# try:
# subtractions = [document["subtraction"]["id"]]
# except TypeError:
# subtractions = list()
#
# update = UpdateOne(
# {"_id": document["_id"]},
# {"$set": {"subtractions": subtractions}, "$unset": {"subtraction": ""}},
# )
#
# updates.append(update)
#
# if updates:
# await collection.bulk_write(updates)
. Output only the next line. | await add_subtractions_field(dbi.samples) |
Here is a snippet: <|code_start|> self._force_reset = force_reset
self._administrator = administrator
self._authenticated = authenticated
self.groups = groups
self.permissions = permissions
self.user_id = user_id
self.session_id = session_id
@property
def authenticated(self) -> bool:
return self._authenticated
@property
def administrator(self) -> bool:
return self._administrator
@property
def force_reset(self) -> bool:
return self._force_reset
def has_permission(self, permission: str) -> bool:
return self.permissions.get(permission, False)
async def has_right_on_analysis(self, analysis_id: str, right: Right) -> bool:
return True
async def has_right_on_hmms(self, right: Right):
if right == READ:
return True
<|code_end|>
. Write the next line using the current file imports:
from abc import ABC, abstractmethod
from typing import Dict, Optional, Sequence, Union
from virtool.http.rights import MODIFY, READ, REMOVE, Right
from virtool.jobs.utils import JobRights
and context from other files:
# Path: virtool/http/rights.py
# READ = "read"
# MODIFY = "modify"
# REMOVE = "remove"
, which may include functions, classes, or code. Output only the next line. | if right == MODIFY or right == REMOVE: |
Next line prediction: <|code_start|> session_id: Optional[str] = None,
):
self._db = db
self._force_reset = force_reset
self._administrator = administrator
self._authenticated = authenticated
self.groups = groups
self.permissions = permissions
self.user_id = user_id
self.session_id = session_id
@property
def authenticated(self) -> bool:
return self._authenticated
@property
def administrator(self) -> bool:
return self._administrator
@property
def force_reset(self) -> bool:
return self._force_reset
def has_permission(self, permission: str) -> bool:
return self.permissions.get(permission, False)
async def has_right_on_analysis(self, analysis_id: str, right: Right) -> bool:
return True
async def has_right_on_hmms(self, right: Right):
<|code_end|>
. Use current file imports:
(from abc import ABC, abstractmethod
from typing import Dict, Optional, Sequence, Union
from virtool.http.rights import MODIFY, READ, REMOVE, Right
from virtool.jobs.utils import JobRights)
and context including class names, function names, or small code snippets from other files:
# Path: virtool/http/rights.py
# READ = "read"
# MODIFY = "modify"
# REMOVE = "remove"
. Output only the next line. | if right == READ: |
Next line prediction: <|code_start|> self._force_reset = force_reset
self._administrator = administrator
self._authenticated = authenticated
self.groups = groups
self.permissions = permissions
self.user_id = user_id
self.session_id = session_id
@property
def authenticated(self) -> bool:
return self._authenticated
@property
def administrator(self) -> bool:
return self._administrator
@property
def force_reset(self) -> bool:
return self._force_reset
def has_permission(self, permission: str) -> bool:
return self.permissions.get(permission, False)
async def has_right_on_analysis(self, analysis_id: str, right: Right) -> bool:
return True
async def has_right_on_hmms(self, right: Right):
if right == READ:
return True
<|code_end|>
. Use current file imports:
(from abc import ABC, abstractmethod
from typing import Dict, Optional, Sequence, Union
from virtool.http.rights import MODIFY, READ, REMOVE, Right
from virtool.jobs.utils import JobRights)
and context including class names, function names, or small code snippets from other files:
# Path: virtool/http/rights.py
# READ = "read"
# MODIFY = "modify"
# REMOVE = "remove"
. Output only the next line. | if right == MODIFY or right == REMOVE: |
Here is a snippet: <|code_start|>
class AbstractClient(ABC):
@property
@abstractmethod
async def authenticated(self) -> bool:
...
@property
@abstractmethod
async def administrator(self) -> bool:
...
@property
@abstractmethod
async def force_reset(self) -> bool:
...
@abstractmethod
async def has_permission(self, permission) -> bool:
...
@abstractmethod
<|code_end|>
. Write the next line using the current file imports:
from abc import ABC, abstractmethod
from typing import Dict, Optional, Sequence, Union
from virtool.http.rights import MODIFY, READ, REMOVE, Right
from virtool.jobs.utils import JobRights
and context from other files:
# Path: virtool/http/rights.py
# READ = "read"
# MODIFY = "modify"
# REMOVE = "remove"
, which may include functions, classes, or code. Output only the next line. | async def has_right_on_analysis(self, analysis_id: str, right: Right) -> bool: |
Here is a snippet: <|code_start|>
async def create_analysis_file(
pg: AsyncEngine, analysis_id: str, analysis_format: str, name: str, size: int = None
) -> Dict[str, any]:
"""
Create a row in the `analysis_files` SQL table that represents an analysis result file.
:param pg: PostgreSQL AsyncEngine object
:param analysis_id: ID that corresponds to a parent analysis
:param analysis_format: Format of the analysis result file
:param name: Name of the analysis result file
:param size: Size of the analysis result file
:return: A dictionary representation of the newly created row
"""
async with AsyncSession(pg) as session:
<|code_end|>
. Write the next line using the current file imports:
from pathlib import Path
from typing import Dict
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from virtool.analyses.models import AnalysisFile
import virtool.analyses.utils
import virtool.utils
and context from other files:
# Path: virtool/analyses/models.py
# class AnalysisFile(Base):
# """
# SQL model to store new analysis files
#
# """
#
# __tablename__ = "analysis_files"
#
# id = Column(Integer, primary_key=True)
# analysis = Column(String)
# description = Column(String)
# format = Column(Enum(AnalysisFormat))
# name = Column(String)
# name_on_disk = Column(String, unique=True)
# size = Column(BigInteger)
# uploaded_at = Column(DateTime)
, which may include functions, classes, or code. Output only the next line. | analysis_file = AnalysisFile( |
Here is a snippet: <|code_start|> if password is not None:
error = await check_password_length(req)
if error:
raise HTTPBadRequest(text=error)
if not await validate_credentials(db, user_id, old_password or ""):
raise HTTPBadRequest(text="Invalid credentials")
update = virtool.account.db.compose_password_update(password)
if "email" in data:
update["email"] = data["email"]
if update:
document = await db.users.find_one_and_update(
{"_id": user_id}, {"$set": update}, projection=virtool.account.db.PROJECTION
)
else:
document = await virtool.account.db.get(db, user_id)
return json_response(base_processor(document))
@routes.get("/account/settings")
async def get_settings(req: Request) -> Response:
"""
Get account settings
"""
<|code_end|>
. Write the next line using the current file imports:
import virtool.account.db
import virtool.http.auth
import virtool.http.routes
import virtool.validators
from aiohttp.web import HTTPNoContent, Request, Response
from aiohttp.web_exceptions import HTTPBadRequest
from virtool.analyses.utils import WORKFLOW_NAMES
from virtool.api.response import NotFound, json_response
from virtool.db.utils import get_one_field
from virtool.http.schema import schema
from virtool.http.utils import set_session_id_cookie, set_session_token_cookie
from virtool.users.checks import check_password_length
from virtool.users.db import validate_credentials
from virtool.users.sessions import create_reset_code, replace_session
from virtool.users.utils import limit_permissions
from virtool.utils import base_processor
and context from other files:
# Path: virtool/db/utils.py
# async def get_one_field(collection, field: str, query: Union[str, Dict]) -> Any:
# """
# Get the value for a single `field` from a single document matching the `query`.
#
# :param collection: the database collection to search
# :param field: the field to return
# :param query: the document matching query
# :return: the field
#
# """
# projected = await collection.find_one(query, [field])
#
# if projected is None:
# return None
#
# return projected.get(field)
#
# Path: virtool/users/utils.py
# def limit_permissions(permissions: dict, limit_filter: dict) -> dict:
# """
# Make sure permission values in `permissions` do not exceed those in `limit_filter`. Returns a
# filtered set of permissions.
#
# :param limit_filter: the limiting permissions that cannot be exceeded
# :param permissions: a permissions to filter
# :return: filtered permissions
#
# """
# return {p: (permissions.get(p, False) and limit_filter[p]) for p in permissions}
, which may include functions, classes, or code. Output only the next line. | account_settings = await get_one_field( |
Based on the snippet: <|code_start|> "check_with": virtool.validators.is_permission_dict,
"required": True,
}
}
)
async def update_api_key(req: Request) -> Response:
"""
Change the permissions for an existing API key.
"""
db = req.app["db"]
data = req["data"]
key_id = req.match_info.get("key_id")
if not await db.keys.count_documents({"id": key_id}):
raise NotFound()
user_id = req["client"].user_id
user = await db.users.find_one(user_id, ["administrator", "permissions"])
# The permissions currently assigned to the API key.
permissions = await get_one_field(
db.keys, "permissions", {"id": key_id, "user.id": user_id}
)
permissions.update(data["permissions"])
if not user["administrator"]:
<|code_end|>
, predict the immediate next line with the help of imports:
import virtool.account.db
import virtool.http.auth
import virtool.http.routes
import virtool.validators
from aiohttp.web import HTTPNoContent, Request, Response
from aiohttp.web_exceptions import HTTPBadRequest
from virtool.analyses.utils import WORKFLOW_NAMES
from virtool.api.response import NotFound, json_response
from virtool.db.utils import get_one_field
from virtool.http.schema import schema
from virtool.http.utils import set_session_id_cookie, set_session_token_cookie
from virtool.users.checks import check_password_length
from virtool.users.db import validate_credentials
from virtool.users.sessions import create_reset_code, replace_session
from virtool.users.utils import limit_permissions
from virtool.utils import base_processor
and context (classes, functions, sometimes code) from other files:
# Path: virtool/db/utils.py
# async def get_one_field(collection, field: str, query: Union[str, Dict]) -> Any:
# """
# Get the value for a single `field` from a single document matching the `query`.
#
# :param collection: the database collection to search
# :param field: the field to return
# :param query: the document matching query
# :return: the field
#
# """
# projected = await collection.find_one(query, [field])
#
# if projected is None:
# return None
#
# return projected.get(field)
#
# Path: virtool/users/utils.py
# def limit_permissions(permissions: dict, limit_filter: dict) -> dict:
# """
# Make sure permission values in `permissions` do not exceed those in `limit_filter`. Returns a
# filtered set of permissions.
#
# :param limit_filter: the limiting permissions that cannot be exceeded
# :param permissions: a permissions to filter
# :return: filtered permissions
#
# """
# return {p: (permissions.get(p, False) and limit_filter[p]) for p in permissions}
. Output only the next line. | permissions = limit_permissions(permissions, user["permissions"]) |
Here is a snippet: <|code_start|>
await shutdown_dispatcher(app)
assert mock.called
async def test_shutdown_executors(mocker, spawn_client):
"""
Test that the app's `ThreadPoolExecutor` is properly closed on shutdown.
"""
client = await spawn_client(authorize=True)
app = client.app
mock = mocker.patch("concurrent.futures.process.ProcessPoolExecutor.shutdown")
await shutdown_executors(app)
assert app["executor"]._shutdown
assert mock.called
async def test_shutdown_scheduler(spawn_client):
"""
Test that the app's `aiojobs` scheduler is properly closed on shutdown.
"""
client = await spawn_client(authorize=True)
app = client.app
<|code_end|>
. Write the next line using the current file imports:
from sqlalchemy import text
from virtool.startup import get_scheduler_from_app
from virtool.shutdown import (
shutdown_client,
shutdown_dispatcher,
shutdown_executors,
shutdown_scheduler,
shutdown_redis,
drop_fake_postgres,
)
and context from other files:
# Path: virtool/startup.py
# def get_scheduler_from_app(app: Application) -> aiojobs.Scheduler:
# scheduler = aiojobs.aiohttp.get_scheduler_from_app(app)
#
# if scheduler is None:
# return app["scheduler"]
#
# return scheduler
, which may include functions, classes, or code. Output only the next line. | scheduler = get_scheduler_from_app(app) |
Given snippet: <|code_start|> "handle",
"administrator",
"email",
"groups",
"last_password_change",
"permissions",
"primary_group",
"settings",
)
def compose_password_update(password: str) -> Dict[str, Any]:
"""
Compose an update dict for self-changing a users account password.
This will disable forced reset and won't invalidate current sessions, unlike a
password change by an administrator.
:param password: the new password
:return: a password update
"""
return {
"password": virtool.users.utils.hash_password(password),
"invalidate_sessions": False,
"last_password_change": virtool.utils.timestamp(),
"force_reset": False,
}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from typing import Any, Dict
from virtool.types import Document
import virtool.users.utils
import virtool.utils
and context:
# Path: virtool/types.py
which might include code, classes, or functions. Output only the next line. | async def get(db, user_id: str) -> Document: |
Here is a snippet: <|code_start|> payload = None
if data:
payload = json.dumps(data)
return await self._test_client.post(url, data=payload)
async def post_form(self, url, data):
return await self._test_client.post(url, data=data)
async def patch(self, url, data):
return await self._test_client.patch(url, data=json.dumps(data))
async def put(self, url, data):
return await self._test_client.put(url, data=json.dumps(data))
async def delete(self, url):
return await self._test_client.delete(url)
@pytest.fixture
def create_app(
create_user,
dbi,
pg_connection_string,
redis_connection_string,
test_db_connection_string,
test_db_name,
):
def _create_app(dev: bool = False, base_url: str = ""):
<|code_end|>
. Write the next line using the current file imports:
import json
import aiohttp
import pytest
import virtool.app
import virtool.jobs.main
from typing import Optional
from aiohttp.web_routedef import RouteTableDef
from virtool.config.cls import Config
from virtool.utils import hash_key
and context from other files:
# Path: virtool/config/cls.py
# class Config:
# db_connection_string: str
# db_name: str
# dev: bool
# postgres_connection_string: str
# redis_connection_string: str
# b2c_client_id: str = None
# b2c_client_secret: str = None
# b2c_tenant: str = None
# b2c_user_flow: str = None
# base_url: str = ""
# data_path: Path = None
# fake: bool = False
# fake_path: Path = None
# force_version: str = None
# host: str = None
# no_check_files: bool = False
# no_check_db: bool = False
# no_fetching: bool = False
# no_sentry: bool = False
# port: int = 9950
# proxy: str = None
# use_b2c: bool = False
# verbose: bool = False
# sentry_dsn: str = "https://9a2f8d1a3f7a431e873207a70ef3d44d:ca6db07b82934005beceae93560a6794@sentry.io/220532"
, which may include functions, classes, or code. Output only the next line. | config = Config( |
Given the following code snippet before the placeholder: <|code_start|>def compose_regex_query(term, fields: List[str]) -> Dict[str, List[Dict[str, dict]]]:
"""
Compose a MongoDB query that checks if the values of the passed `fields` match the
passed search `term`.
:param term: the term to search
:param fields: the list of field to match against
:return: a query
"""
if not isinstance(fields, (list, tuple)):
raise TypeError("Type of 'fields' must be one of 'list' or 'tuple'")
# Stringify fields.
fields = [str(field) for field in coerce_list(fields)]
term = re.escape(term)
# Compile regex, making is case-insensitive.
regex = re.compile(str(term), re.IGNORECASE)
# Compose and return $or-based query.
return {"$or": [{field: {"$regex": regex}} for field in fields]}
async def paginate(
collection,
db_query: Union[Dict, MultiDictProxy[str]],
url_query: Union[Dict, MultiDictProxy[str]],
sort: Optional[Union[List[Tuple[str, int]], str]] = None,
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import math
import re
from typing import Dict, List, Optional, Tuple, Union
from aiohttp.web import Request
from multidict import MultiDictProxy
from virtool.types import Projection
from virtool.utils import coerce_list, to_bool
and context including class names, function names, and sometimes code from other files:
# Path: virtool/types.py
. Output only the next line. | projection: Optional[Projection] = None, |
Given the following code snippet before the placeholder: <|code_start|>
async def migrate_analyses(app: virtool.types.App):
"""
Delete unready analyses.
:param app: the application object
"""
await virtool.db.utils.delete_unready(app["db"].analyses)
await virtool.db.migrate_shared.add_subtractions_field(app["db"].analyses)
await nest_results(app["db"])
async def nest_results(db):
"""
Move the ``subtracted_count`` and ``read_count`` fields from the document to the ``results`` subdocument.
This supports the new jobs API model where only a ``results`` field can be set on the analysis document by a
workflow job.
:param db: the application database object
"""
<|code_end|>
, predict the next line using imports from the current file:
from pymongo import UpdateOne
from virtool.db.utils import buffered_bulk_writer
import virtool.db.migrate
import virtool.db.migrate_shared
import virtool.db.utils
import virtool.types
and context including class names, function names, and sometimes code from other files:
# Path: virtool/db/utils.py
# @asynccontextmanager
# async def buffered_bulk_writer(collection, batch_size=100):
# """
# A context manager for bulk writing to MongoDB.
#
# Returns a :class:``BufferedBulkWriter`` object. Automatically flushes the buffer
# when the context manager exits.
#
# :param collection: the MongoDB collection to write against
# :param batch_size: the number of requests to be sent in each bulk operation
#
# """
# writer = BufferedBulkWriter(collection, batch_size)
#
# try:
# yield writer
# finally:
# await writer.flush()
. Output only the next line. | async with buffered_bulk_writer(db.analyses) as writer: |
Using the snippet: <|code_start|>
async def test_get(snapshot, spawn_client, static_time):
client = await spawn_client(authorize=True)
resp = await client.get("/account")
assert resp.status == 200
assert await resp.json() == snapshot
assert await resp.json() == {
"groups": [],
"handle": "bob",
"id": "test",
"administrator": False,
"last_password_change": static_time.iso,
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from virtool.users.utils import PERMISSIONS, hash_password
and context (class names, function names, or code) available:
# Path: virtool/users/utils.py
# PERMISSIONS = [
# "cancel_job",
# "create_ref",
# "create_sample",
# "modify_hmm",
# "modify_subtraction",
# "remove_file",
# "remove_job",
# "upload_file",
# ]
#
# def hash_password(password: str) -> str:
# """
# Salt and hash a unicode password. Uses bcrypt.
#
# :param password: a password string to salt and hash
# :return: a salt and hashed password
#
# """
# return bcrypt.hashpw(password.encode(), bcrypt.gensalt(12))
. Output only the next line. | "permissions": {p: False for p in PERMISSIONS}, |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize("value", ["valid_email", "invalid_email"])
async def test_is_valid_email(value, spawn_client, resp_is):
"""
Tests that when an invalid email is used, validators.is_valid_email raises a 422 error.
"""
client = await spawn_client(authorize=True)
data = {
"email": "valid@email.ca" if value == "valid_email" else "-foo-bar-@baz!.ca",
"old_password": "old_password",
"password": "password",
}
resp = await client.patch("/account", data=data)
if value == "valid_email":
await resp_is.bad_request(resp, "Invalid credentials")
else:
await resp_is.invalid_input(resp, {"email": ["Not a valid email"]})
@pytest.mark.parametrize("error", [None, "wrong_handle", "wrong_password"])
async def test_login(spawn_client, create_user, resp_is, error, mocker):
client = await spawn_client()
await client.db.users.insert_one(
{
"user_id": "abc123",
"handle": "foobar",
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from virtool.users.utils import PERMISSIONS, hash_password
and context (functions, classes, or occasionally code) from other files:
# Path: virtool/users/utils.py
# PERMISSIONS = [
# "cancel_job",
# "create_ref",
# "create_sample",
# "modify_hmm",
# "modify_subtraction",
# "remove_file",
# "remove_job",
# "upload_file",
# ]
#
# def hash_password(password: str) -> str:
# """
# Salt and hash a unicode password. Uses bcrypt.
#
# :param password: a password string to salt and hash
# :return: a salt and hashed password
#
# """
# return bcrypt.hashpw(password.encode(), bcrypt.gensalt(12))
. Output only the next line. | "password": hash_password("p@ssword123"), |
Continue the code snippet: <|code_start|> async def flush(self):
"""
Flush the buffered write requests to MongoDB.
"""
if self._buffer:
await self.collection.bulk_write(self._buffer)
self._buffer = list()
@asynccontextmanager
async def buffered_bulk_writer(collection, batch_size=100):
"""
A context manager for bulk writing to MongoDB.
Returns a :class:``BufferedBulkWriter`` object. Automatically flushes the buffer
when the context manager exits.
:param collection: the MongoDB collection to write against
:param batch_size: the number of requests to be sent in each bulk operation
"""
writer = BufferedBulkWriter(collection, batch_size)
try:
yield writer
finally:
await writer.flush()
<|code_end|>
. Use current file imports:
from contextlib import asynccontextmanager
from typing import Any, Dict, Optional, Sequence, Set, Union
from motor.motor_asyncio import AsyncIOMotorCollection
from pymongo import InsertOne, UpdateOne
from virtool.types import Projection
import virtool.utils
and context (classes, functions, or code) from other files:
# Path: virtool/types.py
. Output only the next line. | def apply_projection(document: Dict, projection: Projection): |
Given the following code snippet before the placeholder: <|code_start|> if error == "400_exists":
await client.db.users.insert_one({"_id": "abc123"})
client.app["settings"].minimum_password_length = 8
data = {"handle": "fred", "password": "hello_world", "force_reset": False}
if error == "400_password":
data["password"] = "foo"
resp = await client.post("/users", data)
if error == "400_exists":
await resp_is.bad_request(resp, "User already exists")
return
if error == "400_password":
await resp_is.bad_request(
resp, "Password does not meet minimum length requirement (8)"
)
return
assert resp.status == 201
assert resp.headers["Location"] == "/users/abc123"
assert await resp.json() == snapshot
document = await client.db.users.find_one("abc123")
password = document.pop("password")
assert document == snapshot
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from virtool.users.utils import check_password
and context including class names, function names, and sometimes code from other files:
# Path: virtool/users/utils.py
# def check_password(password: str, hashed: bytes) -> bool:
# """
# Check if a unicode ``password`` matches a ``hashed_password``.
#
# :param password: the password to check.
# :param hashed: the salted and hashed password from the database
# :return: success of test
#
# """
# return bcrypt.checkpw(password.encode(), hashed)
. Output only the next line. | assert check_password("hello_world", password) |
Here is a snippet: <|code_start|>
"""
try:
cache_id = virtool.utils.random_alphanumeric(length=8)
document = {
"_id": cache_id,
"created_at": virtool.utils.timestamp(),
"files": list(),
"key": key,
"legacy": False,
"missing": False,
"paired": paired,
"ready": False,
"sample": {"id": sample_id},
}
await db.caches.insert_one(document)
return virtool.utils.base_processor(document)
except pymongo.errors.DuplicateKeyError as e:
# Check if key-sample.id uniqueness was enforced
# Keep trying to add the cache with new ids if the generated id is not unique.
if "_id" in e.details["keyPattern"]:
return await create(db, sample_id, key, paired)
raise
<|code_end|>
. Write the next line using the current file imports:
from typing import Any, Dict
from virtool.types import App
import pymongo.errors
import virtool.utils
and context from other files:
# Path: virtool/types.py
, which may include functions, classes, or code. Output only the next line. | async def remove(app: App, cache_id: str): |
Given the code snippet: <|code_start|> document = await virtool.history.db.get(req.app, change_id)
if document:
return json_response(document)
raise NotFound()
@routes.delete("/history/{change_id}")
async def revert(req):
"""
Remove the change document with the given ``change_id`` and any subsequent changes.
"""
db = req.app["db"]
change_id = req.match_info["change_id"]
document = await db.history.find_one(change_id, ["reference"])
if not document:
raise NotFound()
if not await virtool.references.db.check_right(
req, document["reference"]["id"], "modify_otu"
):
raise InsufficientRights()
try:
await virtool.history.db.revert(req.app, change_id)
<|code_end|>
, generate the next line using the imports in this file:
import virtool.history.db
import virtool.http.routes
import virtool.references.db
from aiohttp.web import HTTPConflict, HTTPNoContent
from virtool.api.response import InsufficientRights, NotFound, json_response
from virtool.errors import DatabaseError
and context (functions, classes, or occasionally code) from other files:
# Path: virtool/errors.py
# class DatabaseError(Exception):
# pass
. Output only the next line. | except DatabaseError: |
Predict the next line for this snippet: <|code_start|>
@pytest.mark.parametrize("rollback", [False, True])
async def test_events(rollback, mocker, pg: AsyncEngine):
"""
Test that changes are recorded as needed and not recorded when a transaction is rolled back.
Specifically, make sure changes aren't recorded for both flushed and un-flushed changes.
"""
changes = list()
def enqueue_change(*args):
changes.append(args)
<|code_end|>
with the help of current file imports:
import pytest
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from virtool.dispatcher.events import DispatcherSQLEvents
from virtool.labels.models import Label
and context from other files:
# Path: virtool/dispatcher/events.py
# class DispatcherSQLEvents:
# """
# Listens on SQLAlchemy session events to know what models have changes on transaction commits.
#
# Calls enqueue change with the correct dispatcher interface and list of modified IDs when a
# transaction is committed. Gracefully handles rollbacks.
#
# Inspired by signalling in [Flask-SQLAlchemy](https://github.com/pallets/flask-sqlalchemy).
#
# """
#
# def __init__(
# self, enqueue_change: Callable[[str, Operation, List[Union[str, int]]], None]
# ):
# self._enqueue_change = enqueue_change
# self._changes = defaultdict(dict)
#
# event.listen(Session, "before_flush", self._record_ops)
# event.listen(Session, "before_commit", self._record_ops)
# event.listen(Session, "after_commit", self._after_commit)
# event.listen(Session, "after_rollback", self._after_rollback)
#
# def _after_commit(self, session: Session):
# """
# Executed after a commit.
#
# Processes recorded changes and uses them to call :meth:`enqueue_change` as needed. Clears
# the record changes when complete.
#
# :param session: the session that was committed
#
# """
# changes = list(self._changes[id(session)].values())
#
# for data, change_type in changes:
# interface = get_interface_from_model(data)
# self._enqueue_change(interface, change_type, [data.id])
#
# del self._changes[id(session)]
#
# def _after_rollback(self, session: Session):
# """
# Executed after session rollback.
#
# Clears the records changes for the passed session.
#
# :param session: the session that was rolled back
#
# """
# del self._changes[id(session)]
#
# def _record_ops(self, session: Session, flush_context=None, instances=None):
# """
# Called when a session fires the `after_flush` or `before_commit` events.
#
# Records the operations that have occurred in the session and stores them so they can be
# sent via `enqueue_change` when the transaction is committed.
#
# The `flush_context` and `instances` arguments are included to match the callback function
# signature expected by SQLAlchemy for the `after_flush` or `before_commit` events. They are
# not used.
#
# :param session: the session the event was fired on
# :param flush_context: unused
# :param instances: unused
#
# """
# session_changes = self._changes[id(session)]
#
# for targets, operation in (
# (session.new, "insert"),
# (session.dirty, "update"),
# (session.deleted, "delete"),
# ):
# for target in targets:
# state = inspect(target)
# key = state.identity_key if state.has_identity else id(target)
# session_changes[key] = (target, operation)
, which may contain function names, class names, or code. Output only the next line. | DispatcherSQLEvents(enqueue_change) |
Predict the next line for this snippet: <|code_start|># coding: utf-8
# Python imports
# Django imports
# MAGE imports
#@atomic
class Command(BaseCommand):
args = '<>'
help = 'Will check all installed applications for delivery checkers and install them'
def __init__(self):
super(Command, self).__init__()
self.this_launch = []
def register(self, checker):
if not issubclass(checker, PackageCheckerBaseImpl):
raise Exception('a checker must be a subclass of PackageCheckerBaseImpl (' + checker.__name__ + ')')
print(u'registering checker named ' + checker.__name__)
<|code_end|>
with the help of current file imports:
from django.core.management.base import BaseCommand, CommandError
from django.db.transaction import atomic
from scm.models import PackageChecker, PackageCheckerBaseImpl
from MAGE.settings import INSTALLED_APPS
import importlib
and context from other files:
# Path: scm/models.py
# class PackageChecker(models.Model):
# module = models.CharField(max_length=200, verbose_name='Python module containing the checker class')
# name = models.CharField(max_length=200, verbose_name='Python checker class name')
# description = models.CharField(max_length=200, verbose_name='description')
#
# def check_package(self, package_file, logical_component, installation_method):
# checker_impl = getattr(__import__(self.module, fromlist=[self.name]), self.name)
# checker_impl.check(checker_impl(), package_file, logical_component, installation_method)
#
# def __str__(self):
# return self.description
#
# class PackageCheckerBaseImpl(object):
# description = None
# def check(self, fileinfo, logical_component, installation_method):
# raise NotImplemented()
, which may contain function names, class names, or code. Output only the next line. | pc = PackageChecker.objects.get_or_create(module=checker.__module__ , name=checker.__name__) |
Given the code snippet: <|code_start|># coding: utf-8
# Python imports
# Django imports
# MAGE imports
#@atomic
class Command(BaseCommand):
args = '<>'
help = 'Will check all installed applications for delivery checkers and install them'
def __init__(self):
super(Command, self).__init__()
self.this_launch = []
def register(self, checker):
<|code_end|>
, generate the next line using the imports in this file:
from django.core.management.base import BaseCommand, CommandError
from django.db.transaction import atomic
from scm.models import PackageChecker, PackageCheckerBaseImpl
from MAGE.settings import INSTALLED_APPS
import importlib
and context (functions, classes, or occasionally code) from other files:
# Path: scm/models.py
# class PackageChecker(models.Model):
# module = models.CharField(max_length=200, verbose_name='Python module containing the checker class')
# name = models.CharField(max_length=200, verbose_name='Python checker class name')
# description = models.CharField(max_length=200, verbose_name='description')
#
# def check_package(self, package_file, logical_component, installation_method):
# checker_impl = getattr(__import__(self.module, fromlist=[self.name]), self.name)
# checker_impl.check(checker_impl(), package_file, logical_component, installation_method)
#
# def __str__(self):
# return self.description
#
# class PackageCheckerBaseImpl(object):
# description = None
# def check(self, fileinfo, logical_component, installation_method):
# raise NotImplemented()
. Output only the next line. | if not issubclass(checker, PackageCheckerBaseImpl): |
Predict the next line after this snippet: <|code_start|> envt = Suppress(CaselessLiteral("environment")) + qs('envt')
pre_filter = Optional(envt) + Optional(lc) + Optional(cic) + Optional(impl) + FollowedBy(k_instances)
# Dict query (only select some elements and navigate)
nl_expr = Group(navigation + ZeroOrMore(Suppress(',') + navigation) + FollowedBy(k_from))('selector')
# The sum of all fears
select = Group(
Suppress(k_select) + Optional(nl_expr + Suppress(k_from)) + pre_filter + Suppress(k_instances) + Optional(
where_clause) + Optional(CaselessLiteral('WITH COMPUTATIONS')('compute')))('select')
expr << select
return expr
__grammar = __build_grammar()
def run(query, return_sensitive_data=False):
expr = __grammar.parseString(query)
return __run(expr, return_sensitive_data)
# return __grammar.parseString(query)
def __run(q, return_sensitive_data):
if q.select != None:
return __select_compo(q.select, return_sensitive_data)
def __select_compo(q, return_sensitive_data):
<|code_end|>
using the current file's imports:
from pyparsing import Forward, Group, Suppress, Optional, ZeroOrMore, Combine, \
Word, alphas, nums, QuotedString, CaselessLiteral, FollowedBy
from ref.models.instances import ComponentInstance, ComponentInstanceField, ComponentInstanceRelation
from django.db.models.query import Prefetch
and any relevant context from other files:
# Path: ref/models/instances.py
# class ComponentInstance(models.Model):
# """Instances! Usually used through its proxy object"""
#
# ## Base data for all components
# instanciates = models.ForeignKey('ComponentImplementationClass', null=True, blank=True, verbose_name=u'implémentation de ', related_name='instances', on_delete=models.CASCADE)
# description = models.ForeignKey('ImplementationDescription', related_name='instance_set', verbose_name=u'décrit par l\'implémentation', on_delete=models.CASCADE)
# deleted = models.BooleanField(default=False)
# include_in_envt_backup = models.BooleanField(default=False)
#
# ## Environments
# environments = models.ManyToManyField(Environment, blank=True, verbose_name='environnements ', related_name='component_instances')
#
# ## Connections
# #TODO: symmetrical
# relationships = models.ManyToManyField('self', verbose_name='relations', through=ComponentInstanceRelation, symmetrical=False, related_name='reverse_relationships')
#
# ## Proxy object for easier handling
# __proxy = None
# def build_proxy(self, force=False):
# if self.description_id is None:
# return
# if self.__proxy is None or force:
# self.__proxy = self.description.proxy_class()(base_instance=self)
# return self.__proxy
# proxy = property(build_proxy)
#
# ## First environment (helper)
# def first_environment(self):
# if self.environments.count() > 0:
# return self.environments.all()[0]
# return None
# first_environment.short_description = u'notamment dans'
# first_environment.admin_order_field = 'environments__name'
#
# def _environments_str(self):
# if not self.environments or self.environments.count() == 0:
# return ""
# return ','.join([e.name for e in self.environments.all()])
# environments_str = property(_environments_str)
#
# ## Pretty print
# def __str__(self):
# if self.description:
# return '%s' % self.description.resolve_self_description(self)
# else:
# return '%s' % self.pk
# name = property(__str__)
#
# ## Pretty admin deleted field
# def active(self):
# return not self.deleted
# active.admin_order_field = 'deleted'
# active.boolean = True
#
# class Meta:
# permissions = (('allfields_componentinstance', 'access all fields including restricted ones'),)
# verbose_name = 'instance de composant'
# verbose_name_plural = 'instances de composant'
#
# class ComponentInstanceField(models.Model):
# objects = RichManager()
#
# value = models.CharField(max_length=255, verbose_name='valeur', db_index=True)
# field = models.ForeignKey('ImplementationFieldDescription', verbose_name=u'champ implémenté', on_delete=models.CASCADE)
# instance = models.ForeignKey('ComponentInstance', verbose_name=u'instance de composant', related_name='field_set', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'valeur de champ'
# verbose_name_plural = u'valeurs des champs'
#
# def __str__(self):
# return 'valeur de %s' % self.field.name
#
# class ComponentInstanceRelation(models.Model):
# source = models.ForeignKey('ComponentInstance', related_name='rel_target_set', verbose_name='instance source', on_delete=models.CASCADE)
# target = models.ForeignKey('ComponentInstance', related_name='rel_targeted_by_set', verbose_name='instance cible', on_delete=models.CASCADE)
# field = models.ForeignKey('ImplementationRelationDescription', verbose_name=u'champ implémenté', related_name='field_set', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'valeur de relation'
# verbose_name_plural = u'valeurs des relations'
#
# def __str__(self):
# return 'valeur de %s' % self.field.name
. Output only the next line. | rs = ComponentInstance.objects.filter(deleted=False) |
Based on the snippet: <|code_start|> r[prefix + 'id'] = val
else:
r[prefix + 'field_set__field__name'] = predicate.navigation[-1]
## MQL supports % as a wildcard in first and last position only.
## Because we don't want dependency on an external Django LIKE module.
escaped_val = val.replace("\%", "")
if escaped_val.endswith("%") and escaped_val.startswith("%"):
r[prefix + 'field_set__value__contains'] = val[1:-1]
elif escaped_val.endswith("%"):
r[prefix + 'field_set__value__startswith'] = val[:-1]
print(r)
elif escaped_val.startswith("%"):
r[prefix + 'field_set__value__endswith'] = val[1:]
else:
r[prefix + 'field_set__value'] = val
rs = rs.filter(**r)
if not q.selector:
return __to_dict(rs, use_computed_fields=q.compute, return_sensitive_data=return_sensitive_data)
else:
return __to_dict(rs, q.selector, return_sensitive_data=return_sensitive_data)
def __to_dict(rs, selector=None, optim=True, use_computed_fields=False, return_sensitive_data=False):
'''Navigations are done entirely in memory to avoid hitting too much the database'''
res = []
## All data
if not selector:
<|code_end|>
, predict the immediate next line with the help of imports:
from pyparsing import Forward, Group, Suppress, Optional, ZeroOrMore, Combine, \
Word, alphas, nums, QuotedString, CaselessLiteral, FollowedBy
from ref.models.instances import ComponentInstance, ComponentInstanceField, ComponentInstanceRelation
from django.db.models.query import Prefetch
and context (classes, functions, sometimes code) from other files:
# Path: ref/models/instances.py
# class ComponentInstance(models.Model):
# """Instances! Usually used through its proxy object"""
#
# ## Base data for all components
# instanciates = models.ForeignKey('ComponentImplementationClass', null=True, blank=True, verbose_name=u'implémentation de ', related_name='instances', on_delete=models.CASCADE)
# description = models.ForeignKey('ImplementationDescription', related_name='instance_set', verbose_name=u'décrit par l\'implémentation', on_delete=models.CASCADE)
# deleted = models.BooleanField(default=False)
# include_in_envt_backup = models.BooleanField(default=False)
#
# ## Environments
# environments = models.ManyToManyField(Environment, blank=True, verbose_name='environnements ', related_name='component_instances')
#
# ## Connections
# #TODO: symmetrical
# relationships = models.ManyToManyField('self', verbose_name='relations', through=ComponentInstanceRelation, symmetrical=False, related_name='reverse_relationships')
#
# ## Proxy object for easier handling
# __proxy = None
# def build_proxy(self, force=False):
# if self.description_id is None:
# return
# if self.__proxy is None or force:
# self.__proxy = self.description.proxy_class()(base_instance=self)
# return self.__proxy
# proxy = property(build_proxy)
#
# ## First environment (helper)
# def first_environment(self):
# if self.environments.count() > 0:
# return self.environments.all()[0]
# return None
# first_environment.short_description = u'notamment dans'
# first_environment.admin_order_field = 'environments__name'
#
# def _environments_str(self):
# if not self.environments or self.environments.count() == 0:
# return ""
# return ','.join([e.name for e in self.environments.all()])
# environments_str = property(_environments_str)
#
# ## Pretty print
# def __str__(self):
# if self.description:
# return '%s' % self.description.resolve_self_description(self)
# else:
# return '%s' % self.pk
# name = property(__str__)
#
# ## Pretty admin deleted field
# def active(self):
# return not self.deleted
# active.admin_order_field = 'deleted'
# active.boolean = True
#
# class Meta:
# permissions = (('allfields_componentinstance', 'access all fields including restricted ones'),)
# verbose_name = 'instance de composant'
# verbose_name_plural = 'instances de composant'
#
# class ComponentInstanceField(models.Model):
# objects = RichManager()
#
# value = models.CharField(max_length=255, verbose_name='valeur', db_index=True)
# field = models.ForeignKey('ImplementationFieldDescription', verbose_name=u'champ implémenté', on_delete=models.CASCADE)
# instance = models.ForeignKey('ComponentInstance', verbose_name=u'instance de composant', related_name='field_set', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'valeur de champ'
# verbose_name_plural = u'valeurs des champs'
#
# def __str__(self):
# return 'valeur de %s' % self.field.name
#
# class ComponentInstanceRelation(models.Model):
# source = models.ForeignKey('ComponentInstance', related_name='rel_target_set', verbose_name='instance source', on_delete=models.CASCADE)
# target = models.ForeignKey('ComponentInstance', related_name='rel_targeted_by_set', verbose_name='instance cible', on_delete=models.CASCADE)
# field = models.ForeignKey('ImplementationRelationDescription', verbose_name=u'champ implémenté', related_name='field_set', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'valeur de relation'
# verbose_name_plural = u'valeurs des relations'
#
# def __str__(self):
# return 'valeur de %s' % self.field.name
. Output only the next line. | rs = rs.prefetch_related(Prefetch('field_set', queryset=ComponentInstanceField.objects.select_related('field'))) |
Predict the next line for this snippet: <|code_start|> r[prefix + 'field_set__field__name'] = predicate.navigation[-1]
## MQL supports % as a wildcard in first and last position only.
## Because we don't want dependency on an external Django LIKE module.
escaped_val = val.replace("\%", "")
if escaped_val.endswith("%") and escaped_val.startswith("%"):
r[prefix + 'field_set__value__contains'] = val[1:-1]
elif escaped_val.endswith("%"):
r[prefix + 'field_set__value__startswith'] = val[:-1]
print(r)
elif escaped_val.startswith("%"):
r[prefix + 'field_set__value__endswith'] = val[1:]
else:
r[prefix + 'field_set__value'] = val
rs = rs.filter(**r)
if not q.selector:
return __to_dict(rs, use_computed_fields=q.compute, return_sensitive_data=return_sensitive_data)
else:
return __to_dict(rs, q.selector, return_sensitive_data=return_sensitive_data)
def __to_dict(rs, selector=None, optim=True, use_computed_fields=False, return_sensitive_data=False):
'''Navigations are done entirely in memory to avoid hitting too much the database'''
res = []
## All data
if not selector:
rs = rs.prefetch_related(Prefetch('field_set', queryset=ComponentInstanceField.objects.select_related('field')))
rs = rs.prefetch_related(
<|code_end|>
with the help of current file imports:
from pyparsing import Forward, Group, Suppress, Optional, ZeroOrMore, Combine, \
Word, alphas, nums, QuotedString, CaselessLiteral, FollowedBy
from ref.models.instances import ComponentInstance, ComponentInstanceField, ComponentInstanceRelation
from django.db.models.query import Prefetch
and context from other files:
# Path: ref/models/instances.py
# class ComponentInstance(models.Model):
# """Instances! Usually used through its proxy object"""
#
# ## Base data for all components
# instanciates = models.ForeignKey('ComponentImplementationClass', null=True, blank=True, verbose_name=u'implémentation de ', related_name='instances', on_delete=models.CASCADE)
# description = models.ForeignKey('ImplementationDescription', related_name='instance_set', verbose_name=u'décrit par l\'implémentation', on_delete=models.CASCADE)
# deleted = models.BooleanField(default=False)
# include_in_envt_backup = models.BooleanField(default=False)
#
# ## Environments
# environments = models.ManyToManyField(Environment, blank=True, verbose_name='environnements ', related_name='component_instances')
#
# ## Connections
# #TODO: symmetrical
# relationships = models.ManyToManyField('self', verbose_name='relations', through=ComponentInstanceRelation, symmetrical=False, related_name='reverse_relationships')
#
# ## Proxy object for easier handling
# __proxy = None
# def build_proxy(self, force=False):
# if self.description_id is None:
# return
# if self.__proxy is None or force:
# self.__proxy = self.description.proxy_class()(base_instance=self)
# return self.__proxy
# proxy = property(build_proxy)
#
# ## First environment (helper)
# def first_environment(self):
# if self.environments.count() > 0:
# return self.environments.all()[0]
# return None
# first_environment.short_description = u'notamment dans'
# first_environment.admin_order_field = 'environments__name'
#
# def _environments_str(self):
# if not self.environments or self.environments.count() == 0:
# return ""
# return ','.join([e.name for e in self.environments.all()])
# environments_str = property(_environments_str)
#
# ## Pretty print
# def __str__(self):
# if self.description:
# return '%s' % self.description.resolve_self_description(self)
# else:
# return '%s' % self.pk
# name = property(__str__)
#
# ## Pretty admin deleted field
# def active(self):
# return not self.deleted
# active.admin_order_field = 'deleted'
# active.boolean = True
#
# class Meta:
# permissions = (('allfields_componentinstance', 'access all fields including restricted ones'),)
# verbose_name = 'instance de composant'
# verbose_name_plural = 'instances de composant'
#
# class ComponentInstanceField(models.Model):
# objects = RichManager()
#
# value = models.CharField(max_length=255, verbose_name='valeur', db_index=True)
# field = models.ForeignKey('ImplementationFieldDescription', verbose_name=u'champ implémenté', on_delete=models.CASCADE)
# instance = models.ForeignKey('ComponentInstance', verbose_name=u'instance de composant', related_name='field_set', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'valeur de champ'
# verbose_name_plural = u'valeurs des champs'
#
# def __str__(self):
# return 'valeur de %s' % self.field.name
#
# class ComponentInstanceRelation(models.Model):
# source = models.ForeignKey('ComponentInstance', related_name='rel_target_set', verbose_name='instance source', on_delete=models.CASCADE)
# target = models.ForeignKey('ComponentInstance', related_name='rel_targeted_by_set', verbose_name='instance cible', on_delete=models.CASCADE)
# field = models.ForeignKey('ImplementationRelationDescription', verbose_name=u'champ implémenté', related_name='field_set', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'valeur de relation'
# verbose_name_plural = u'valeurs des relations'
#
# def __str__(self):
# return 'valeur de %s' % self.field.name
, which may contain function names, class names, or code. Output only the next line. | Prefetch('rel_target_set', queryset=ComponentInstanceRelation.objects.select_related('field'))) |
Predict the next line after this snippet: <|code_start|> for ii in ii_selection:
if ii.belongs_to_set != iset:
raise MageScmCallerError('an Installable Item does not belong to the specified set')
if install_date is None:
install_date = now()
## Check prerequisites
try:
iset.check_prerequisites(envt.name, ii_selection)
except MageScmFailedEnvironmentDependencyCheck as e:
if not force_prereqs:
raise e
## Select targets
install_detail = []
for compo in targets:
## Is the compo patchable?
if not compo.instanciates:
raise MageScmError('a given component\'s configuration cannot be managed as it has no implementation class')
## Is there a corresponding element in the IS? (same CIC (through IM))
ii_list = iset.set_content.filter(how_to_install__method_compatible_with=compo.instanciates).filter(what_is_installed__logical_component = compo.instanciates.implements).order_by('pk') # sort PK: gives patch order
if ii_list.count() == 0:
continue
## If here, there are IS concerning the component. Mark them for install.
for ii in ii_list:
install_detail.append((compo, ii))
## Registration
<|code_end|>
using the current file's imports:
from datetime import timedelta
from django.utils.timezone import now
from scm.exceptions import MageScmError, MageScmCallerError,\
MageScmFailedEnvironmentDependencyCheck
from scm.models import Installation, ComponentInstanceConfiguration
from ref.models.parameters import getParam
and any relevant context from other files:
# Path: scm/models.py
# class Installation(models.Model):
# installed_set = models.ForeignKey(InstallableSet, verbose_name='livraison appliquée ', on_delete=models.CASCADE)
# asked_in_ticket = models.CharField(max_length=10, verbose_name='ticket lié ', blank=True, null=True)
# install_date = models.DateTimeField(verbose_name='date d\installation ')
#
# def __str__(self):
# return '%s sur %s le %s' % (self.installed_set.name, [i.component_instance.environments.all() for i in self.modified_components.all()], self.install_date)
#
# class ComponentInstanceConfiguration(models.Model):
# component_instance = models.ForeignKey(ComponentInstance, related_name='configurations', on_delete=models.CASCADE)
# result_of = models.ForeignKey(InstallableItem, on_delete=models.CASCADE)
# part_of_installation = models.ForeignKey(Installation, related_name='modified_components', on_delete=models.CASCADE)
# created_on = models.DateTimeField()
# install_failure = models.BooleanField(default=False)
#
# def __str__(self):
# return u'At %s, component %s was at version %s' % (self.created_on, self.component_instance.name, self.result_of.what_is_installed.version)
#
# Path: ref/models/parameters.py
# def getParam(key, **others):
# """
# Retrieves a parameter.
# This function hits the database, so it should be called as little as possible.
#
# @return: the parameter value as a string (unicode).
# @raise ParamNotFound: if the param cannot be found, or if multiple params were found.
# """
# if others and 'app' in others: app = others['app']
# else: app = sys._getframe(1).f_globals['__name__'].split('.')[0]
# filters = others or {}
# filters['app'] = app
# filters['key'] = key
#
# try:
# return MageParam.objects.get(**filters).value
# except (MageParam.DoesNotExist, MageParam.MultipleObjectsReturned):
# raise ParamNotFound(filters)
. Output only the next line. | i = Installation(installed_set = iset, install_date = install_date, asked_in_ticket = ticket) |
Based on the snippet: <|code_start|> ## Check prerequisites
try:
iset.check_prerequisites(envt.name, ii_selection)
except MageScmFailedEnvironmentDependencyCheck as e:
if not force_prereqs:
raise e
## Select targets
install_detail = []
for compo in targets:
## Is the compo patchable?
if not compo.instanciates:
raise MageScmError('a given component\'s configuration cannot be managed as it has no implementation class')
## Is there a corresponding element in the IS? (same CIC (through IM))
ii_list = iset.set_content.filter(how_to_install__method_compatible_with=compo.instanciates).filter(what_is_installed__logical_component = compo.instanciates.implements).order_by('pk') # sort PK: gives patch order
if ii_list.count() == 0:
continue
## If here, there are IS concerning the component. Mark them for install.
for ii in ii_list:
install_detail.append((compo, ii))
## Registration
i = Installation(installed_set = iset, install_date = install_date, asked_in_ticket = ticket)
i.save()
for duet in install_detail:
compo = duet[0]
ii = duet[1]
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import timedelta
from django.utils.timezone import now
from scm.exceptions import MageScmError, MageScmCallerError,\
MageScmFailedEnvironmentDependencyCheck
from scm.models import Installation, ComponentInstanceConfiguration
from ref.models.parameters import getParam
and context (classes, functions, sometimes code) from other files:
# Path: scm/models.py
# class Installation(models.Model):
# installed_set = models.ForeignKey(InstallableSet, verbose_name='livraison appliquée ', on_delete=models.CASCADE)
# asked_in_ticket = models.CharField(max_length=10, verbose_name='ticket lié ', blank=True, null=True)
# install_date = models.DateTimeField(verbose_name='date d\installation ')
#
# def __str__(self):
# return '%s sur %s le %s' % (self.installed_set.name, [i.component_instance.environments.all() for i in self.modified_components.all()], self.install_date)
#
# class ComponentInstanceConfiguration(models.Model):
# component_instance = models.ForeignKey(ComponentInstance, related_name='configurations', on_delete=models.CASCADE)
# result_of = models.ForeignKey(InstallableItem, on_delete=models.CASCADE)
# part_of_installation = models.ForeignKey(Installation, related_name='modified_components', on_delete=models.CASCADE)
# created_on = models.DateTimeField()
# install_failure = models.BooleanField(default=False)
#
# def __str__(self):
# return u'At %s, component %s was at version %s' % (self.created_on, self.component_instance.name, self.result_of.what_is_installed.version)
#
# Path: ref/models/parameters.py
# def getParam(key, **others):
# """
# Retrieves a parameter.
# This function hits the database, so it should be called as little as possible.
#
# @return: the parameter value as a string (unicode).
# @raise ParamNotFound: if the param cannot be found, or if multiple params were found.
# """
# if others and 'app' in others: app = others['app']
# else: app = sys._getframe(1).f_globals['__name__'].split('.')[0]
# filters = others or {}
# filters['app'] = app
# filters['key'] = key
#
# try:
# return MageParam.objects.get(**filters).value
# except (MageParam.DoesNotExist, MageParam.MultipleObjectsReturned):
# raise ParamNotFound(filters)
. Output only the next line. | cic = ComponentInstanceConfiguration(component_instance = compo, result_of = ii, part_of_installation = i, created_on = install_date) |
Predict the next line after this snippet: <|code_start|> continue
## If here, there are IS concerning the component. Mark them for install.
for ii in ii_list:
install_detail.append((compo, ii))
## Registration
i = Installation(installed_set = iset, install_date = install_date, asked_in_ticket = ticket)
i.save()
for duet in install_detail:
compo = duet[0]
ii = duet[1]
cic = ComponentInstanceConfiguration(component_instance = compo, result_of = ii, part_of_installation = i, created_on = install_date)
cic.save()
def install_ii_single_target_envt(ii, instance, envt, force_prereqs = False, install_date = None, ticket = None, install = None):
iset = ii.belongs_to_set
if install_date is None:
install_date = now()
## Check prerequisites
try:
iset.check_prerequisites(envt.name)
except MageScmFailedEnvironmentDependencyCheck as e:
if not force_prereqs:
raise e
if install is None:
## Check if an install is in progress
<|code_end|>
using the current file's imports:
from datetime import timedelta
from django.utils.timezone import now
from scm.exceptions import MageScmError, MageScmCallerError,\
MageScmFailedEnvironmentDependencyCheck
from scm.models import Installation, ComponentInstanceConfiguration
from ref.models.parameters import getParam
and any relevant context from other files:
# Path: scm/models.py
# class Installation(models.Model):
# installed_set = models.ForeignKey(InstallableSet, verbose_name='livraison appliquée ', on_delete=models.CASCADE)
# asked_in_ticket = models.CharField(max_length=10, verbose_name='ticket lié ', blank=True, null=True)
# install_date = models.DateTimeField(verbose_name='date d\installation ')
#
# def __str__(self):
# return '%s sur %s le %s' % (self.installed_set.name, [i.component_instance.environments.all() for i in self.modified_components.all()], self.install_date)
#
# class ComponentInstanceConfiguration(models.Model):
# component_instance = models.ForeignKey(ComponentInstance, related_name='configurations', on_delete=models.CASCADE)
# result_of = models.ForeignKey(InstallableItem, on_delete=models.CASCADE)
# part_of_installation = models.ForeignKey(Installation, related_name='modified_components', on_delete=models.CASCADE)
# created_on = models.DateTimeField()
# install_failure = models.BooleanField(default=False)
#
# def __str__(self):
# return u'At %s, component %s was at version %s' % (self.created_on, self.component_instance.name, self.result_of.what_is_installed.version)
#
# Path: ref/models/parameters.py
# def getParam(key, **others):
# """
# Retrieves a parameter.
# This function hits the database, so it should be called as little as possible.
#
# @return: the parameter value as a string (unicode).
# @raise ParamNotFound: if the param cannot be found, or if multiple params were found.
# """
# if others and 'app' in others: app = others['app']
# else: app = sys._getframe(1).f_globals['__name__'].split('.')[0]
# filters = others or {}
# filters['app'] = app
# filters['key'] = key
#
# try:
# return MageParam.objects.get(**filters).value
# except (MageParam.DoesNotExist, MageParam.MultipleObjectsReturned):
# raise ParamNotFound(filters)
. Output only the next line. | limit = int(getParam('APPLY_MERGE_LIMIT')) |
Using the snippet: <|code_start|># coding: utf-8
# Python imports
# Django imports
# MAGE imports
@atomic
class Command(BaseCommand):
args = '<older_than_days>'
help = 'Purges old archived backupsets from the database. Sets that were used for at least one restoration are left untouched.'
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError('no parameter specified')
try:
days = int(args[0])
except:
raise CommandError('parameter should be an integer')
limit = timezone.now() - timedelta(days=days)
<|code_end|>
, determine the next line of code. You have imports:
from datetime import timedelta
from django.core.management.base import BaseCommand, CommandError
from django.db.models.aggregates import Count
from django.utils import timezone
from django.db.transaction import atomic
from scm.models import BackupSet
and context (class names, function names, or code) available:
# Path: scm/models.py
# class BackupSet(InstallableSet):
# from_envt = models.ForeignKey(Environment, blank=True, null=True, on_delete=models.CASCADE)
. Output only the next line. | init = BackupSet.objects.filter(removed__isnull=False).count() |
Based on the snippet: <|code_start|># coding: utf-8
'''
@license: Apache License, Version 2.0
@copyright: 2007-2013 Marc-Antoine Gouillart
@author: Marc-Antoine Gouillart
'''
<|code_end|>
, predict the immediate next line with the help of imports:
from ref import admin
from scm.models import BackupRestoreMethod, InstallationMethod, BackupSet, \
PackageChecker
and context (classes, functions, sometimes code) from other files:
# Path: ref/admin.py
# class MageParamAdmin(ModelAdmin):
# class EnvironmentAdmin(ModelAdmin):
# class EnvironmentTypeAdmin(ModelAdmin):
# class LogicalComponentAdmin(ModelAdmin):
# class ApplicationAdmin(ModelAdmin):
# class ProjectAdmin(ModelAdmin):
# class LinkAdmin(ModelAdmin):
# class CICAdmin(ModelAdmin):
# class ImplementationRelationTypeAdmin(ModelAdmin):
# class ImplementationFieldDescriptionInline(TabularInline):
# class ImplementationRelationDescriptionInline(TabularInline):
# class ImplementationComputedFieldDescriptionInline(TabularInline):
# class ImplementationDescriptionAdmin(ModelAdmin):
# class ConventionCounterAdmin(ModelAdmin):
# class ExtendedParameterInline(TabularInline):
# class ComponentInstanceFieldAdmin(TabularInline):
# class ComponentInstanceRelationAdmin(TabularInline):
# class ComponentInstanceAdmin(ModelAdmin):
# def has_delete_permission(self, request, obj=None):
# def get_actions(self, request):
#
# Path: scm/models.py
# class BackupRestoreMethod(models.Model):
# """
# BMRs are needed because there may be multiple InstallationMethods available for the same CIC. Therefore,
# we need a mean to know which InstallationMethod to use to restore a backup.
# There cannot be more than one BMR per CIC (we are talking default restoration method - only one default!)
# """
# method = models.ForeignKey(InstallationMethod, on_delete=models.CASCADE)
# target = models.ForeignKey(ComponentImplementationClass, related_name='restore_methods', verbose_name='cible', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'méthode de restauration par défaut'
# verbose_name_plural = 'méthodes de restauration par défaut'
#
# class InstallationMethod(models.Model):
# name = models.CharField(max_length=254, verbose_name=u'nom')
# halts_service = models.BooleanField(default=True, verbose_name=u'arrêt de service')
# method_compatible_with = models.ManyToManyField(ComponentImplementationClass, related_name='installation_methods', verbose_name=u'permet d\'installer')
# available = models.BooleanField(default=True, verbose_name=u'disponible')
# restoration_only = models.BooleanField(default=False, verbose_name=u'opération purement de restauration')
# checkers = models.ManyToManyField('PackageChecker', related_name='used_in', blank=True)
#
# def __str__(self):
# a = ""
# if not self.available:
# a = "OBSOLETE - "
# return u'%s%s' % (a, self.name) #, ",".join([ i.name for i in self.method_compatible_with.all()]))
#
# def check_package(self, package_file, logical_component):
# for checker in self.checkers.all():
# checker.check_package(package_file, logical_component, self)
#
# class Meta:
# verbose_name = u'méthode d\'installation'
# verbose_name_plural = u'méthodes d\'installation'
#
# class BackupSet(InstallableSet):
# from_envt = models.ForeignKey(Environment, blank=True, null=True, on_delete=models.CASCADE)
#
# class PackageChecker(models.Model):
# module = models.CharField(max_length=200, verbose_name='Python module containing the checker class')
# name = models.CharField(max_length=200, verbose_name='Python checker class name')
# description = models.CharField(max_length=200, verbose_name='description')
#
# def check_package(self, package_file, logical_component, installation_method):
# checker_impl = getattr(__import__(self.module, fromlist=[self.name]), self.name)
# checker_impl.check(checker_impl(), package_file, logical_component, installation_method)
#
# def __str__(self):
# return self.description
. Output only the next line. | class BackupRestoreMethodAdmin(admin.ModelAdmin): |
Given the code snippet: <|code_start|># coding: utf-8
'''
@license: Apache License, Version 2.0
@copyright: 2007-2013 Marc-Antoine Gouillart
@author: Marc-Antoine Gouillart
'''
class BackupRestoreMethodAdmin(admin.ModelAdmin):
list_display = ('target', 'method')
ordering = ('target',)
def has_delete_permission(self, request, obj=None):
return False
def get_actions(self, request):
actions = super(BackupRestoreMethodAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
<|code_end|>
, generate the next line using the imports in this file:
from ref import admin
from scm.models import BackupRestoreMethod, InstallationMethod, BackupSet, \
PackageChecker
and context (functions, classes, or occasionally code) from other files:
# Path: ref/admin.py
# class MageParamAdmin(ModelAdmin):
# class EnvironmentAdmin(ModelAdmin):
# class EnvironmentTypeAdmin(ModelAdmin):
# class LogicalComponentAdmin(ModelAdmin):
# class ApplicationAdmin(ModelAdmin):
# class ProjectAdmin(ModelAdmin):
# class LinkAdmin(ModelAdmin):
# class CICAdmin(ModelAdmin):
# class ImplementationRelationTypeAdmin(ModelAdmin):
# class ImplementationFieldDescriptionInline(TabularInline):
# class ImplementationRelationDescriptionInline(TabularInline):
# class ImplementationComputedFieldDescriptionInline(TabularInline):
# class ImplementationDescriptionAdmin(ModelAdmin):
# class ConventionCounterAdmin(ModelAdmin):
# class ExtendedParameterInline(TabularInline):
# class ComponentInstanceFieldAdmin(TabularInline):
# class ComponentInstanceRelationAdmin(TabularInline):
# class ComponentInstanceAdmin(ModelAdmin):
# def has_delete_permission(self, request, obj=None):
# def get_actions(self, request):
#
# Path: scm/models.py
# class BackupRestoreMethod(models.Model):
# """
# BMRs are needed because there may be multiple InstallationMethods available for the same CIC. Therefore,
# we need a mean to know which InstallationMethod to use to restore a backup.
# There cannot be more than one BMR per CIC (we are talking default restoration method - only one default!)
# """
# method = models.ForeignKey(InstallationMethod, on_delete=models.CASCADE)
# target = models.ForeignKey(ComponentImplementationClass, related_name='restore_methods', verbose_name='cible', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'méthode de restauration par défaut'
# verbose_name_plural = 'méthodes de restauration par défaut'
#
# class InstallationMethod(models.Model):
# name = models.CharField(max_length=254, verbose_name=u'nom')
# halts_service = models.BooleanField(default=True, verbose_name=u'arrêt de service')
# method_compatible_with = models.ManyToManyField(ComponentImplementationClass, related_name='installation_methods', verbose_name=u'permet d\'installer')
# available = models.BooleanField(default=True, verbose_name=u'disponible')
# restoration_only = models.BooleanField(default=False, verbose_name=u'opération purement de restauration')
# checkers = models.ManyToManyField('PackageChecker', related_name='used_in', blank=True)
#
# def __str__(self):
# a = ""
# if not self.available:
# a = "OBSOLETE - "
# return u'%s%s' % (a, self.name) #, ",".join([ i.name for i in self.method_compatible_with.all()]))
#
# def check_package(self, package_file, logical_component):
# for checker in self.checkers.all():
# checker.check_package(package_file, logical_component, self)
#
# class Meta:
# verbose_name = u'méthode d\'installation'
# verbose_name_plural = u'méthodes d\'installation'
#
# class BackupSet(InstallableSet):
# from_envt = models.ForeignKey(Environment, blank=True, null=True, on_delete=models.CASCADE)
#
# class PackageChecker(models.Model):
# module = models.CharField(max_length=200, verbose_name='Python module containing the checker class')
# name = models.CharField(max_length=200, verbose_name='Python checker class name')
# description = models.CharField(max_length=200, verbose_name='description')
#
# def check_package(self, package_file, logical_component, installation_method):
# checker_impl = getattr(__import__(self.module, fromlist=[self.name]), self.name)
# checker_impl.check(checker_impl(), package_file, logical_component, installation_method)
#
# def __str__(self):
# return self.description
. Output only the next line. | admin.site.register(BackupRestoreMethod, BackupRestoreMethodAdmin) |
Next line prediction: <|code_start|>
class BackupRestoreMethodAdmin(admin.ModelAdmin):
list_display = ('target', 'method')
ordering = ('target',)
def has_delete_permission(self, request, obj=None):
return False
def get_actions(self, request):
actions = super(BackupRestoreMethodAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
admin.site.register(BackupRestoreMethod, BackupRestoreMethodAdmin)
class InstallationMethodAdmin(admin.ModelAdmin):
list_display = ('name', 'halts_service', 'available', 'restoration_only')
ordering = ('name',)
list_filter = ('available', 'restoration_only')
filter_horizontal = ('method_compatible_with', 'checkers',)
def has_delete_permission(self, request, obj=None):
return False
def get_actions(self, request):
actions = super(InstallationMethodAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
<|code_end|>
. Use current file imports:
(from ref import admin
from scm.models import BackupRestoreMethod, InstallationMethod, BackupSet, \
PackageChecker)
and context including class names, function names, or small code snippets from other files:
# Path: ref/admin.py
# class MageParamAdmin(ModelAdmin):
# class EnvironmentAdmin(ModelAdmin):
# class EnvironmentTypeAdmin(ModelAdmin):
# class LogicalComponentAdmin(ModelAdmin):
# class ApplicationAdmin(ModelAdmin):
# class ProjectAdmin(ModelAdmin):
# class LinkAdmin(ModelAdmin):
# class CICAdmin(ModelAdmin):
# class ImplementationRelationTypeAdmin(ModelAdmin):
# class ImplementationFieldDescriptionInline(TabularInline):
# class ImplementationRelationDescriptionInline(TabularInline):
# class ImplementationComputedFieldDescriptionInline(TabularInline):
# class ImplementationDescriptionAdmin(ModelAdmin):
# class ConventionCounterAdmin(ModelAdmin):
# class ExtendedParameterInline(TabularInline):
# class ComponentInstanceFieldAdmin(TabularInline):
# class ComponentInstanceRelationAdmin(TabularInline):
# class ComponentInstanceAdmin(ModelAdmin):
# def has_delete_permission(self, request, obj=None):
# def get_actions(self, request):
#
# Path: scm/models.py
# class BackupRestoreMethod(models.Model):
# """
# BMRs are needed because there may be multiple InstallationMethods available for the same CIC. Therefore,
# we need a mean to know which InstallationMethod to use to restore a backup.
# There cannot be more than one BMR per CIC (we are talking default restoration method - only one default!)
# """
# method = models.ForeignKey(InstallationMethod, on_delete=models.CASCADE)
# target = models.ForeignKey(ComponentImplementationClass, related_name='restore_methods', verbose_name='cible', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'méthode de restauration par défaut'
# verbose_name_plural = 'méthodes de restauration par défaut'
#
# class InstallationMethod(models.Model):
# name = models.CharField(max_length=254, verbose_name=u'nom')
# halts_service = models.BooleanField(default=True, verbose_name=u'arrêt de service')
# method_compatible_with = models.ManyToManyField(ComponentImplementationClass, related_name='installation_methods', verbose_name=u'permet d\'installer')
# available = models.BooleanField(default=True, verbose_name=u'disponible')
# restoration_only = models.BooleanField(default=False, verbose_name=u'opération purement de restauration')
# checkers = models.ManyToManyField('PackageChecker', related_name='used_in', blank=True)
#
# def __str__(self):
# a = ""
# if not self.available:
# a = "OBSOLETE - "
# return u'%s%s' % (a, self.name) #, ",".join([ i.name for i in self.method_compatible_with.all()]))
#
# def check_package(self, package_file, logical_component):
# for checker in self.checkers.all():
# checker.check_package(package_file, logical_component, self)
#
# class Meta:
# verbose_name = u'méthode d\'installation'
# verbose_name_plural = u'méthodes d\'installation'
#
# class BackupSet(InstallableSet):
# from_envt = models.ForeignKey(Environment, blank=True, null=True, on_delete=models.CASCADE)
#
# class PackageChecker(models.Model):
# module = models.CharField(max_length=200, verbose_name='Python module containing the checker class')
# name = models.CharField(max_length=200, verbose_name='Python checker class name')
# description = models.CharField(max_length=200, verbose_name='description')
#
# def check_package(self, package_file, logical_component, installation_method):
# checker_impl = getattr(__import__(self.module, fromlist=[self.name]), self.name)
# checker_impl.check(checker_impl(), package_file, logical_component, installation_method)
#
# def __str__(self):
# return self.description
. Output only the next line. | admin.site.register(InstallationMethod, InstallationMethodAdmin) |
Given the following code snippet before the placeholder: <|code_start|>
def has_delete_permission(self, request, obj=None):
return False
def get_actions(self, request):
actions = super(InstallationMethodAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
admin.site.register(InstallationMethod, InstallationMethodAdmin)
class BackupSetAdmin(admin.ModelAdmin):
list_display = ('name', 'is_available', 'from_envt')
list_filter = ('from_envt', 'set_date', 'removed')
def has_delete_permission(self, request, obj=None):
return False
def get_actions(self, request):
actions = super(BackupSetAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
#admin.site.register(BackupSet, BackupSetAdmin)
class PackageCheckerAdmin(admin.ModelAdmin):
list_display = ('description', 'module', 'name',)
readonly_fields = ('module', 'name')
<|code_end|>
, predict the next line using imports from the current file:
from ref import admin
from scm.models import BackupRestoreMethod, InstallationMethod, BackupSet, \
PackageChecker
and context including class names, function names, and sometimes code from other files:
# Path: ref/admin.py
# class MageParamAdmin(ModelAdmin):
# class EnvironmentAdmin(ModelAdmin):
# class EnvironmentTypeAdmin(ModelAdmin):
# class LogicalComponentAdmin(ModelAdmin):
# class ApplicationAdmin(ModelAdmin):
# class ProjectAdmin(ModelAdmin):
# class LinkAdmin(ModelAdmin):
# class CICAdmin(ModelAdmin):
# class ImplementationRelationTypeAdmin(ModelAdmin):
# class ImplementationFieldDescriptionInline(TabularInline):
# class ImplementationRelationDescriptionInline(TabularInline):
# class ImplementationComputedFieldDescriptionInline(TabularInline):
# class ImplementationDescriptionAdmin(ModelAdmin):
# class ConventionCounterAdmin(ModelAdmin):
# class ExtendedParameterInline(TabularInline):
# class ComponentInstanceFieldAdmin(TabularInline):
# class ComponentInstanceRelationAdmin(TabularInline):
# class ComponentInstanceAdmin(ModelAdmin):
# def has_delete_permission(self, request, obj=None):
# def get_actions(self, request):
#
# Path: scm/models.py
# class BackupRestoreMethod(models.Model):
# """
# BMRs are needed because there may be multiple InstallationMethods available for the same CIC. Therefore,
# we need a mean to know which InstallationMethod to use to restore a backup.
# There cannot be more than one BMR per CIC (we are talking default restoration method - only one default!)
# """
# method = models.ForeignKey(InstallationMethod, on_delete=models.CASCADE)
# target = models.ForeignKey(ComponentImplementationClass, related_name='restore_methods', verbose_name='cible', on_delete=models.CASCADE)
#
# class Meta:
# verbose_name = u'méthode de restauration par défaut'
# verbose_name_plural = 'méthodes de restauration par défaut'
#
# class InstallationMethod(models.Model):
# name = models.CharField(max_length=254, verbose_name=u'nom')
# halts_service = models.BooleanField(default=True, verbose_name=u'arrêt de service')
# method_compatible_with = models.ManyToManyField(ComponentImplementationClass, related_name='installation_methods', verbose_name=u'permet d\'installer')
# available = models.BooleanField(default=True, verbose_name=u'disponible')
# restoration_only = models.BooleanField(default=False, verbose_name=u'opération purement de restauration')
# checkers = models.ManyToManyField('PackageChecker', related_name='used_in', blank=True)
#
# def __str__(self):
# a = ""
# if not self.available:
# a = "OBSOLETE - "
# return u'%s%s' % (a, self.name) #, ",".join([ i.name for i in self.method_compatible_with.all()]))
#
# def check_package(self, package_file, logical_component):
# for checker in self.checkers.all():
# checker.check_package(package_file, logical_component, self)
#
# class Meta:
# verbose_name = u'méthode d\'installation'
# verbose_name_plural = u'méthodes d\'installation'
#
# class BackupSet(InstallableSet):
# from_envt = models.ForeignKey(Environment, blank=True, null=True, on_delete=models.CASCADE)
#
# class PackageChecker(models.Model):
# module = models.CharField(max_length=200, verbose_name='Python module containing the checker class')
# name = models.CharField(max_length=200, verbose_name='Python checker class name')
# description = models.CharField(max_length=200, verbose_name='description')
#
# def check_package(self, package_file, logical_component, installation_method):
# checker_impl = getattr(__import__(self.module, fromlist=[self.name]), self.name)
# checker_impl.check(checker_impl(), package_file, logical_component, installation_method)
#
# def __str__(self):
# return self.description
. Output only the next line. | admin.site.register(PackageChecker, PackageCheckerAdmin) |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
class CacheStateHandler(object):
"""
State handlers that relies on cache to store and retrieve the current
checksum of a definition."
"""
def __init__(self):
<|code_end|>
, generate the next line using the imports in this file:
from django.core.cache import caches
from ...settings import STATE_CACHE_ALIAS
and context (functions, classes, or occasionally code) from other files:
# Path: mutant/settings.py
# STATE_CACHE_ALIAS = getattr(
# settings, 'MUTANT_STATE_CACHE_ALIAS', DEFAULT_CACHE_ALIAS
# )
. Output only the next line. | self.cache = caches[STATE_CACHE_ALIAS] |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
class DataCommandTestCase(BaseModelDefinitionTestCase):
def setUp(self):
super(DataCommandTestCase, self).setUp()
self.model_cls = self.model_def.model_class()
class DumpDataTestCase(DataCommandTestCase):
def dump_model_data(self):
# Make sure to remove the model from the app cache because we're
# actually testing it's correctly loaded.
output = StringIO()
<|code_end|>
, predict the next line using imports from the current file:
import json
from tempfile import NamedTemporaryFile
from django.core.management import call_command
from django.core.serializers.base import DeserializationError
from django.core.serializers.json import Serializer as JSONSerializer
from django.utils.encoding import force_bytes
from django.utils.six import StringIO
from mutant.utils import remove_from_app_cache
from .utils import BaseModelDefinitionTestCase
and context including class names, function names, and sometimes code from other files:
# Path: mutant/utils.py
# def remove_from_app_cache(model_class, quiet=False):
# opts = model_class._meta
# apps = opts.apps
# app_label, model_name = opts.app_label, opts.model_name
# with apps_lock():
# try:
# model_class = apps.app_configs[app_label].models.pop(model_name)
# except KeyError:
# if not quiet:
# raise ValueError("%r is not cached" % model_class)
# apps.clear_cache()
# unreference_model(model_class)
# return model_class
#
# Path: tests/utils.py
# class BaseModelDefinitionTestCase(ModelDefinitionDDLTestCase):
# @classmethod
# def setUpTestData(cls):
# model_def = ModelDefinition.objects.create(app_label='mutant', object_name='Model')
# cls.model_def_pk = model_def.pk
#
# def setUp(self):
# self.model_def = ModelDefinition.objects.get(pk=self.model_def_pk)
#
# @classmethod
# @contextmanager
# def assertChecksumChange(cls, model_def=None):
# if not model_def:
# model_def = ModelDefinition.objects.get(pk=cls.model_def_pk)
# checksum = model_def.model_class().checksum()
# yield
# if model_def.model_class().checksum() == checksum:
# raise AssertionError("Checksum of model %s should have changed." % model_def)
#
# @classmethod
# @contextmanager
# def assertChecksumDoesntChange(cls, model_def=None):
# if not model_def:
# model_def = ModelDefinition.objects.get(pk=cls.model_def_pk)
# try:
# with cls.assertChecksumChange(model_def):
# yield
# except AssertionError:
# pass
# else:
# model_class = model_def.model_class()
# raise AssertionError("Checksum of model %s shouldn't have changed." % model_class)
#
# def assertTableExists(self, db, table):
# tables = connections[db].introspection.table_names()
# msg = "Table '%s.%s' doesn't exist, existing tables are %s"
# self.assertTrue(table in tables, msg % (db, table, tables))
#
# def assertTableDoesntExists(self, db, table):
# tables = connections[db].introspection.table_names()
# msg = "Table '%s.%s' exists, existing tables are %s"
# self.assertFalse(table in tables, msg % (db, table, tables))
#
# def assertModelTablesExist(self, model):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertTableExists(db, table)
#
# def assertModelTablesDontExist(self, model):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertTableDoesntExists(db, table)
#
# def assertColumnExists(self, db, table, column):
# columns = tuple(table_columns_iterator(db, table))
# data = {
# 'db': db,
# 'table': table,
# 'column': column,
# 'columns': columns
# }
# self.assertIn(column, columns,
# "Column '%(db)s.%(table)s.%(column)s' doesn't exist, "
# "%(db)s.'%(table)s's columns are %(columns)s" % data)
#
# def assertColumnDoesntExists(self, db, table, column):
# self.assertRaises(
# AssertionError, self.assertColumnExists, db, table, column
# )
#
# def assertModelTablesColumnExists(self, model, column):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertColumnExists(db, table, column)
#
# def assertModelTablesColumnDoesntExists(self, model, column):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertColumnDoesntExists(db, table, column)
. Output only the next line. | remove_from_app_cache(self.model_cls) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
class DirectoryPathField(CharField):
def validate(self, value, model_instance):
if not os.path.exists(value):
raise ValidationError(_("Specified path doesn't exist"))
elif not os.path.isdir(value):
raise ValidationError(_("Specified path isn't a directory"))
class RegExpStringField(CharField):
def to_python(self, value):
value = super(RegExpStringField, self).to_python(value)
if value is None:
return
try:
re.compile(value)
except Exception as e:
raise ValidationError(_(e))
else:
return value
class PythonIdentifierField(CharField):
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
from django.core.exceptions import ValidationError
from django.db.models.fields import CharField
from django.utils.translation import ugettext_lazy as _
from ...validators import validate_python_identifier
and context including class names, function names, and sometimes code from other files:
# Path: mutant/validators.py
. Output only the next line. | default_validators = [validate_python_identifier] |
Here is a snippet: <|code_start|>from __future__ import unicode_literals
class RelatedConfig(AppConfig):
name = 'mutant.contrib.related'
def ready(self):
<|code_end|>
. Write the next line using the current file imports:
from django.apps import AppConfig
from ...signals import mutable_class_prepared
from . import management
and context from other files:
# Path: mutant/signals.py
, which may include functions, classes, or code. Output only the next line. | mutable_class_prepared.connect(management.mutable_model_prepared) |
Using the snippet: <|code_start|>
class IPAddressFieldDefinition(CharFieldDefinition):
class Meta(_WebMeta):
app_label = 'web'
proxy = True
defined_field_class = fields.IPAddressField
protocol_help_text = _('Limits valid inputs to the specified protocol.')
unpack_ipv4_help_text = _('Unpacks IPv4 mapped addresses like '
'``::ffff::192.0.2.1`` to ``192.0.2.1``')
class GenericIPAddressFieldDefinition(CharFieldDefinition):
PROTOCOL_BOTH = 'both'
PROTOCOL_IPV4 = 'IPv4'
PROTOCOL_IPV6 = 'IPv6'
PROTOCOL_CHOICES = (
(PROTOCOL_BOTH, _('both')),
(PROTOCOL_IPV4, _('IPv4')),
(PROTOCOL_IPV6, _('IPv6'))
)
protocol = fields.CharField(
_('protocol'), max_length=4,
choices=PROTOCOL_CHOICES, default=PROTOCOL_BOTH
)
unpack_ipv4 = fields.BooleanField(_('unpack ipv4'), default=False)
<|code_end|>
, determine the next line of code. You have imports:
from django.core.exceptions import ValidationError
from django.db.models import fields
from django.utils.translation import ugettext_lazy as _
from ...models import FieldDefinitionManager
from ..text.models import CharFieldDefinition
and context (class names, function names, or code) available:
# Path: mutant/models/field/managers.py
# class FieldDefinitionManager(PolymorphicManager.from_queryset(FieldDefinitionQuerySet)):
# def get_by_natural_key(self, app_label, model, name):
# qs = self.select_subclasses()
# return qs.get(model_def__app_label=app_label,
# model_def__model=model, name=name)
#
# def names(self):
# qs = self.get_queryset()
# return qs.order_by('name').values_list('name', flat=True)
#
# def create_with_default(self, default, **kwargs):
# qs = self.get_queryset()
# return qs.create_with_default(default, **kwargs)
#
# Path: mutant/contrib/text/models.py
# class CharFieldDefinition(FieldDefinition):
# max_length = fields.PositiveSmallIntegerField(
# _('max length'), blank=True, null=True
# )
#
# objects = FieldDefinitionManager()
#
# class Meta:
# app_label = 'text'
# defined_field_class = fields.CharField
# defined_field_options = ('max_length',)
# defined_field_description = _('String')
# defined_field_category = _('Text')
. Output only the next line. | objects = FieldDefinitionManager() |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
class _WebMeta:
defined_field_category = _('Web')
<|code_end|>
, predict the next line using imports from the current file:
from django.core.exceptions import ValidationError
from django.db.models import fields
from django.utils.translation import ugettext_lazy as _
from ...models import FieldDefinitionManager
from ..text.models import CharFieldDefinition
and context including class names, function names, and sometimes code from other files:
# Path: mutant/models/field/managers.py
# class FieldDefinitionManager(PolymorphicManager.from_queryset(FieldDefinitionQuerySet)):
# def get_by_natural_key(self, app_label, model, name):
# qs = self.select_subclasses()
# return qs.get(model_def__app_label=app_label,
# model_def__model=model, name=name)
#
# def names(self):
# qs = self.get_queryset()
# return qs.order_by('name').values_list('name', flat=True)
#
# def create_with_default(self, default, **kwargs):
# qs = self.get_queryset()
# return qs.create_with_default(default, **kwargs)
#
# Path: mutant/contrib/text/models.py
# class CharFieldDefinition(FieldDefinition):
# max_length = fields.PositiveSmallIntegerField(
# _('max length'), blank=True, null=True
# )
#
# objects = FieldDefinitionManager()
#
# class Meta:
# app_label = 'text'
# defined_field_class = fields.CharField
# defined_field_options = ('max_length',)
# defined_field_description = _('String')
# defined_field_category = _('Text')
. Output only the next line. | class EmailFieldDefinition(CharFieldDefinition): |
Next line prediction: <|code_start|>from __future__ import unicode_literals
path_help_text = _('The absolute filesystem path to a directory from which '
'this field should get its choices.')
match_help_text = _('A regular expression used to filter filenames.')
recursive_help_text = _('Specifies whether all subdirectories of '
'path should be included')
class FilePathFieldDefinition(CharFieldDefinition):
<|code_end|>
. Use current file imports:
(from django.db.models import fields
from django.utils.translation import ugettext_lazy as _
from ...db.fields.python import DirectoryPathField, RegExpStringField
from ...models.field.managers import FieldDefinitionManager
from ..text.models import CharFieldDefinition)
and context including class names, function names, or small code snippets from other files:
# Path: mutant/db/fields/python.py
# class DirectoryPathField(CharField):
# def validate(self, value, model_instance):
# if not os.path.exists(value):
# raise ValidationError(_("Specified path doesn't exist"))
# elif not os.path.isdir(value):
# raise ValidationError(_("Specified path isn't a directory"))
#
# class RegExpStringField(CharField):
# def to_python(self, value):
# value = super(RegExpStringField, self).to_python(value)
# if value is None:
# return
# try:
# re.compile(value)
# except Exception as e:
# raise ValidationError(_(e))
# else:
# return value
#
# Path: mutant/models/field/managers.py
# class FieldDefinitionManager(PolymorphicManager.from_queryset(FieldDefinitionQuerySet)):
# def get_by_natural_key(self, app_label, model, name):
# qs = self.select_subclasses()
# return qs.get(model_def__app_label=app_label,
# model_def__model=model, name=name)
#
# def names(self):
# qs = self.get_queryset()
# return qs.order_by('name').values_list('name', flat=True)
#
# def create_with_default(self, default, **kwargs):
# qs = self.get_queryset()
# return qs.create_with_default(default, **kwargs)
#
# Path: mutant/contrib/text/models.py
# class CharFieldDefinition(FieldDefinition):
# max_length = fields.PositiveSmallIntegerField(
# _('max length'), blank=True, null=True
# )
#
# objects = FieldDefinitionManager()
#
# class Meta:
# app_label = 'text'
# defined_field_class = fields.CharField
# defined_field_options = ('max_length',)
# defined_field_description = _('String')
# defined_field_category = _('Text')
. Output only the next line. | path = DirectoryPathField(_('path'), max_length=100, |
Next line prediction: <|code_start|>from __future__ import unicode_literals
path_help_text = _('The absolute filesystem path to a directory from which '
'this field should get its choices.')
match_help_text = _('A regular expression used to filter filenames.')
recursive_help_text = _('Specifies whether all subdirectories of '
'path should be included')
class FilePathFieldDefinition(CharFieldDefinition):
path = DirectoryPathField(_('path'), max_length=100,
help_text=path_help_text)
<|code_end|>
. Use current file imports:
(from django.db.models import fields
from django.utils.translation import ugettext_lazy as _
from ...db.fields.python import DirectoryPathField, RegExpStringField
from ...models.field.managers import FieldDefinitionManager
from ..text.models import CharFieldDefinition)
and context including class names, function names, or small code snippets from other files:
# Path: mutant/db/fields/python.py
# class DirectoryPathField(CharField):
# def validate(self, value, model_instance):
# if not os.path.exists(value):
# raise ValidationError(_("Specified path doesn't exist"))
# elif not os.path.isdir(value):
# raise ValidationError(_("Specified path isn't a directory"))
#
# class RegExpStringField(CharField):
# def to_python(self, value):
# value = super(RegExpStringField, self).to_python(value)
# if value is None:
# return
# try:
# re.compile(value)
# except Exception as e:
# raise ValidationError(_(e))
# else:
# return value
#
# Path: mutant/models/field/managers.py
# class FieldDefinitionManager(PolymorphicManager.from_queryset(FieldDefinitionQuerySet)):
# def get_by_natural_key(self, app_label, model, name):
# qs = self.select_subclasses()
# return qs.get(model_def__app_label=app_label,
# model_def__model=model, name=name)
#
# def names(self):
# qs = self.get_queryset()
# return qs.order_by('name').values_list('name', flat=True)
#
# def create_with_default(self, default, **kwargs):
# qs = self.get_queryset()
# return qs.create_with_default(default, **kwargs)
#
# Path: mutant/contrib/text/models.py
# class CharFieldDefinition(FieldDefinition):
# max_length = fields.PositiveSmallIntegerField(
# _('max length'), blank=True, null=True
# )
#
# objects = FieldDefinitionManager()
#
# class Meta:
# app_label = 'text'
# defined_field_class = fields.CharField
# defined_field_options = ('max_length',)
# defined_field_description = _('String')
# defined_field_category = _('Text')
. Output only the next line. | match = RegExpStringField(_('match'), max_length=100, |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
path_help_text = _('The absolute filesystem path to a directory from which '
'this field should get its choices.')
match_help_text = _('A regular expression used to filter filenames.')
recursive_help_text = _('Specifies whether all subdirectories of '
'path should be included')
class FilePathFieldDefinition(CharFieldDefinition):
path = DirectoryPathField(_('path'), max_length=100,
help_text=path_help_text)
match = RegExpStringField(_('match'), max_length=100,
blank=True, null=True, help_text=match_help_text)
recursive = fields.BooleanField(_('recursive'), default=False,
help_text=recursive_help_text)
<|code_end|>
, predict the next line using imports from the current file:
from django.db.models import fields
from django.utils.translation import ugettext_lazy as _
from ...db.fields.python import DirectoryPathField, RegExpStringField
from ...models.field.managers import FieldDefinitionManager
from ..text.models import CharFieldDefinition
and context including class names, function names, and sometimes code from other files:
# Path: mutant/db/fields/python.py
# class DirectoryPathField(CharField):
# def validate(self, value, model_instance):
# if not os.path.exists(value):
# raise ValidationError(_("Specified path doesn't exist"))
# elif not os.path.isdir(value):
# raise ValidationError(_("Specified path isn't a directory"))
#
# class RegExpStringField(CharField):
# def to_python(self, value):
# value = super(RegExpStringField, self).to_python(value)
# if value is None:
# return
# try:
# re.compile(value)
# except Exception as e:
# raise ValidationError(_(e))
# else:
# return value
#
# Path: mutant/models/field/managers.py
# class FieldDefinitionManager(PolymorphicManager.from_queryset(FieldDefinitionQuerySet)):
# def get_by_natural_key(self, app_label, model, name):
# qs = self.select_subclasses()
# return qs.get(model_def__app_label=app_label,
# model_def__model=model, name=name)
#
# def names(self):
# qs = self.get_queryset()
# return qs.order_by('name').values_list('name', flat=True)
#
# def create_with_default(self, default, **kwargs):
# qs = self.get_queryset()
# return qs.create_with_default(default, **kwargs)
#
# Path: mutant/contrib/text/models.py
# class CharFieldDefinition(FieldDefinition):
# max_length = fields.PositiveSmallIntegerField(
# _('max length'), blank=True, null=True
# )
#
# objects = FieldDefinitionManager()
#
# class Meta:
# app_label = 'text'
# defined_field_class = fields.CharField
# defined_field_options = ('max_length',)
# defined_field_description = _('String')
# defined_field_category = _('Text')
. Output only the next line. | objects = FieldDefinitionManager() |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
path_help_text = _('The absolute filesystem path to a directory from which '
'this field should get its choices.')
match_help_text = _('A regular expression used to filter filenames.')
recursive_help_text = _('Specifies whether all subdirectories of '
'path should be included')
<|code_end|>
, predict the next line using imports from the current file:
from django.db.models import fields
from django.utils.translation import ugettext_lazy as _
from ...db.fields.python import DirectoryPathField, RegExpStringField
from ...models.field.managers import FieldDefinitionManager
from ..text.models import CharFieldDefinition
and context including class names, function names, and sometimes code from other files:
# Path: mutant/db/fields/python.py
# class DirectoryPathField(CharField):
# def validate(self, value, model_instance):
# if not os.path.exists(value):
# raise ValidationError(_("Specified path doesn't exist"))
# elif not os.path.isdir(value):
# raise ValidationError(_("Specified path isn't a directory"))
#
# class RegExpStringField(CharField):
# def to_python(self, value):
# value = super(RegExpStringField, self).to_python(value)
# if value is None:
# return
# try:
# re.compile(value)
# except Exception as e:
# raise ValidationError(_(e))
# else:
# return value
#
# Path: mutant/models/field/managers.py
# class FieldDefinitionManager(PolymorphicManager.from_queryset(FieldDefinitionQuerySet)):
# def get_by_natural_key(self, app_label, model, name):
# qs = self.select_subclasses()
# return qs.get(model_def__app_label=app_label,
# model_def__model=model, name=name)
#
# def names(self):
# qs = self.get_queryset()
# return qs.order_by('name').values_list('name', flat=True)
#
# def create_with_default(self, default, **kwargs):
# qs = self.get_queryset()
# return qs.create_with_default(default, **kwargs)
#
# Path: mutant/contrib/text/models.py
# class CharFieldDefinition(FieldDefinition):
# max_length = fields.PositiveSmallIntegerField(
# _('max length'), blank=True, null=True
# )
#
# objects = FieldDefinitionManager()
#
# class Meta:
# app_label = 'text'
# defined_field_class = fields.CharField
# defined_field_options = ('max_length',)
# defined_field_description = _('String')
# defined_field_category = _('Text')
. Output only the next line. | class FilePathFieldDefinition(CharFieldDefinition): |
Using the snippet: <|code_start|> obj = self.model(**kwargs)
obj._state._creation_default_value = default
self._for_write = True
obj.save(force_insert=True, using=self.db)
return obj
class FieldDefinitionManager(PolymorphicManager.from_queryset(FieldDefinitionQuerySet)):
def get_by_natural_key(self, app_label, model, name):
qs = self.select_subclasses()
return qs.get(model_def__app_label=app_label,
model_def__model=model, name=name)
def names(self):
qs = self.get_queryset()
return qs.order_by('name').values_list('name', flat=True)
def create_with_default(self, default, **kwargs):
qs = self.get_queryset()
return qs.create_with_default(default, **kwargs)
class FieldDefinitionChoiceQuerySet(models.query.QuerySet):
def construct(self):
# Here we don't use .values() since it's raw output from the database
# and values are not prepared correctly.
choices = (
{'group': choice.group, 'label': choice.label, 'value': choice.value}
for choice in self.only('group', 'value', 'label')
)
<|code_end|>
, determine the next line of code. You have imports:
import django
from django.db import models
from polymodels.managers import PolymorphicManager, PolymorphicQuerySet
from ...utils import choices_from_dict
and context (class names, function names, or code) available:
# Path: mutant/utils.py
# def choices_from_dict(choices):
# for grp, choices in groupby(choices, key=group_item_getter):
# if grp is None:
# for choice in choices:
# yield (choice['value'], choice['label'])
# else:
# yield (grp, tuple(
# (choice['value'], choice['label']) for choice in choices)
# )
. Output only the next line. | return tuple(choices_from_dict(choices)) |
Based on the snippet: <|code_start|> models = self.__dict__.get('models')
self._wrapped = queryset.filter(
pk__in=[ct.pk for ct in ContentType.objects.get_for_models(
*models, for_concrete_models=False
).values()]
)
class LazyFieldDefinitionGroupedChoices(LazyObject):
def __init__(self, queryset, empty_label, label_from_instance):
super(LazyFieldDefinitionGroupedChoices, self).__init__()
self.__dict__.update(
queryset=queryset, empty_label=empty_label,
label_from_instance=label_from_instance
)
def _setup(self):
queryset = self.__dict__.get('queryset')
label_from_instance = self.__dict__.get('label_from_instance')
empty_label = self.__dict__.get('empty_label')
definition_choices = []
for content_type in queryset:
definition = content_type.model_class()
category = definition.get_field_category()
definition_choices.append({
'group': smart_text(category) if category else None,
'value': content_type.pk,
'label': label_from_instance(content_type),
})
choices = list(
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import smart_text
from django.utils.functional import LazyObject
from .utils import choices_from_dict
from mutant.models import FieldDefinition
and context (classes, functions, sometimes code) from other files:
# Path: mutant/utils.py
# def choices_from_dict(choices):
# for grp, choices in groupby(choices, key=group_item_getter):
# if grp is None:
# for choice in choices:
# yield (choice['value'], choice['label'])
# else:
# yield (grp, tuple(
# (choice['value'], choice['label']) for choice in choices)
# )
. Output only the next line. | choices_from_dict( |
Predict the next line after this snippet: <|code_start|>from __future__ import unicode_literals
PACKAGE_PATH = os.path.dirname(sys.modules[__name__].__file__)
MODULE_PATH = os.path.abspath(sys.modules[__name__].__file__)
<|code_end|>
using the current file's imports:
import os
import sys
from django.utils.translation import ugettext_lazy as _
from mutant.contrib.file import models
from mutant.test import testcases
from .utils import BaseModelDefinitionTestCase
and any relevant context from other files:
# Path: mutant/contrib/file/models.py
# class FilePathFieldDefinition(CharFieldDefinition):
# class Meta:
#
# Path: mutant/test/testcases.py
# def connections_can_rollback_ddl():
# def _use_transactions(cls):
# def setUpClass(cls):
# def tearDownClass(cls):
# def _should_reload_connections(self):
# def _fixture_setup(self):
# def _fixture_teardown(self):
# def tearDown(self):
# def setUpTestData(cls):
# def setUp(self):
# def get_field_value(self, instance, name='field'):
# def prepare_default_value(self, value):
# def test_field_default(self):
# def test_create_with_default(self):
# def test_model_save(self):
# def test_field_renaming(self):
# def test_field_deletion(self):
# def test_field_unique(self):
# def test_field_cloning(self):
# def test_field_definition_category(self):
# class DDLTestCase(TestCase):
# class ModelDefinitionDDLTestCase(DDLTestCase):
# class FieldDefinitionTestMixin(object):
#
# Path: tests/utils.py
# class BaseModelDefinitionTestCase(ModelDefinitionDDLTestCase):
# @classmethod
# def setUpTestData(cls):
# model_def = ModelDefinition.objects.create(app_label='mutant', object_name='Model')
# cls.model_def_pk = model_def.pk
#
# def setUp(self):
# self.model_def = ModelDefinition.objects.get(pk=self.model_def_pk)
#
# @classmethod
# @contextmanager
# def assertChecksumChange(cls, model_def=None):
# if not model_def:
# model_def = ModelDefinition.objects.get(pk=cls.model_def_pk)
# checksum = model_def.model_class().checksum()
# yield
# if model_def.model_class().checksum() == checksum:
# raise AssertionError("Checksum of model %s should have changed." % model_def)
#
# @classmethod
# @contextmanager
# def assertChecksumDoesntChange(cls, model_def=None):
# if not model_def:
# model_def = ModelDefinition.objects.get(pk=cls.model_def_pk)
# try:
# with cls.assertChecksumChange(model_def):
# yield
# except AssertionError:
# pass
# else:
# model_class = model_def.model_class()
# raise AssertionError("Checksum of model %s shouldn't have changed." % model_class)
#
# def assertTableExists(self, db, table):
# tables = connections[db].introspection.table_names()
# msg = "Table '%s.%s' doesn't exist, existing tables are %s"
# self.assertTrue(table in tables, msg % (db, table, tables))
#
# def assertTableDoesntExists(self, db, table):
# tables = connections[db].introspection.table_names()
# msg = "Table '%s.%s' exists, existing tables are %s"
# self.assertFalse(table in tables, msg % (db, table, tables))
#
# def assertModelTablesExist(self, model):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertTableExists(db, table)
#
# def assertModelTablesDontExist(self, model):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertTableDoesntExists(db, table)
#
# def assertColumnExists(self, db, table, column):
# columns = tuple(table_columns_iterator(db, table))
# data = {
# 'db': db,
# 'table': table,
# 'column': column,
# 'columns': columns
# }
# self.assertIn(column, columns,
# "Column '%(db)s.%(table)s.%(column)s' doesn't exist, "
# "%(db)s.'%(table)s's columns are %(columns)s" % data)
#
# def assertColumnDoesntExists(self, db, table, column):
# self.assertRaises(
# AssertionError, self.assertColumnExists, db, table, column
# )
#
# def assertModelTablesColumnExists(self, model, column):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertColumnExists(db, table, column)
#
# def assertModelTablesColumnDoesntExists(self, model, column):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertColumnDoesntExists(db, table, column)
. Output only the next line. | MODELS_MODULE_PATH = os.path.abspath(models.__file__) |
Based on the snippet: <|code_start|>from __future__ import unicode_literals
PACKAGE_PATH = os.path.dirname(sys.modules[__name__].__file__)
MODULE_PATH = os.path.abspath(sys.modules[__name__].__file__)
MODELS_MODULE_PATH = os.path.abspath(models.__file__)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
from django.utils.translation import ugettext_lazy as _
from mutant.contrib.file import models
from mutant.test import testcases
from .utils import BaseModelDefinitionTestCase
and context (classes, functions, sometimes code) from other files:
# Path: mutant/contrib/file/models.py
# class FilePathFieldDefinition(CharFieldDefinition):
# class Meta:
#
# Path: mutant/test/testcases.py
# def connections_can_rollback_ddl():
# def _use_transactions(cls):
# def setUpClass(cls):
# def tearDownClass(cls):
# def _should_reload_connections(self):
# def _fixture_setup(self):
# def _fixture_teardown(self):
# def tearDown(self):
# def setUpTestData(cls):
# def setUp(self):
# def get_field_value(self, instance, name='field'):
# def prepare_default_value(self, value):
# def test_field_default(self):
# def test_create_with_default(self):
# def test_model_save(self):
# def test_field_renaming(self):
# def test_field_deletion(self):
# def test_field_unique(self):
# def test_field_cloning(self):
# def test_field_definition_category(self):
# class DDLTestCase(TestCase):
# class ModelDefinitionDDLTestCase(DDLTestCase):
# class FieldDefinitionTestMixin(object):
#
# Path: tests/utils.py
# class BaseModelDefinitionTestCase(ModelDefinitionDDLTestCase):
# @classmethod
# def setUpTestData(cls):
# model_def = ModelDefinition.objects.create(app_label='mutant', object_name='Model')
# cls.model_def_pk = model_def.pk
#
# def setUp(self):
# self.model_def = ModelDefinition.objects.get(pk=self.model_def_pk)
#
# @classmethod
# @contextmanager
# def assertChecksumChange(cls, model_def=None):
# if not model_def:
# model_def = ModelDefinition.objects.get(pk=cls.model_def_pk)
# checksum = model_def.model_class().checksum()
# yield
# if model_def.model_class().checksum() == checksum:
# raise AssertionError("Checksum of model %s should have changed." % model_def)
#
# @classmethod
# @contextmanager
# def assertChecksumDoesntChange(cls, model_def=None):
# if not model_def:
# model_def = ModelDefinition.objects.get(pk=cls.model_def_pk)
# try:
# with cls.assertChecksumChange(model_def):
# yield
# except AssertionError:
# pass
# else:
# model_class = model_def.model_class()
# raise AssertionError("Checksum of model %s shouldn't have changed." % model_class)
#
# def assertTableExists(self, db, table):
# tables = connections[db].introspection.table_names()
# msg = "Table '%s.%s' doesn't exist, existing tables are %s"
# self.assertTrue(table in tables, msg % (db, table, tables))
#
# def assertTableDoesntExists(self, db, table):
# tables = connections[db].introspection.table_names()
# msg = "Table '%s.%s' exists, existing tables are %s"
# self.assertFalse(table in tables, msg % (db, table, tables))
#
# def assertModelTablesExist(self, model):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertTableExists(db, table)
#
# def assertModelTablesDontExist(self, model):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertTableDoesntExists(db, table)
#
# def assertColumnExists(self, db, table, column):
# columns = tuple(table_columns_iterator(db, table))
# data = {
# 'db': db,
# 'table': table,
# 'column': column,
# 'columns': columns
# }
# self.assertIn(column, columns,
# "Column '%(db)s.%(table)s.%(column)s' doesn't exist, "
# "%(db)s.'%(table)s's columns are %(columns)s" % data)
#
# def assertColumnDoesntExists(self, db, table, column):
# self.assertRaises(
# AssertionError, self.assertColumnExists, db, table, column
# )
#
# def assertModelTablesColumnExists(self, model, column):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertColumnExists(db, table, column)
#
# def assertModelTablesColumnDoesntExists(self, model, column):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertColumnDoesntExists(db, table, column)
. Output only the next line. | class FilePathFieldDefinitionTest(testcases.FieldDefinitionTestMixin, |
Next line prediction: <|code_start|>from __future__ import unicode_literals
PACKAGE_PATH = os.path.dirname(sys.modules[__name__].__file__)
MODULE_PATH = os.path.abspath(sys.modules[__name__].__file__)
MODELS_MODULE_PATH = os.path.abspath(models.__file__)
class FilePathFieldDefinitionTest(testcases.FieldDefinitionTestMixin,
<|code_end|>
. Use current file imports:
(import os
import sys
from django.utils.translation import ugettext_lazy as _
from mutant.contrib.file import models
from mutant.test import testcases
from .utils import BaseModelDefinitionTestCase)
and context including class names, function names, or small code snippets from other files:
# Path: mutant/contrib/file/models.py
# class FilePathFieldDefinition(CharFieldDefinition):
# class Meta:
#
# Path: mutant/test/testcases.py
# def connections_can_rollback_ddl():
# def _use_transactions(cls):
# def setUpClass(cls):
# def tearDownClass(cls):
# def _should_reload_connections(self):
# def _fixture_setup(self):
# def _fixture_teardown(self):
# def tearDown(self):
# def setUpTestData(cls):
# def setUp(self):
# def get_field_value(self, instance, name='field'):
# def prepare_default_value(self, value):
# def test_field_default(self):
# def test_create_with_default(self):
# def test_model_save(self):
# def test_field_renaming(self):
# def test_field_deletion(self):
# def test_field_unique(self):
# def test_field_cloning(self):
# def test_field_definition_category(self):
# class DDLTestCase(TestCase):
# class ModelDefinitionDDLTestCase(DDLTestCase):
# class FieldDefinitionTestMixin(object):
#
# Path: tests/utils.py
# class BaseModelDefinitionTestCase(ModelDefinitionDDLTestCase):
# @classmethod
# def setUpTestData(cls):
# model_def = ModelDefinition.objects.create(app_label='mutant', object_name='Model')
# cls.model_def_pk = model_def.pk
#
# def setUp(self):
# self.model_def = ModelDefinition.objects.get(pk=self.model_def_pk)
#
# @classmethod
# @contextmanager
# def assertChecksumChange(cls, model_def=None):
# if not model_def:
# model_def = ModelDefinition.objects.get(pk=cls.model_def_pk)
# checksum = model_def.model_class().checksum()
# yield
# if model_def.model_class().checksum() == checksum:
# raise AssertionError("Checksum of model %s should have changed." % model_def)
#
# @classmethod
# @contextmanager
# def assertChecksumDoesntChange(cls, model_def=None):
# if not model_def:
# model_def = ModelDefinition.objects.get(pk=cls.model_def_pk)
# try:
# with cls.assertChecksumChange(model_def):
# yield
# except AssertionError:
# pass
# else:
# model_class = model_def.model_class()
# raise AssertionError("Checksum of model %s shouldn't have changed." % model_class)
#
# def assertTableExists(self, db, table):
# tables = connections[db].introspection.table_names()
# msg = "Table '%s.%s' doesn't exist, existing tables are %s"
# self.assertTrue(table in tables, msg % (db, table, tables))
#
# def assertTableDoesntExists(self, db, table):
# tables = connections[db].introspection.table_names()
# msg = "Table '%s.%s' exists, existing tables are %s"
# self.assertFalse(table in tables, msg % (db, table, tables))
#
# def assertModelTablesExist(self, model):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertTableExists(db, table)
#
# def assertModelTablesDontExist(self, model):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertTableDoesntExists(db, table)
#
# def assertColumnExists(self, db, table, column):
# columns = tuple(table_columns_iterator(db, table))
# data = {
# 'db': db,
# 'table': table,
# 'column': column,
# 'columns': columns
# }
# self.assertIn(column, columns,
# "Column '%(db)s.%(table)s.%(column)s' doesn't exist, "
# "%(db)s.'%(table)s's columns are %(columns)s" % data)
#
# def assertColumnDoesntExists(self, db, table, column):
# self.assertRaises(
# AssertionError, self.assertColumnExists, db, table, column
# )
#
# def assertModelTablesColumnExists(self, model, column):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertColumnExists(db, table, column)
#
# def assertModelTablesColumnDoesntExists(self, model, column):
# table = model._meta.db_table
# for db in allow_migrate(model):
# self.assertColumnDoesntExists(db, table, column)
. Output only the next line. | BaseModelDefinitionTestCase): |
Continue the code snippet: <|code_start|> raise ValueError("%r is not cached" % model_class)
apps.clear_cache()
unreference_model(model_class)
return model_class
def get_foward_fields(opts):
return chain(
opts.fields,
opts.many_to_many
)
def get_reverse_fields(opts):
return opts._get_fields(forward=False, reverse=True, include_hidden=True)
def clear_opts_related_cache(model_class):
opts = model_class._meta
children = [
related_object.related_model
for related_object in opts.__dict__.get('related_objects', []) if related_object.parent_link
]
opts._expire_cache()
for child in children:
clear_opts_related_cache(child)
def unreference_model(model):
for field in get_foward_fields(model._meta):
<|code_end|>
. Use current file imports:
from collections import defaultdict
from contextlib import contextmanager
from copy import deepcopy
from itertools import chain, groupby
from operator import itemgetter
from django.apps import AppConfig, apps
from django.db import connections, models, router
from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import lazy
from .compat import get_remote_field, get_remote_field_model
and context (classes, functions, or code) from other files:
# Path: mutant/compat.py
# def get_remote_field_model(field):
# def get_opts_label(opts):
# def many_to_many_set(instance, m2m, value):
# def get_remote_field_model(field):
# def get_opts_label(opts):
# def many_to_many_set(instance, m2m, value):
. Output only the next line. | remote_field = get_remote_field(field) |
Given the following code snippet before the placeholder: <|code_start|> unreference_model(model_class)
return model_class
def get_foward_fields(opts):
return chain(
opts.fields,
opts.many_to_many
)
def get_reverse_fields(opts):
return opts._get_fields(forward=False, reverse=True, include_hidden=True)
def clear_opts_related_cache(model_class):
opts = model_class._meta
children = [
related_object.related_model
for related_object in opts.__dict__.get('related_objects', []) if related_object.parent_link
]
opts._expire_cache()
for child in children:
clear_opts_related_cache(child)
def unreference_model(model):
for field in get_foward_fields(model._meta):
remote_field = get_remote_field(field)
if field.model is model and remote_field:
<|code_end|>
, predict the next line using imports from the current file:
from collections import defaultdict
from contextlib import contextmanager
from copy import deepcopy
from itertools import chain, groupby
from operator import itemgetter
from django.apps import AppConfig, apps
from django.db import connections, models, router
from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import lazy
from .compat import get_remote_field, get_remote_field_model
and context including class names, function names, and sometimes code from other files:
# Path: mutant/compat.py
# def get_remote_field_model(field):
# def get_opts_label(opts):
# def many_to_many_set(instance, m2m, value):
# def get_remote_field_model(field):
# def get_opts_label(opts):
# def many_to_many_set(instance, m2m, value):
. Output only the next line. | remote_field_model = get_remote_field_model(field) |
Predict the next line after this snippet: <|code_start|> ('contenttypes', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ConcreteModel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('concrete_model_field', models.NullBooleanField()),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='CustomFieldDefinition',
fields=[
('fielddefinition_ptr', models.OneToOneField(
to='mutant.FieldDefinition', on_delete=models.CASCADE, parent_link=True, auto_created=True,
primary_key=True, serialize=False
)),
],
options={
},
bases=('mutant.fielddefinition',),
),
migrations.CreateModel(
name='FieldDefinitionModel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
<|code_end|>
using the current file's imports:
from django.db import migrations, models
from mutant.db.fields.generic import FieldDefinitionTypeField
and any relevant context from other files:
# Path: mutant/db/fields/generic.py
# class FieldDefinitionTypeField(PolymorphicTypeField):
# def __init__(self, on_delete=models.CASCADE, *args, **kwargs):
# super(FieldDefinitionTypeField, self).__init__(
# 'mutant.FieldDefinition', on_delete=on_delete, *args, **kwargs
# )
#
# def deconstruct(self):
# name, path, args, kwargs = super(FieldDefinitionTypeField, self).deconstruct()
# kwargs.pop('polymorphic_type')
# if kwargs.get('on_delete') == models.CASCADE:
# kwargs.pop('on_delete')
# return name, path, args, kwargs
#
# def formfield(self, **kwargs):
# defaults = {'form_class': forms.FieldDefinitionTypeField}
# defaults.update(kwargs)
# return super(FieldDefinitionTypeField, self).formfield(**kwargs)
. Output only the next line. | ('field_type', FieldDefinitionTypeField()), |
Continue the code snippet: <|code_start|> for changes to take effect.
"""
return self._changes_require_reboot
@property
def is_supported(self):
"""Tells whether the router supports DMZ."""
return self._is_supported
def set_supported_status(self, value):
self._is_supported = bool(value)
@property
def is_enabled(self):
"""Tells whether the DMZ feature is enabled."""
return self._is_enabled
def set_enabled_status(self, value):
self._is_enabled = bool(value)
@property
def ip(self):
"""The IP address of the DMZ host."""
return self._ip
def set_ip(self, value):
self._ip = value
def validate(self):
errors = {}
<|code_end|>
. Use current file imports:
from roscraco.helper import validator
from roscraco.exception import RouterSettingsError
and context (classes, functions, or code) from other files:
# Path: roscraco/helper/validator.py
# WEP_CONSTRAINTS_MAP = {
# 64: {'ascii': 5, 'hex': 10},
# 128: {'ascii': 13, 'hex': 26},
# 152: {'ascii': 16, 'hex': 32}
# }
# def is_valid_mac_address(mac):
# def is_valid_mac_address_normalized(mac):
# def is_valid_ip_address(ip):
# def _is_hex_string(string):
# def is_valid_wpa_psk_password(password):
# def is_valid_wep_password(password, bit_length):
# def is_wep_password_in_hex(password, bit_length):
# def is_valid_ssid(ssid):
# def is_ip_in_range(ip, ip_range_start, ip_range_end):
#
# Path: roscraco/exception.py
# class RouterSettingsError(RouterError):
# pass
. Output only the next line. | if not validator.is_valid_ip_address(self.ip): |
Given the code snippet: <|code_start|> return self._is_supported
def set_supported_status(self, value):
self._is_supported = bool(value)
@property
def is_enabled(self):
"""Tells whether the DMZ feature is enabled."""
return self._is_enabled
def set_enabled_status(self, value):
self._is_enabled = bool(value)
@property
def ip(self):
"""The IP address of the DMZ host."""
return self._ip
def set_ip(self, value):
self._ip = value
def validate(self):
errors = {}
if not validator.is_valid_ip_address(self.ip):
errors['ip'] = 'Invalid IP: %s' % self.ip
return errors
def ensure_valid(self):
errors = self.validate()
if len(errors) != 0:
<|code_end|>
, generate the next line using the imports in this file:
from roscraco.helper import validator
from roscraco.exception import RouterSettingsError
and context (functions, classes, or occasionally code) from other files:
# Path: roscraco/helper/validator.py
# WEP_CONSTRAINTS_MAP = {
# 64: {'ascii': 5, 'hex': 10},
# 128: {'ascii': 13, 'hex': 26},
# 152: {'ascii': 16, 'hex': 32}
# }
# def is_valid_mac_address(mac):
# def is_valid_mac_address_normalized(mac):
# def is_valid_ip_address(ip):
# def _is_hex_string(string):
# def is_valid_wpa_psk_password(password):
# def is_valid_wep_password(password, bit_length):
# def is_wep_password_in_hex(password, bit_length):
# def is_valid_ssid(ssid):
# def is_ip_in_range(ip, ip_range_start, ip_range_end):
#
# Path: roscraco/exception.py
# class RouterSettingsError(RouterError):
# pass
. Output only the next line. | raise RouterSettingsError(str(errors)) |
Predict the next line after this snippet: <|code_start|> @property
def channel(self):
"""The transmission channel for wireless communications."""
return self._channel
def set_password(self, value):
self._password = value
@property
def password(self):
"""The current password for the given security type.
The password is sometimes None for some routers, to indicate
that the password cannot be determined.
Some routers hide the current password from their web-interface,
so we can't detect it (but that doesn't mean that we can't change it
with a new one).
"""
return self._password
@property
def is_wep_password_in_hex(self):
"""Tells whether the current WEP password is in HEX or in ASCII.
Detecting this allows us to set the ASCII/HEX
field in the management interface automatically.
"""
if not self.security_type_is_wep:
raise RouterSettingsError('Not using WEP, but trying to inspect password!')
bit_length = 128 if self.security_type == self.__class__.SECURITY_TYPE_WEP128 else 64
<|code_end|>
using the current file's imports:
from roscraco.helper import validator
from roscraco.exception import RouterSettingsError
and any relevant context from other files:
# Path: roscraco/helper/validator.py
# WEP_CONSTRAINTS_MAP = {
# 64: {'ascii': 5, 'hex': 10},
# 128: {'ascii': 13, 'hex': 26},
# 152: {'ascii': 16, 'hex': 32}
# }
# def is_valid_mac_address(mac):
# def is_valid_mac_address_normalized(mac):
# def is_valid_ip_address(ip):
# def _is_hex_string(string):
# def is_valid_wpa_psk_password(password):
# def is_valid_wep_password(password, bit_length):
# def is_wep_password_in_hex(password, bit_length):
# def is_valid_ssid(ssid):
# def is_ip_in_range(ip, ip_range_start, ip_range_end):
#
# Path: roscraco/exception.py
# class RouterSettingsError(RouterError):
# pass
. Output only the next line. | return validator.is_wep_password_in_hex(self.password, bit_length) |
Predict the next line after this snippet: <|code_start|> self._channel = int(value)
@property
def channel(self):
"""The transmission channel for wireless communications."""
return self._channel
def set_password(self, value):
self._password = value
@property
def password(self):
"""The current password for the given security type.
The password is sometimes None for some routers, to indicate
that the password cannot be determined.
Some routers hide the current password from their web-interface,
so we can't detect it (but that doesn't mean that we can't change it
with a new one).
"""
return self._password
@property
def is_wep_password_in_hex(self):
"""Tells whether the current WEP password is in HEX or in ASCII.
Detecting this allows us to set the ASCII/HEX
field in the management interface automatically.
"""
if not self.security_type_is_wep:
<|code_end|>
using the current file's imports:
from roscraco.helper import validator
from roscraco.exception import RouterSettingsError
and any relevant context from other files:
# Path: roscraco/helper/validator.py
# WEP_CONSTRAINTS_MAP = {
# 64: {'ascii': 5, 'hex': 10},
# 128: {'ascii': 13, 'hex': 26},
# 152: {'ascii': 16, 'hex': 32}
# }
# def is_valid_mac_address(mac):
# def is_valid_mac_address_normalized(mac):
# def is_valid_ip_address(ip):
# def _is_hex_string(string):
# def is_valid_wpa_psk_password(password):
# def is_valid_wep_password(password, bit_length):
# def is_wep_password_in_hex(password, bit_length):
# def is_valid_ssid(ssid):
# def is_ip_in_range(ip, ip_range_start, ip_range_end):
#
# Path: roscraco/exception.py
# class RouterSettingsError(RouterError):
# pass
. Output only the next line. | raise RouterSettingsError('Not using WEP, but trying to inspect password!') |
Predict the next line after this snippet: <|code_start|>
Such requests sometimes use the POST request method,
although not necessarily.
"""
url = self.url_base + path
self._invalidate_http_cache()
return self._perform_http_request(url, *args, **kwargs)[2]
def _handle_first_request(self):
"""To be implemented in a subclass
(if it needs to do something special on the first request).
"""
pass
def _perform_http_request(self, url, data=None, headers=(), timeout=7.0):
"""Makes the actual HTTP request and returns the result.
The result is a 3-tuple:
- requested URL
- info() - meta information, such as headers
- contents
"""
if self._is_first_request:
self._is_first_request = False
self._handle_first_request()
if data is not None:
if isinstance(data, dict) or isinstance(data, list):
data = urlencoder.urlencode(data)
else:
<|code_end|>
using the current file's imports:
import sys
import base64
import contextlib
import urllib.parse as urlencoder
import urllib as urlencoder
import urllib.request as requestor
import urllib2 as requestor
from roscraco.exception import RouterFetchError
and any relevant context from other files:
# Path: roscraco/exception.py
# class RouterFetchError(RouterError):
# pass
. Output only the next line. | raise RouterFetchError( |
Predict the next line after this snippet: <|code_start|> )
def __init__(self):
self._mac_address = None
self._ip_address = None
self._is_enabled = True
def set_mac(self, value):
self._mac_address = converter.normalize_mac(value)
@property
def mac(self):
return self._mac_address
def set_ip(self, value):
self._ip_address = value
@property
def ip(self):
return self._ip_address
def set_enabled_status(self, value):
self._is_enabled = bool(value)
@property
def is_enabled(self):
return self._is_enabled
def validate(self):
errors = {}
<|code_end|>
using the current file's imports:
from roscraco.helper import validator, converter
from roscraco.exception import RouterSettingsError
and any relevant context from other files:
# Path: roscraco/helper/validator.py
# WEP_CONSTRAINTS_MAP = {
# 64: {'ascii': 5, 'hex': 10},
# 128: {'ascii': 13, 'hex': 26},
# 152: {'ascii': 16, 'hex': 32}
# }
# def is_valid_mac_address(mac):
# def is_valid_mac_address_normalized(mac):
# def is_valid_ip_address(ip):
# def _is_hex_string(string):
# def is_valid_wpa_psk_password(password):
# def is_valid_wep_password(password, bit_length):
# def is_wep_password_in_hex(password, bit_length):
# def is_valid_ssid(ssid):
# def is_ip_in_range(ip, ip_range_start, ip_range_end):
#
# Path: roscraco/helper/converter.py
# def ip2long(ip_addr):
# def long2ip(ip):
# def normalize_mac(mac):
#
# Path: roscraco/exception.py
# class RouterSettingsError(RouterError):
# pass
. Output only the next line. | if not validator.is_valid_ip_address(self.ip): |
Using the snippet: <|code_start|> def __ne__(self, other):
return not self == other
def __hash__(self):
return id(self)
def export(self):
"""Exports the most important settings attributes,
omitting any internal attributes.
"""
export = {}
for i, item in enumerate(self):
export['entry_%d' % i] = item.export()
return export
class DHCPReservationListItem(object):
"""Represents a single entry in the DHCP address reservation table."""
#: Properties to export()
PROPERTIES = (
'mac', 'ip'
)
def __init__(self):
self._mac_address = None
self._ip_address = None
self._is_enabled = True
def set_mac(self, value):
<|code_end|>
, determine the next line of code. You have imports:
from roscraco.helper import validator, converter
from roscraco.exception import RouterSettingsError
and context (class names, function names, or code) available:
# Path: roscraco/helper/validator.py
# WEP_CONSTRAINTS_MAP = {
# 64: {'ascii': 5, 'hex': 10},
# 128: {'ascii': 13, 'hex': 26},
# 152: {'ascii': 16, 'hex': 32}
# }
# def is_valid_mac_address(mac):
# def is_valid_mac_address_normalized(mac):
# def is_valid_ip_address(ip):
# def _is_hex_string(string):
# def is_valid_wpa_psk_password(password):
# def is_valid_wep_password(password, bit_length):
# def is_wep_password_in_hex(password, bit_length):
# def is_valid_ssid(ssid):
# def is_ip_in_range(ip, ip_range_start, ip_range_end):
#
# Path: roscraco/helper/converter.py
# def ip2long(ip_addr):
# def long2ip(ip):
# def normalize_mac(mac):
#
# Path: roscraco/exception.py
# class RouterSettingsError(RouterError):
# pass
. Output only the next line. | self._mac_address = converter.normalize_mac(value) |
Continue the code snippet: <|code_start|>
@property
def mac(self):
return self._mac_address
def set_ip(self, value):
self._ip_address = value
@property
def ip(self):
return self._ip_address
def set_enabled_status(self, value):
self._is_enabled = bool(value)
@property
def is_enabled(self):
return self._is_enabled
def validate(self):
errors = {}
if not validator.is_valid_ip_address(self.ip):
errors['ip'] = 'Invalid IP address: %s' % self.ip
if not validator.is_valid_mac_address_normalized(self.mac):
errors['mac'] = 'Invalid normalized MAC address: %s' % self.mac
return errors
def ensure_valid(self):
errors = self.validate()
if len(errors) != 0:
<|code_end|>
. Use current file imports:
from roscraco.helper import validator, converter
from roscraco.exception import RouterSettingsError
and context (classes, functions, or code) from other files:
# Path: roscraco/helper/validator.py
# WEP_CONSTRAINTS_MAP = {
# 64: {'ascii': 5, 'hex': 10},
# 128: {'ascii': 13, 'hex': 26},
# 152: {'ascii': 16, 'hex': 32}
# }
# def is_valid_mac_address(mac):
# def is_valid_mac_address_normalized(mac):
# def is_valid_ip_address(ip):
# def _is_hex_string(string):
# def is_valid_wpa_psk_password(password):
# def is_valid_wep_password(password, bit_length):
# def is_wep_password_in_hex(password, bit_length):
# def is_valid_ssid(ssid):
# def is_ip_in_range(ip, ip_range_start, ip_range_end):
#
# Path: roscraco/helper/converter.py
# def ip2long(ip_addr):
# def long2ip(ip):
# def normalize_mac(mac):
#
# Path: roscraco/exception.py
# class RouterSettingsError(RouterError):
# pass
. Output only the next line. | raise RouterSettingsError(str(errors)) |
Predict the next line for this snippet: <|code_start|>
def ip2long(ip_addr):
"""Converts an IP address string to an integer."""
ip_packed = inet_aton(ip_addr)
ip = unpack('!L', ip_packed)[0]
return ip
def long2ip(ip):
"""Converts an integer representation of an IP address to string."""
return inet_ntoa(pack('!L', ip))
def normalize_mac(mac):
"""Converts any MAC address format to lowercase HEX with no separators."""
mac = mac.lower()
if not is_valid_mac_address(mac):
<|code_end|>
with the help of current file imports:
from ..exception import RouterParseError
from socket import inet_aton
from struct import unpack
from socket import inet_ntoa
from struct import pack
from .validator import is_valid_mac_address
and context from other files:
# Path: roscraco/exception.py
# class RouterParseError(RouterError):
# pass
, which may contain function names, class names, or code. Output only the next line. | raise RouterParseError('MAC address %s is invalid!' % mac) |
Predict the next line for this snippet: <|code_start|>
def is_valid_wep_password(password, bit_length):
"""Validates a WEP password of the specified bit length,
which imposes certain constraints on what's allowed."""
# the password could be either HEX or ASCII
# HEX is valid ASCII too
try:
password = password.decode('ascii')
except (UnicodeDecodeError, UnicodeEncodeError):
return False
if password.strip(' ') != password:
return False
length = len(password)
try:
constraints = WEP_CONSTRAINTS_MAP[bit_length]
if length == constraints['ascii']:
# any ascii character works
return True
elif length == constraints['hex']:
# if the string is that long, it can only be in HEX
return _is_hex_string(password)
return False
except KeyError:
<|code_end|>
with the help of current file imports:
import re
from ..exception import RouterError
from .converter import ip2long
and context from other files:
# Path: roscraco/exception.py
# class RouterError(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | raise RouterError('Invalid bit length: %d' % int(bit_length)) |
Based on the snippet: <|code_start|>NM_STATE_CONNECTING = 40 # A network device is connecting to a network and there is no other available network connection.
NM_STATE_CONNECTED_LOCAL = 50 # A network device is connected, but there is only link-local connectivity.
NM_STATE_CONNECTED_SITE = 60 # A network device is connected, but there is only site-local connectivity.
NM_STATE_CONNECTED_GLOBAL = 70 # A network device is connected, with global network connectivity.
# See firstboot_lib.Window.py for more details about how this class works
class FirstbootWindow(Window):
__gtype_name__ = "FirstbootWindow"
__gsignals__ = {
'link-status': (GObject.SignalFlags.ACTION, None, (GObject.TYPE_BOOLEAN,))
}
def finish_initializing(self, builder, options=None): # pylint: disable=E1002
"""Set up the main window"""
super(FirstbootWindow, self).finish_initializing(builder)
self.connect("delete_event", self.on_delete_event)
screen = Gdk.Screen.get_default()
sw = math.floor(screen.width() - screen.width() / 6)
sh = math.floor(screen.height() - screen.height() / 6)
self.resize(sw, sh)
self.btnPrev = self.ui.btnPrev
self.btnNext = self.ui.btnNext
self.cmd_options = options
self.fbe = FirstbootEntry.FirstbootEntry()
<|code_end|>
, predict the immediate next line with the help of imports:
import gettext
import math
import shlex
import subprocess
import os
import logging
import pages
import dbus
from gettext import gettext as _
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Pango
from gi.repository import Gio
from gi.repository import GdkPixbuf
from gi.repository import GObject
from firstboot_lib import Window, firstbootconfig, FirstbootEntry
from dbus.mainloop.glib import DBusGMainLoop
and context (classes, functions, sometimes code) from other files:
# Path: firstboot_lib/firstbootconfig.py
# class project_path_not_found(Exception):
# def get_bin_path():
# def get_data_file(*path_segments):
# def get_prefix():
# def get_data_path():
# def get_version():
#
# Path: firstboot_lib/FirstbootEntry.py
# class FirstbootEntry(IniFile):
#
# default_group = 'Firstboot Entry'
#
# def __init__(self):
#
# self.content = dict()
#
# self.config_path = '/var/lib/firstboot'
# self.config_file = os.path.join(self.config_path, 'firstboot.conf')
#
# if not os.path.exists(self.config_path):
# os.makedirs(self.config_path)
#
# if not os.path.exists(self.config_file):
# self._create_config_file()
#
# IniFile.parse(self, self.config_file, [self.default_group])
#
# def _create_config_file(self):
#
# fd = open(self.config_file, 'w')
# if fd != None:
# fd.write('[Firstboot Entry]\n')
# fd.write('firststart=0\n')
# fd.write('\n')
# fd.write('[LinkToServer]\n')
# fd.write('url=https://GECOS-SERVER/autoconfig\n')
# fd.write('\n')
# fd.close()
#
# def get_firststart(self):
# fs = self.get('firststart').strip()
# fs = bool(int(fs))
# return fs
#
# def set_firststart(self, value):
# self.set('firststart', value)
# self.write()
#
# def get_url(self):
# return self.get('url', group='LinkToServer')
#
# def set_url(self, value):
# self.set('url', value, group='LinkToServer')
# self.write()
. Output only the next line. | iconfile = firstbootconfig.get_data_file('media', '%s' % ('wizard1.png',)) |
Next line prediction: <|code_start|>NM_STATE_DISCONNECTED = 20 # There is no active network connection.
NM_STATE_DISCONNECTING = 30 # Network connections are being cleaned up.
NM_STATE_CONNECTING = 40 # A network device is connecting to a network and there is no other available network connection.
NM_STATE_CONNECTED_LOCAL = 50 # A network device is connected, but there is only link-local connectivity.
NM_STATE_CONNECTED_SITE = 60 # A network device is connected, but there is only site-local connectivity.
NM_STATE_CONNECTED_GLOBAL = 70 # A network device is connected, with global network connectivity.
# See firstboot_lib.Window.py for more details about how this class works
class FirstbootWindow(Window):
__gtype_name__ = "FirstbootWindow"
__gsignals__ = {
'link-status': (GObject.SignalFlags.ACTION, None, (GObject.TYPE_BOOLEAN,))
}
def finish_initializing(self, builder, options=None): # pylint: disable=E1002
"""Set up the main window"""
super(FirstbootWindow, self).finish_initializing(builder)
self.connect("delete_event", self.on_delete_event)
screen = Gdk.Screen.get_default()
sw = math.floor(screen.width() - screen.width() / 6)
sh = math.floor(screen.height() - screen.height() / 6)
self.resize(sw, sh)
self.btnPrev = self.ui.btnPrev
self.btnNext = self.ui.btnNext
self.cmd_options = options
<|code_end|>
. Use current file imports:
(import gettext
import math
import shlex
import subprocess
import os
import logging
import pages
import dbus
from gettext import gettext as _
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Pango
from gi.repository import Gio
from gi.repository import GdkPixbuf
from gi.repository import GObject
from firstboot_lib import Window, firstbootconfig, FirstbootEntry
from dbus.mainloop.glib import DBusGMainLoop)
and context including class names, function names, or small code snippets from other files:
# Path: firstboot_lib/firstbootconfig.py
# class project_path_not_found(Exception):
# def get_bin_path():
# def get_data_file(*path_segments):
# def get_prefix():
# def get_data_path():
# def get_version():
#
# Path: firstboot_lib/FirstbootEntry.py
# class FirstbootEntry(IniFile):
#
# default_group = 'Firstboot Entry'
#
# def __init__(self):
#
# self.content = dict()
#
# self.config_path = '/var/lib/firstboot'
# self.config_file = os.path.join(self.config_path, 'firstboot.conf')
#
# if not os.path.exists(self.config_path):
# os.makedirs(self.config_path)
#
# if not os.path.exists(self.config_file):
# self._create_config_file()
#
# IniFile.parse(self, self.config_file, [self.default_group])
#
# def _create_config_file(self):
#
# fd = open(self.config_file, 'w')
# if fd != None:
# fd.write('[Firstboot Entry]\n')
# fd.write('firststart=0\n')
# fd.write('\n')
# fd.write('[LinkToServer]\n')
# fd.write('url=https://GECOS-SERVER/autoconfig\n')
# fd.write('\n')
# fd.close()
#
# def get_firststart(self):
# fs = self.get('firststart').strip()
# fs = bool(int(fs))
# return fs
#
# def set_firststart(self, value):
# self.set('firststart', value)
# self.write()
#
# def get_url(self):
# return self.get('url', group='LinkToServer')
#
# def set_url(self, value):
# self.set('url', value, group='LinkToServer')
# self.write()
. Output only the next line. | self.fbe = FirstbootEntry.FirstbootEntry() |
Next line prediction: <|code_start|> class Meta:
model = Host
exclude = ("id",)
widgets = {
'hostname': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;', 'placeholder': u'必填项'}),
'ip': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;', 'placeholder': u'必填项'}),
'other_ip': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'group': Select(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'asset_no': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'asset_type': Select(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'status': Select(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'os': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'vendor': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'cpu_model': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'cpu_num': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'memory': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'disk': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'sn': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'idc': Select(attrs={'class': 'form-control', 'style': 'width:530px;'}),
'position': TextInput(attrs={'class': 'form-control', 'style': 'width:530px;', 'placeholder': u'物理机写位置,虚机写宿主'}),
'memo': Textarea(attrs={'class': 'form-control', 'style': 'width:530px;'}),
}
class IdcForm(forms.ModelForm):
def clean(self):
cleaned_data = super(IdcForm, self).clean()
value = cleaned_data.get('name')
try:
<|code_end|>
. Use current file imports:
(from django import forms
from django.forms.widgets import *
from .models import Host, Idc, HostGroup)
and context including class names, function names, or small code snippets from other files:
# Path: cmdb/models.py
# class Host(models.Model):
# hostname = models.CharField(max_length=50, verbose_name=u"主机名", unique=True)
# ip = models.GenericIPAddressField(u"管理IP", max_length=15)
# other_ip = models.CharField(u"其它IP", max_length=100, null=True, blank=True)
# group = models.ForeignKey(HostGroup, verbose_name=u"设备组", on_delete=models.SET_NULL, null=True, blank=True)
# asset_no = models.CharField(u"资产编号", max_length=50, null=True, blank=True)
# asset_type = models.CharField(u"设备类型", choices=ASSET_TYPE, max_length=30, null=True, blank=True)
# status = models.CharField(u"设备状态", choices=ASSET_STATUS, max_length=30, null=True, blank=True)
# os = models.CharField(u"操作系统", max_length=100, null=True, blank=True)
# vendor = models.CharField(u"设备厂商", max_length=50, null=True, blank=True)
# cpu_model = models.CharField(u"CPU型号", max_length=100, null=True, blank=True)
# cpu_num = models.CharField(u"CPU数量", max_length=100, null=True, blank=True)
# memory = models.CharField(u"内存大小", max_length=30, null=True, blank=True)
# disk = models.CharField(u"硬盘信息", max_length=255, null=True, blank=True)
# sn = models.CharField(u"SN号 码", max_length=60, blank=True)
# idc = models.ForeignKey(Idc, verbose_name=u"所在机房", on_delete=models.SET_NULL, null=True, blank=True)
# position = models.CharField(u"所在位置", max_length=100, null=True, blank=True)
# memo = models.TextField(u"备注信息", max_length=200, null=True, blank=True)
#
# def __unicode__(self):
# return self.hostname
#
# class Idc(models.Model):
# name = models.CharField(u"机房名称", max_length=30, null=True)
# address = models.CharField(u"机房地址", max_length=100, null=True)
# tel = models.CharField(u"机房电话", max_length=30, null=True)
# contact = models.CharField(u"客户经理", max_length=30, null=True)
# contact_phone = models.CharField(u"移动电话", max_length=30, null=True)
# jigui = models.CharField(u"机柜信息", max_length=30, null=True)
# ip_range = models.CharField(u"IP范围", max_length=30, null=True)
# bandwidth = models.CharField(u"接入带宽", max_length=30, null=True)
#
# def __unicode__(self):
# return self.name
#
# class Meta:
# verbose_name = u'数据中心'
# verbose_name_plural = verbose_name
#
# class HostGroup(models.Model):
# name = models.CharField(u"组名", max_length=30, unique=True)
# desc = models.CharField(u"描述", max_length=100, null=True, blank=True)
#
# def __unicode__(self):
# return self.name
. Output only the next line. | Idc.objects.get(name=value) |
Here is a snippet: <|code_start|> value = cleaned_data.get('name')
try:
Idc.objects.get(name=value)
self._errors['name'] = self.error_class(["%s的信息已经存在" % value])
except Idc.DoesNotExist:
pass
return cleaned_data
class Meta:
model = Idc
exclude = ("id",)
widgets = {
'name': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'address': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'tel': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'contact': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'contact_phone': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'ip_range': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'jigui': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'bandwidth': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
}
class GroupForm(forms.ModelForm):
def clean(self):
cleaned_data = super(GroupForm, self).clean()
value = cleaned_data.get('name')
try:
<|code_end|>
. Write the next line using the current file imports:
from django import forms
from django.forms.widgets import *
from .models import Host, Idc, HostGroup
and context from other files:
# Path: cmdb/models.py
# class Host(models.Model):
# hostname = models.CharField(max_length=50, verbose_name=u"主机名", unique=True)
# ip = models.GenericIPAddressField(u"管理IP", max_length=15)
# other_ip = models.CharField(u"其它IP", max_length=100, null=True, blank=True)
# group = models.ForeignKey(HostGroup, verbose_name=u"设备组", on_delete=models.SET_NULL, null=True, blank=True)
# asset_no = models.CharField(u"资产编号", max_length=50, null=True, blank=True)
# asset_type = models.CharField(u"设备类型", choices=ASSET_TYPE, max_length=30, null=True, blank=True)
# status = models.CharField(u"设备状态", choices=ASSET_STATUS, max_length=30, null=True, blank=True)
# os = models.CharField(u"操作系统", max_length=100, null=True, blank=True)
# vendor = models.CharField(u"设备厂商", max_length=50, null=True, blank=True)
# cpu_model = models.CharField(u"CPU型号", max_length=100, null=True, blank=True)
# cpu_num = models.CharField(u"CPU数量", max_length=100, null=True, blank=True)
# memory = models.CharField(u"内存大小", max_length=30, null=True, blank=True)
# disk = models.CharField(u"硬盘信息", max_length=255, null=True, blank=True)
# sn = models.CharField(u"SN号 码", max_length=60, blank=True)
# idc = models.ForeignKey(Idc, verbose_name=u"所在机房", on_delete=models.SET_NULL, null=True, blank=True)
# position = models.CharField(u"所在位置", max_length=100, null=True, blank=True)
# memo = models.TextField(u"备注信息", max_length=200, null=True, blank=True)
#
# def __unicode__(self):
# return self.hostname
#
# class Idc(models.Model):
# name = models.CharField(u"机房名称", max_length=30, null=True)
# address = models.CharField(u"机房地址", max_length=100, null=True)
# tel = models.CharField(u"机房电话", max_length=30, null=True)
# contact = models.CharField(u"客户经理", max_length=30, null=True)
# contact_phone = models.CharField(u"移动电话", max_length=30, null=True)
# jigui = models.CharField(u"机柜信息", max_length=30, null=True)
# ip_range = models.CharField(u"IP范围", max_length=30, null=True)
# bandwidth = models.CharField(u"接入带宽", max_length=30, null=True)
#
# def __unicode__(self):
# return self.name
#
# class Meta:
# verbose_name = u'数据中心'
# verbose_name_plural = verbose_name
#
# class HostGroup(models.Model):
# name = models.CharField(u"组名", max_length=30, unique=True)
# desc = models.CharField(u"描述", max_length=100, null=True, blank=True)
#
# def __unicode__(self):
# return self.name
, which may include functions, classes, or code. Output only the next line. | HostGroup.objects.get(name=value) |
Predict the next line for this snippet: <|code_start|> if request.user.is_authenticated():
return HttpResponseRedirect('/')
if request.method == 'GET' and request.GET.has_key('next'):
next_page = request.GET['next']
else:
next_page = '/'
if next_page == "/accounts/logout/":
next_page = '/'
if request.method == "POST":
form = LoginUserForm(request, data=request.POST)
if form.is_valid():
auth.login(request, form.get_user())
return HttpResponseRedirect(request.POST['next'])
else:
form = LoginUserForm(request)
kwargs = {
'request': request,
'form': form,
'next': next_page,
}
return render(request, 'accounts/login.html', kwargs)
@login_required
def logout(request):
auth.logout(request)
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
@login_required()
<|code_end|>
with the help of current file imports:
from django.shortcuts import render, HttpResponseRedirect, RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from forms import LoginUserForm, EditUserForm, ChangePasswordForm
from django.contrib.auth import get_user_model
from forms import AddUserForm
from django.core.urlresolvers import reverse
from accounts.permission import permission_verify
and context from other files:
# Path: accounts/permission.py
# def permission_verify():
# """
# 权限认证模块,
# 此模块会先判断用户是否是管理员(is_superuser为True),如果是管理员,则具有所有权限,
# 如果不是管理员则获取request.user和request.path两个参数,判断两个参数是否匹配,匹配则有权限,反之则没有。
# """
# def decorator(view_func):
# def _wrapped_view(request, *args, **kwargs):
# iUser = UserInfo.objects.get(username=request.user)
# # 判断用户如果是超级管理员则具有所有权限
# if not iUser.is_superuser:
# if not iUser.role: # 如果用户无角色,直接返回无权限
# return HttpResponseRedirect(reverse('permission_deny'))
#
# role_permission = RoleList.objects.get(name=iUser.role)
# role_permission_list = role_permission.permission.all()
#
# matchUrl = []
# for x in role_permission_list:
# # 精确匹配,判断request.path是否与permission表中的某一条相符
# if request.path == x.url or request.path.rstrip('/') == x.url:
# matchUrl.append(x.url)
# # 判断request.path是否以permission表中的某一条url开头
# elif request.path.startswith(x.url):
# matchUrl.append(x.url)
# else:
# pass
#
# print('{}---->matchUrl:{}'.format(request.user, str(matchUrl)))
# if len(matchUrl) == 0:
# return HttpResponseRedirect(reverse('permission_deny'))
# else:
# pass
#
# return view_func(request, *args, **kwargs)
# return _wrapped_view
#
# return decorator
, which may contain function names, class names, or code. Output only the next line. | @permission_verify() |
Next line prediction: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
class AppOwnerForm(forms.ModelForm):
class Meta:
model = AppOwner
exclude = ("id",)
widgets = {
'name': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'phone': TextInput(attrs={'class': 'form-control','style': 'width:450px'}),
'qq': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'weChat': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
}
class ProductForm(forms.ModelForm):
class Meta:
<|code_end|>
. Use current file imports:
(from django import forms
from django.forms import widgets
from django.forms.widgets import *
from .models import Product, Project, AppOwner)
and context including class names, function names, or small code snippets from other files:
# Path: appconf/models.py
# class Product(models.Model):
# name = models.CharField(u"产品线名称", max_length=50, unique=True, null=False, blank=False)
# description = models.CharField(u"产品线描述", max_length=255, null=True, blank=True)
# owner = models.ForeignKey(
# AppOwner, verbose_name=u"产品线负责人",
# null=True, blank=True,
# on_delete=models.SET_NULL
# )
#
# def __unicode__(self):
# return self.name
#
# class Project(models.Model):
# LANGUAGE_TYPES = (
# ("Java", "Java"),
# ("PHP", "PHP"),
# ("Python", "Python"),
# ("C#", "C#"),
# ("Html", "Html"),
# ("Javascript", "Javascript"),
# ("C/C++", "C/C++"),
# ("Ruby", "Ruby"),
# ("Other", "Other"),
# )
#
# APP_TYPE = (
# ("Frontend", "Frontend"),
# ("Middleware", "Middleware"),
# ("Backend", "Backend"),
# )
#
# SERVER_TYPE = (
# ("Tomcat", "Tomcat"),
# ("Weblogic", "Weblogic"),
# ("JETTY", "JETTY"),
# ("Nginx", "Nginx"),
# ("Gunicorn", "Gunicorn"),
# ("Uwsgi", "Uwsgi"),
# ("Apache", "Apache"),
# ("IIS", "IIS"),
# )
#
# APP_ARCH = (
# ("Django", "Django"),
# ("Flask", "Flask"),
# ("Tornado", "Tornado"),
# ("Dubbo", "Dubbo"),
# ("SSH", "SSH"),
# ("Spring boot", "Spring boot"),
# ("Spring cloud", "Spring cloud"),
# ("Laravel", "Laravel"),
# ("ThinkPHP", "ThinkPHP"),
# ("Phalcon", "Phalcon"),
# ("other", "other"),
# )
#
# SOURCE_TYPE = (
# ("svn", "svn"),
# ("git", "git"),
# ("file", "file"),
# )
#
# name = models.CharField(u"项目名称", max_length=50, unique=True, null=False, blank=False)
# description = models.CharField(u"项目描述", max_length=255, null=True, blank=True)
# language_type = models.CharField(u"语言类型", choices=LANGUAGE_TYPES, max_length=30, null=True, blank=True)
# app_type = models.CharField(u"程序类型", choices=APP_TYPE, max_length=30, null=True, blank=True)
# server_type = models.CharField(u"服务器类型", choices=SERVER_TYPE, max_length=30, null=True, blank=True)
# app_arch = models.CharField(u"程序框架", choices=APP_ARCH, max_length=30, null=True, blank=True)
# source_type = models.CharField(max_length=255, choices=SOURCE_TYPE, verbose_name=u"源类型", blank=True)
# source_address = models.CharField(max_length=255, verbose_name=u"源地址", null=True, blank=True)
# appPath = models.CharField(u"程序部署路径", max_length=255, null=True, blank=True)
# configPath = models.CharField(u"配置文件路径", max_length=255, null=True, blank=True)
# product = models.ForeignKey(
# Product,
# null=True,
# blank=True,
# on_delete=models.SET_NULL,
# verbose_name=u"所属产品线"
# )
# owner = models.ForeignKey(
# AppOwner,
# null=True,
# blank=True,
# on_delete=models.SET_NULL,
# verbose_name=u"项目负责人"
# )
# serverList = models.ManyToManyField(
# Host,
# blank=True,
# verbose_name=u"所在服务器"
# )
#
# class AppOwner(models.Model):
# name = models.CharField(u"负责人姓名", max_length=50, unique=True, null=False, blank=False)
# phone = models.CharField(u"负责人手机", max_length=50, null=False, blank=False)
# qq = models.CharField(u"负责人QQ", max_length=100, null=True, blank=True)
# weChat = models.CharField(u"负责人微信", max_length=100, null=True, blank=True)
#
# def __unicode__(self):
# return self.name
. Output only the next line. | model = Product |
Predict the next line for this snippet: <|code_start|>
class AppOwnerForm(forms.ModelForm):
class Meta:
model = AppOwner
exclude = ("id",)
widgets = {
'name': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'phone': TextInput(attrs={'class': 'form-control','style': 'width:450px'}),
'qq': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'weChat': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
}
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = ("id",)
widgets = {
'name': TextInput(attrs={'class': 'form-control','style': 'width:450px;'}),
'description': Textarea(attrs={'class': 'form-control','style': 'width:450px; height:100px'}),
'owner': Select(attrs={'class': 'form-control','style': 'width:450px;'}),
}
class ProjectForm(forms.ModelForm):
class Meta:
<|code_end|>
with the help of current file imports:
from django import forms
from django.forms import widgets
from django.forms.widgets import *
from .models import Product, Project, AppOwner
and context from other files:
# Path: appconf/models.py
# class Product(models.Model):
# name = models.CharField(u"产品线名称", max_length=50, unique=True, null=False, blank=False)
# description = models.CharField(u"产品线描述", max_length=255, null=True, blank=True)
# owner = models.ForeignKey(
# AppOwner, verbose_name=u"产品线负责人",
# null=True, blank=True,
# on_delete=models.SET_NULL
# )
#
# def __unicode__(self):
# return self.name
#
# class Project(models.Model):
# LANGUAGE_TYPES = (
# ("Java", "Java"),
# ("PHP", "PHP"),
# ("Python", "Python"),
# ("C#", "C#"),
# ("Html", "Html"),
# ("Javascript", "Javascript"),
# ("C/C++", "C/C++"),
# ("Ruby", "Ruby"),
# ("Other", "Other"),
# )
#
# APP_TYPE = (
# ("Frontend", "Frontend"),
# ("Middleware", "Middleware"),
# ("Backend", "Backend"),
# )
#
# SERVER_TYPE = (
# ("Tomcat", "Tomcat"),
# ("Weblogic", "Weblogic"),
# ("JETTY", "JETTY"),
# ("Nginx", "Nginx"),
# ("Gunicorn", "Gunicorn"),
# ("Uwsgi", "Uwsgi"),
# ("Apache", "Apache"),
# ("IIS", "IIS"),
# )
#
# APP_ARCH = (
# ("Django", "Django"),
# ("Flask", "Flask"),
# ("Tornado", "Tornado"),
# ("Dubbo", "Dubbo"),
# ("SSH", "SSH"),
# ("Spring boot", "Spring boot"),
# ("Spring cloud", "Spring cloud"),
# ("Laravel", "Laravel"),
# ("ThinkPHP", "ThinkPHP"),
# ("Phalcon", "Phalcon"),
# ("other", "other"),
# )
#
# SOURCE_TYPE = (
# ("svn", "svn"),
# ("git", "git"),
# ("file", "file"),
# )
#
# name = models.CharField(u"项目名称", max_length=50, unique=True, null=False, blank=False)
# description = models.CharField(u"项目描述", max_length=255, null=True, blank=True)
# language_type = models.CharField(u"语言类型", choices=LANGUAGE_TYPES, max_length=30, null=True, blank=True)
# app_type = models.CharField(u"程序类型", choices=APP_TYPE, max_length=30, null=True, blank=True)
# server_type = models.CharField(u"服务器类型", choices=SERVER_TYPE, max_length=30, null=True, blank=True)
# app_arch = models.CharField(u"程序框架", choices=APP_ARCH, max_length=30, null=True, blank=True)
# source_type = models.CharField(max_length=255, choices=SOURCE_TYPE, verbose_name=u"源类型", blank=True)
# source_address = models.CharField(max_length=255, verbose_name=u"源地址", null=True, blank=True)
# appPath = models.CharField(u"程序部署路径", max_length=255, null=True, blank=True)
# configPath = models.CharField(u"配置文件路径", max_length=255, null=True, blank=True)
# product = models.ForeignKey(
# Product,
# null=True,
# blank=True,
# on_delete=models.SET_NULL,
# verbose_name=u"所属产品线"
# )
# owner = models.ForeignKey(
# AppOwner,
# null=True,
# blank=True,
# on_delete=models.SET_NULL,
# verbose_name=u"项目负责人"
# )
# serverList = models.ManyToManyField(
# Host,
# blank=True,
# verbose_name=u"所在服务器"
# )
#
# class AppOwner(models.Model):
# name = models.CharField(u"负责人姓名", max_length=50, unique=True, null=False, blank=False)
# phone = models.CharField(u"负责人手机", max_length=50, null=False, blank=False)
# qq = models.CharField(u"负责人QQ", max_length=100, null=True, blank=True)
# weChat = models.CharField(u"负责人微信", max_length=100, null=True, blank=True)
#
# def __unicode__(self):
# return self.name
, which may contain function names, class names, or code. Output only the next line. | model = Project |
Based on the snippet: <|code_start|> show_end = 1
else:
show_end = 0
# 所有对象, 分页器, 本页对象, 所有页码, 本页页码,是否显示第一页,是否显示最后一页
return post_objects, paginator, page_objects, page_range, current_page, show_first, show_end
@csrf_exempt
@token_verify()
def collect(request):
asset_info = json.loads(request.body)
if request.method == 'POST':
vendor = asset_info['vendor']
# group = asset_info['group']
disk = asset_info['disk']
cpu_model = asset_info['cpu_model']
cpu_num = asset_info['cpu_num']
memory = asset_info['memory']
sn = asset_info['sn']
osver = asset_info['osver']
hostname = asset_info['hostname']
ip = asset_info['ip']
# asset_type = ""
# status = ""
try:
host = Host.objects.get(hostname=hostname)
except Exception as msg:
print(msg)
host = Host()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.http import HttpResponse
from models import Host, HostGroup, ASSET_TYPE, ASSET_STATUS
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.views.decorators.csrf import csrf_exempt
from lib.common import token_verify
from lib.deploy_key import deploy_key
from lib.log import log
from config.views import get_dir
import logging
import json
import simplejson as json
and context (classes, functions, sometimes code) from other files:
# Path: config/views.py
# def get_dir(args):
# config = ConfigParser.RawConfigParser()
# dirs = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# with open(dirs+'/adminset.conf', 'r') as cfgfile:
# config.readfp(cfgfile)
# a_path = config.get('config', 'ansible_path')
# r_path = config.get('config', 'roles_path')
# p_path = config.get('config', 'playbook_path')
# s_path = config.get('config', 'scripts_path')
# token = config.get('token', 'token')
# ssh_pwd = config.get('token', 'ssh_pwd')
# log_path = config.get('log', 'log_path')
# log_level = config.get('log', 'log_level')
# mongodb_ip = config.get('mongodb', 'mongodb_ip')
# mongodb_port = config.get('mongodb', 'mongodb_port')
# mongodb_user = config.get('mongodb', 'mongodb_user')
# mongodb_pwd = config.get('mongodb', 'mongodb_pwd')
# mongodb_collection = config.get('mongodb', 'collection')
# webssh_domain = config.get('webssh', 'domain')
# # 根据传入参数返回变量以获取配置,返回变量名与参数名相同
# if args:
# return vars()[args]
# else:
# return HttpResponse(status=403)
. Output only the next line. | level = get_dir("log_level") |
Based on the snippet: <|code_start|> ("svn", "svn"),
("git", "git"),
("file", "file"),
)
name = models.CharField(u"项目名称", max_length=50, unique=True, null=False, blank=False)
description = models.CharField(u"项目描述", max_length=255, null=True, blank=True)
language_type = models.CharField(u"语言类型", choices=LANGUAGE_TYPES, max_length=30, null=True, blank=True)
app_type = models.CharField(u"程序类型", choices=APP_TYPE, max_length=30, null=True, blank=True)
server_type = models.CharField(u"服务器类型", choices=SERVER_TYPE, max_length=30, null=True, blank=True)
app_arch = models.CharField(u"程序框架", choices=APP_ARCH, max_length=30, null=True, blank=True)
source_type = models.CharField(max_length=255, choices=SOURCE_TYPE, verbose_name=u"源类型", blank=True)
source_address = models.CharField(max_length=255, verbose_name=u"源地址", null=True, blank=True)
appPath = models.CharField(u"程序部署路径", max_length=255, null=True, blank=True)
configPath = models.CharField(u"配置文件路径", max_length=255, null=True, blank=True)
product = models.ForeignKey(
Product,
null=True,
blank=True,
on_delete=models.SET_NULL,
verbose_name=u"所属产品线"
)
owner = models.ForeignKey(
AppOwner,
null=True,
blank=True,
on_delete=models.SET_NULL,
verbose_name=u"项目负责人"
)
serverList = models.ManyToManyField(
<|code_end|>
, predict the immediate next line with the help of imports:
from django.db import models
from cmdb.models import Host
and context (classes, functions, sometimes code) from other files:
# Path: cmdb/models.py
# class Host(models.Model):
# hostname = models.CharField(max_length=50, verbose_name=u"主机名", unique=True)
# ip = models.GenericIPAddressField(u"管理IP", max_length=15)
# other_ip = models.CharField(u"其它IP", max_length=100, null=True, blank=True)
# group = models.ForeignKey(HostGroup, verbose_name=u"设备组", on_delete=models.SET_NULL, null=True, blank=True)
# asset_no = models.CharField(u"资产编号", max_length=50, null=True, blank=True)
# asset_type = models.CharField(u"设备类型", choices=ASSET_TYPE, max_length=30, null=True, blank=True)
# status = models.CharField(u"设备状态", choices=ASSET_STATUS, max_length=30, null=True, blank=True)
# os = models.CharField(u"操作系统", max_length=100, null=True, blank=True)
# vendor = models.CharField(u"设备厂商", max_length=50, null=True, blank=True)
# cpu_model = models.CharField(u"CPU型号", max_length=100, null=True, blank=True)
# cpu_num = models.CharField(u"CPU数量", max_length=100, null=True, blank=True)
# memory = models.CharField(u"内存大小", max_length=30, null=True, blank=True)
# disk = models.CharField(u"硬盘信息", max_length=255, null=True, blank=True)
# sn = models.CharField(u"SN号 码", max_length=60, blank=True)
# idc = models.ForeignKey(Idc, verbose_name=u"所在机房", on_delete=models.SET_NULL, null=True, blank=True)
# position = models.CharField(u"所在位置", max_length=100, null=True, blank=True)
# memo = models.TextField(u"备注信息", max_length=200, null=True, blank=True)
#
# def __unicode__(self):
# return self.hostname
. Output only the next line. | Host, |
Given the following code snippet before the placeholder: <|code_start|>""" /* To test in Postgres */
CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;
SELECT levenshtein(a, b)
FROM (
VALUES
('sitting', 'kitten'),
('Sunday', 'Saturday'),
('settings', 'settings'),
('setting', 'settings'),
('abcdefghijklm', 'nopqrstuvwxyz'),
('abc klm', '** _rs /wxyz'),
('ABCD', 'abcd')
) as t(a, b);
"""
class TestLevenshteinDistance(unittest.TestCase):
def test_levenshtein_distance(self):
"""Should return the expected distance value."""
# Verified against Postgres v10 extension "fuzzystrmatch" levenshtein().
test_data = (
(3, "sitting", "kitten"),
(3, "Sunday", "Saturday"),
(0, "settings", "settings"),
(1, "setting", "settings"),
(13, "abcdefghijklm", "nopqrstuvwxyz"),
(11, "abc klm", "** _rs /wxyz"),
(4, "ABCD", "abcd"),
)
for i in test_data:
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from pyxform.utils import levenshtein_distance
and context including class names, function names, and sometimes code from other files:
# Path: pyxform/utils.py
# def levenshtein_distance(a: str, b: str) -> int:
# """
# Calculate Levenshtein distance between two strings.
#
# A Python translation of the "iterative with two matrix rows" algorithm from
# Wikipedia: https://en.wikipedia.org/wiki/Levenshtein_distance
#
# :param a: The first string to compare.
# :param b: The second string to compare.
# :return:
# """
# m = len(a)
# n = len(b)
#
# # create two work vectors of integer distances
# v1 = [0 for _ in range(0, n + 1)]
#
# # initialize v0 (the previous row of distances)
# # this row is A[0][i]: edit distance for an empty s
# # the distance is just the number of characters to delete from t
# v0 = [i for i in range(0, n + 1)]
#
# for i in range(0, m):
# # calculate v1 (current row distances) from the previous row v0
#
# # first element of v1 is A[i+1][0]
# # edit distance is delete (i+1) chars from s to match empty t
# v1[0] = i + 1
#
# # use formula to fill in the rest of the row
# for j in range(0, n):
# # calculating costs for A[i+1][j+1]
# deletion_cost = v0[j + 1] + 1
# insertion_cost = v1[j] + 1
# if a[i] == b[j]:
# substitution_cost = v0[j]
# else:
# substitution_cost = v0[j] + 1
#
# v1[j + 1] = min((deletion_cost, insertion_cost, substitution_cost))
#
# # copy v1 (current row) to v0 (previous row) for next iteration
# # since data in v1 is always invalidated, a swap without copy could be more efficient
# v0 = copy.copy(v1)
# # after the last swap, the results of v1 are now in v0
# return v0[n]
. Output only the next line. | self.assertEqual(i[0], levenshtein_distance(i[1], i[2]), str(i)) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test pyxform.validators.utils module.
"""
class TestValidatorUtil(TestCase):
maxDiff = None
config = None
cls_name = None
@classmethod
def setUpClass(cls):
prep_class_config(cls=cls)
def test_cleanup_error_message(self):
test_str = self.config.get(self.cls_name, "test_cleanup_error_message_test")
expected_str = self.config.get(
self.cls_name, "test_cleanup_error_message_expected"
)
<|code_end|>
, determine the next line of code. You have imports:
import os
from unittest import TestCase
from pyxform.validators.error_cleaner import ErrorCleaner
from pyxform.validators.util import XFORM_SPEC_PATH, check_readable
from tests.utils import prep_class_config
and context (class names, function names, or code) available:
# Path: pyxform/validators/error_cleaner.py
# class ErrorCleaner:
# """Cleans up raw error messages from XForm validators for end users."""
#
# @staticmethod
# def _replace_xpath_with_tokens(match):
# strmatch = match.group()
# # eliminate e.g /html/body/select1[@ref=/id_string/elId]/item/value
# # instance('q4')/root/item[...]
# if (
# strmatch.startswith("/html/body")
# or strmatch.startswith("/root/item")
# or strmatch.startswith("/html/head/model/bind")
# or strmatch.endswith("/item/value")
# ):
# return strmatch
# line = match.group().split("/")
# return "${%s}" % line[len(line) - 1]
#
# @staticmethod
# def _cleanup_errors(error_message):
# pattern = r"(/[a-z0-9\-_]+(?:/[a-z0-9\-_]+)+)"
# error_message = re.sub(
# pattern, ErrorCleaner._replace_xpath_with_tokens, error_message, flags=re.I
# )
# lines = str(error_message).strip().splitlines()
# no_dupes = [
# line for i, line in enumerate(lines) if line != lines[i - 1] or i == 0
# ]
# return no_dupes
#
# @staticmethod
# def _remove_java_content(line):
# # has a java filename (with line number)
# has_java_filename = line.find(".java:") != -1
# # starts with ' at java class path or method path'
# is_a_java_method = line.find("\tat") != -1
# if not has_java_filename and not is_a_java_method:
# # remove java.lang.RuntimeException
# if line.startswith("java.lang.RuntimeException: "):
# line = line.replace("java.lang.RuntimeException: ", "")
# # remove org.javarosa.xpath.XPathUnhandledException
# if line.startswith("org.javarosa.xpath.XPathUnhandledException: "):
# line = line.replace("org.javarosa.xpath.XPathUnhandledException: ", "")
# # remove java.lang.NullPointerException
# if line.startswith("java.lang.NullPointerException"):
# line = line.replace("java.lang.NullPointerException", "")
# if line.startswith("org.javarosa.xform.parse.XFormParseException"):
# line = line.replace("org.javarosa.xform.parse.XFormParseException", "")
# return line
#
# @staticmethod
# def _join_final(error_messages):
# return "\n".join(line for line in error_messages if line is not None)
#
# @staticmethod
# def odk_validate(error_message):
# if "Error: Unable to access jarfile" in error_message:
# return error_message # Avoids tokenising the file path.
# common = ErrorCleaner._cleanup_errors(error_message)
# java_clean = [ErrorCleaner._remove_java_content(i) for i in common]
# final_message = ErrorCleaner._join_final(java_clean)
# return final_message
#
# @staticmethod
# def enketo_validate(error_message):
# common = ErrorCleaner._cleanup_errors(error_message)
# final_message = ErrorCleaner._join_final(common)
# return final_message
#
# Path: pyxform/validators/util.py
# XFORM_SPEC_PATH = os.path.join(HERE, "xlsform_spec_test.xml")
#
# def check_readable(file_path, retry_limit=10, wait_seconds=0.5):
# """
# Check if a file is readable: True if so, IOError if not. Retry as per args.
#
# If a file that needs to be read may be locked by some other process (such
# as for reading or writing), this can help avoid an error by waiting for the
# lock to clear.
#
# :param file_path: Path to file to check.
# :param retry_limit: Number of attempts to read the file.
# :param wait_seconds: Amount of sleep time between read attempts.
# :return: True or raise IOError.
# """
#
# def catch_try():
# try:
# with io.open(file_path, mode="r"):
# return True
# except IOError:
# return False
#
# tries = 0
# while not catch_try():
# if tries < retry_limit:
# tries += 1
# time.sleep(wait_seconds)
# else:
# raise IOError("Could not read file: {f}".format(f=file_path))
# return True
#
# Path: tests/utils.py
# def prep_class_config(cls, test_dir="tests"):
# cls.config = configparser.ConfigParser()
# here = os.path.dirname(__file__)
# root = os.path.dirname(here)
# strings = os.path.join(root, test_dir, "fixtures", "strings.ini")
# cls.config.read(strings)
# cls.cls_name = cls.__name__
. Output only the next line. | self.assertEqual(ErrorCleaner.odk_validate(test_str), expected_str.strip()) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test pyxform.validators.utils module.
"""
class TestValidatorUtil(TestCase):
maxDiff = None
config = None
cls_name = None
@classmethod
def setUpClass(cls):
<|code_end|>
, generate the next line using the imports in this file:
import os
from unittest import TestCase
from pyxform.validators.error_cleaner import ErrorCleaner
from pyxform.validators.util import XFORM_SPEC_PATH, check_readable
from tests.utils import prep_class_config
and context (functions, classes, or occasionally code) from other files:
# Path: pyxform/validators/error_cleaner.py
# class ErrorCleaner:
# """Cleans up raw error messages from XForm validators for end users."""
#
# @staticmethod
# def _replace_xpath_with_tokens(match):
# strmatch = match.group()
# # eliminate e.g /html/body/select1[@ref=/id_string/elId]/item/value
# # instance('q4')/root/item[...]
# if (
# strmatch.startswith("/html/body")
# or strmatch.startswith("/root/item")
# or strmatch.startswith("/html/head/model/bind")
# or strmatch.endswith("/item/value")
# ):
# return strmatch
# line = match.group().split("/")
# return "${%s}" % line[len(line) - 1]
#
# @staticmethod
# def _cleanup_errors(error_message):
# pattern = r"(/[a-z0-9\-_]+(?:/[a-z0-9\-_]+)+)"
# error_message = re.sub(
# pattern, ErrorCleaner._replace_xpath_with_tokens, error_message, flags=re.I
# )
# lines = str(error_message).strip().splitlines()
# no_dupes = [
# line for i, line in enumerate(lines) if line != lines[i - 1] or i == 0
# ]
# return no_dupes
#
# @staticmethod
# def _remove_java_content(line):
# # has a java filename (with line number)
# has_java_filename = line.find(".java:") != -1
# # starts with ' at java class path or method path'
# is_a_java_method = line.find("\tat") != -1
# if not has_java_filename and not is_a_java_method:
# # remove java.lang.RuntimeException
# if line.startswith("java.lang.RuntimeException: "):
# line = line.replace("java.lang.RuntimeException: ", "")
# # remove org.javarosa.xpath.XPathUnhandledException
# if line.startswith("org.javarosa.xpath.XPathUnhandledException: "):
# line = line.replace("org.javarosa.xpath.XPathUnhandledException: ", "")
# # remove java.lang.NullPointerException
# if line.startswith("java.lang.NullPointerException"):
# line = line.replace("java.lang.NullPointerException", "")
# if line.startswith("org.javarosa.xform.parse.XFormParseException"):
# line = line.replace("org.javarosa.xform.parse.XFormParseException", "")
# return line
#
# @staticmethod
# def _join_final(error_messages):
# return "\n".join(line for line in error_messages if line is not None)
#
# @staticmethod
# def odk_validate(error_message):
# if "Error: Unable to access jarfile" in error_message:
# return error_message # Avoids tokenising the file path.
# common = ErrorCleaner._cleanup_errors(error_message)
# java_clean = [ErrorCleaner._remove_java_content(i) for i in common]
# final_message = ErrorCleaner._join_final(java_clean)
# return final_message
#
# @staticmethod
# def enketo_validate(error_message):
# common = ErrorCleaner._cleanup_errors(error_message)
# final_message = ErrorCleaner._join_final(common)
# return final_message
#
# Path: pyxform/validators/util.py
# XFORM_SPEC_PATH = os.path.join(HERE, "xlsform_spec_test.xml")
#
# def check_readable(file_path, retry_limit=10, wait_seconds=0.5):
# """
# Check if a file is readable: True if so, IOError if not. Retry as per args.
#
# If a file that needs to be read may be locked by some other process (such
# as for reading or writing), this can help avoid an error by waiting for the
# lock to clear.
#
# :param file_path: Path to file to check.
# :param retry_limit: Number of attempts to read the file.
# :param wait_seconds: Amount of sleep time between read attempts.
# :return: True or raise IOError.
# """
#
# def catch_try():
# try:
# with io.open(file_path, mode="r"):
# return True
# except IOError:
# return False
#
# tries = 0
# while not catch_try():
# if tries < retry_limit:
# tries += 1
# time.sleep(wait_seconds)
# else:
# raise IOError("Could not read file: {f}".format(f=file_path))
# return True
#
# Path: tests/utils.py
# def prep_class_config(cls, test_dir="tests"):
# cls.config = configparser.ConfigParser()
# here = os.path.dirname(__file__)
# root = os.path.dirname(here)
# strings = os.path.join(root, test_dir, "fixtures", "strings.ini")
# cls.config.read(strings)
# cls.cls_name = cls.__name__
. Output only the next line. | prep_class_config(cls=cls) |
Predict the next line for this snippet: <|code_start|> if not updated:
child["children"].append(question)
if "ref" not in question:
new_ref = "/".join(ref.split("/")[2:])
root_ref = "/".join(ref.split("/")[:2])
q = self._get_item_func(root_ref, new_ref, item)
if "type" not in q and "type" in question:
q.update(question)
if q["type"] == "group" and q["name"] == "meta":
q["control"] = {"bodyless": True}
q["__order"] = self._get_question_order(ref)
self.children.append(q)
self._bind_list.append(item)
break
if self._bind_list:
self._cleanup_bind_list()
def _get_item_func(self, ref, name, item):
rs = {}
name_splits = name.split("/")
rs["name"] = name_splits[0]
ref = "%s/%s" % (ref, rs["name"])
rs["ref"] = ref
if name_splits.__len__() > 1:
rs["type"] = "group"
rs["children"] = [self._get_item_func(ref, "/".join(name_splits[1:]), item)]
return rs
def survey(self):
new_doc = json.dumps(self.new_doc)
<|code_end|>
with the help of current file imports:
import codecs
import copy
import json
import logging
import re
import xml.etree.ElementTree as ETree
from operator import itemgetter
from pyxform import builder
from pyxform.utils import NSMAP
and context from other files:
# Path: pyxform/builder.py
# def copy_json_dict(json_dict):
# def __init__(self, **kwargs):
# def set_sections(self, sections):
# def create_survey_element_from_dict(self, d):
# def _save_trigger_as_setvalue_and_remove_calculate(self, d):
# def _create_question_from_dict(d, question_type_dictionary, add_none_option=False):
# def _add_other_option_to_multiple_choice_question(d):
# def _add_none_option_to_select_all_that_apply(d_copy):
# def _get_question_class(question_type_str, question_type_dictionary):
# def _create_specify_other_question_from_dict(d):
# def _create_section_from_dict(self, d):
# def _create_loop_from_dict(self, d):
# def _name_and_label_substitutions(self, question_template, column_headers):
# def create_survey_element_from_json(self, str_or_path):
# def create_survey_element_from_dict(d, sections=None):
# def create_survey_element_from_json(str_or_path):
# def create_survey_from_xls(path_or_file, default_name=None):
# def create_survey(
# name_of_main_section=None,
# sections=None,
# main_section=None,
# id_string=None,
# title=None,
# default_language=None,
# ):
# def create_survey_from_path(path, include_directory=False):
# class SurveyElementBuilder:
# QUESTION_CLASSES = {
# "": Question,
# "action": Question,
# "input": InputQuestion,
# "odk:rank": MultipleChoiceQuestion,
# "osm": OsmUploadQuestion,
# "range": RangeQuestion,
# "select": MultipleChoiceQuestion,
# "select1": MultipleChoiceQuestion,
# "trigger": TriggerQuestion,
# "upload": UploadQuestion,
# }
# SECTION_CLASSES = {
# "group": GroupedSection,
# "repeat": RepeatingSection,
# "survey": Survey,
# }
#
# Path: pyxform/utils.py
# NSMAP = {
# "xmlns": "http://www.w3.org/2002/xforms",
# "xmlns:h": "http://www.w3.org/1999/xhtml",
# "xmlns:ev": "http://www.w3.org/2001/xml-events",
# "xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
# "xmlns:jr": "http://openrosa.org/javarosa",
# "xmlns:orx": "http://openrosa.org/xforms",
# "xmlns:odk": "http://www.opendatakit.org/xforms",
# }
, which may contain function names, class names, or code. Output only the next line. | _survey = builder.create_survey_element_from_json(new_doc) |
Next line prediction: <|code_start|>
# end of http://code.activestate.com/recipes/573463/ }}}
def _try_parse(root, parser=None):
"""
Try to parse the root from a string or a file/file-like object.
"""
root = root.encode("UTF-8")
try:
parsed_root = ETree.fromstring(root, parser)
except ETree.ParseError:
parsed_root = ETree.parse(root, parser=parser).getroot()
return parsed_root
class XFormToDict:
def __init__(self, root):
if isinstance(root, str):
parser = ETree.XMLParser(encoding="UTF-8")
self._root = _try_parse(root, parser)
self._dict = XmlDictObject(
{self._root.tag: _convert_xml_to_dict_recurse(self._root, XmlDictObject)}
)
elif not isinstance(root, ETree.Element):
raise TypeError("Expected ElementTree.Element or file path string")
def get_dict(self):
json_str = json.dumps(self._dict)
<|code_end|>
. Use current file imports:
(import codecs
import copy
import json
import logging
import re
import xml.etree.ElementTree as ETree
from operator import itemgetter
from pyxform import builder
from pyxform.utils import NSMAP)
and context including class names, function names, or small code snippets from other files:
# Path: pyxform/builder.py
# def copy_json_dict(json_dict):
# def __init__(self, **kwargs):
# def set_sections(self, sections):
# def create_survey_element_from_dict(self, d):
# def _save_trigger_as_setvalue_and_remove_calculate(self, d):
# def _create_question_from_dict(d, question_type_dictionary, add_none_option=False):
# def _add_other_option_to_multiple_choice_question(d):
# def _add_none_option_to_select_all_that_apply(d_copy):
# def _get_question_class(question_type_str, question_type_dictionary):
# def _create_specify_other_question_from_dict(d):
# def _create_section_from_dict(self, d):
# def _create_loop_from_dict(self, d):
# def _name_and_label_substitutions(self, question_template, column_headers):
# def create_survey_element_from_json(self, str_or_path):
# def create_survey_element_from_dict(d, sections=None):
# def create_survey_element_from_json(str_or_path):
# def create_survey_from_xls(path_or_file, default_name=None):
# def create_survey(
# name_of_main_section=None,
# sections=None,
# main_section=None,
# id_string=None,
# title=None,
# default_language=None,
# ):
# def create_survey_from_path(path, include_directory=False):
# class SurveyElementBuilder:
# QUESTION_CLASSES = {
# "": Question,
# "action": Question,
# "input": InputQuestion,
# "odk:rank": MultipleChoiceQuestion,
# "osm": OsmUploadQuestion,
# "range": RangeQuestion,
# "select": MultipleChoiceQuestion,
# "select1": MultipleChoiceQuestion,
# "trigger": TriggerQuestion,
# "upload": UploadQuestion,
# }
# SECTION_CLASSES = {
# "group": GroupedSection,
# "repeat": RepeatingSection,
# "survey": Survey,
# }
#
# Path: pyxform/utils.py
# NSMAP = {
# "xmlns": "http://www.w3.org/2002/xforms",
# "xmlns:h": "http://www.w3.org/1999/xhtml",
# "xmlns:ev": "http://www.w3.org/2001/xml-events",
# "xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
# "xmlns:jr": "http://openrosa.org/javarosa",
# "xmlns:orx": "http://openrosa.org/xforms",
# "xmlns:odk": "http://www.opendatakit.org/xforms",
# }
. Output only the next line. | for uri in NSMAP.values(): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test loop syntax.
"""
class LoopTests(TestCase):
def test_loop(self):
path = utils.path_to_text_fixture("another_loop.xls")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from pyxform.builder import create_survey_from_xls
from tests import utils
and context:
# Path: pyxform/builder.py
# def create_survey_from_xls(path_or_file, default_name=None):
# excel_reader = SurveyReader(path_or_file, default_name=default_name)
# d = excel_reader.to_json_dict()
# survey = create_survey_element_from_dict(d)
# if not survey.id_string:
# survey.id_string = excel_reader._name
# return survey
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
which might include code, classes, or functions. Output only the next line. | survey = create_survey_from_xls(path, "another_loop") |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test loop syntax.
"""
class LoopTests(TestCase):
def test_loop(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from pyxform.builder import create_survey_from_xls
from tests import utils
and context (classes, functions, sometimes code) from other files:
# Path: pyxform/builder.py
# def create_survey_from_xls(path_or_file, default_name=None):
# excel_reader = SurveyReader(path_or_file, default_name=default_name)
# d = excel_reader.to_json_dict()
# survey = create_survey_element_from_dict(d)
# if not survey.id_string:
# survey.id_string = excel_reader._name
# return survey
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | path = utils.path_to_text_fixture("another_loop.xls") |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Testing our ability to import from a JSON text file.
"""
class Json2XformTestJsonImport(TestCase):
def test_simple_questions_can_be_imported_from_json(self):
json_text = {
"type": "survey",
"name": "Exchange rate",
"children": [
{
"label": {"French": "Combien?", "English": "How many?"},
"type": "decimal",
"name": "exchange_rate",
}
],
}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from pyxform.builder import create_survey_element_from_dict
and context:
# Path: pyxform/builder.py
# def create_survey_element_from_dict(self, d):
# """
# Convert from a nested python dictionary/array structure (a json dict I
# call it because it corresponds directly with a json object)
# to a survey object
# """
# if "add_none_option" in d:
# self._add_none_option = d["add_none_option"]
# if d["type"] in self.SECTION_CLASSES:
# section = self._create_section_from_dict(d)
#
# if d["type"] == "survey":
# section.setvalues_by_triggering_ref = self.setvalues_by_triggering_ref
#
# return section
# elif d["type"] == "loop":
# return self._create_loop_from_dict(d)
# elif d["type"] == "include":
# section_name = d["name"]
# if section_name not in self._sections:
# raise PyXFormError(
# "This section has not been included.",
# section_name,
# self._sections.keys(),
# )
# d = self._sections[section_name]
# full_survey = self.create_survey_element_from_dict(d)
# return full_survey.children
# elif d["type"] in ["xml-external", "csv-external"]:
# return ExternalInstance(**d)
# else:
# self._save_trigger_as_setvalue_and_remove_calculate(d)
#
# return self._create_question_from_dict(
# d, copy_json_dict(QUESTION_TYPE_DICT), self._add_none_option
# )
which might include code, classes, or functions. Output only the next line. | s = create_survey_element_from_dict(json_text) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.