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.
"""
... | 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 ... | 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... | 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,
subtra... | 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... | 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 r... | 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_upda... | 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", "hash... | 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 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, m... | 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 e... | 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
... | 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(
se... | ) -> 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",
... | 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",
},
{
... | 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)
@s... | "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.
... | 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_compr... | 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,
"... | 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 authentic... | 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:... | 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 = {
... | 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},
... | 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 ... | 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... | 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
d... | 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:
... | 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 ob... | 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")
... | 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"]
... | 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
... | 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.
... | 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):
... | 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
:... | 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_subtra... | 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": [],
"h... | "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=Tr... | "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(c... | 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_p... | 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... | 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... | 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 recor... | 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, s... | 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__()
... | 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 + Z... | 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 externa... | 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.
e... | 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:
... | 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:
... | 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, inst... | 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(se... | 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 BackupResto... | 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 ha... | 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, s... | 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 ac... | 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 ... | 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 DumpDataTestCas... | 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 ... | 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
... | 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 = _('Unpack... | 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 i... | 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 wh... | 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 wh... | 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.')
re... | 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.')
re... | 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... | 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... | 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.transl... | 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 he... | 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.FieldDefinitio... | 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_fie... | 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=Tr... | 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=Tr... | ('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.... | 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, ... | 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 p... | 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 pass... | 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... | 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):
retu... | 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 ... | 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)
... | 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 ... | 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:
... | 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 devic... | 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_CON... | 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;', ... | 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
... | 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/":
... | @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': ... | 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': 'for... | 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(re... | 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.Cha... | 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'),
('abcdefghijkl... | 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):
... | 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:
imp... | 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 = se... | _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... | 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 pyxf... | 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
... | 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",
... | 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.