Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|> SKIP_UPDATE_REFERENCES = True
def run(self, stack_context):
# stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
self.ppt.pprint_st... | raise |
Next line prediction: <|code_start|>
@click.command('status')
@click.option('--dry-run', '-d', is_flag=True, default=False,
help='Don\'t retrieve stack deployment status (faster).')
@click.option('--stack-resources', '-r', is_flag=True, default=False,
help='Display stack resources.')
@clic... | dry_run=dry_run, |
Given the following code snippet before the placeholder: <|code_start|>
@click.command('status')
@click.option('--dry-run', '-d', is_flag=True, default=False,
help='Don\'t retrieve stack deployment status (faster).')
@click.option('--stack-resources', '-r', is_flag=True, default=False,
hel... | pretty_printer=ctx.obj.ppt, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class Boto3RunBook(RunBook):
def __init__(self, profile, artifact_store, manager, selector, pretty_printer):
RunBook.__init__(self)
self._profile = profile
self._artifact_store = artifact_store
self._manager = manager
... | self._ppt.secho('Available stacks are:') |
Given snippet: <|code_start|>
def test_main():
cli_runner = click.testing.CliRunner()
with cli_runner.isolated_filesystem():
# by default, print help when invoked with no options
result = cli_runner.invoke(cli)
assert result.exit_code == 0
assert "AWS CloudFormation CLI" in r... | assert os.path.exists("cfn-cli.yaml") |
Using the snippet: <|code_start|>
class StackDeleteOptions(namedtuple('StackDeleteOptions',
['no_wait',
'ignore_missing'])):
pass
class StackDeleteCommand(Command):
SKIP_UPDATE_REFERENCES = True
def run(self, stack_context):
... | parameters['StackName'], |
Next line prediction: <|code_start|>
class StackDeleteOptions(namedtuple('StackDeleteOptions',
['no_wait',
'ignore_missing'])):
pass
class StackDeleteCommand(Command):
SKIP_UPDATE_REFERENCES = True
def run(self, stack_context):
... | parameters['StackName'], |
Given the following code snippet before the placeholder: <|code_start|> # stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
self.ppt.pprint_stack_name(stack_context.stack_key,
... | raise |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def _extends(base, **kwargs):
for k, v in base.items():
base[k] = kwargs.get(k, v)
class StackDefaults(object):
STACK_KEY = dict(
<|code_end|>
, determine the next line of code. You have imports:
import fnmatch
import copy
from collections i... | StageKey=None, |
Next line prediction: <|code_start|>
def run(self, stack_context):
# stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
# print qualified name
self.ppt.pprint_stack_name(stack_context.stack_key,
... | try: |
Continue the code snippet: <|code_start|>
class StackDeployOptions(
namedtuple('StackDeployOptions',
[
'no_wait',
'on_failure',
'disable_rollback',
'timeout_in_minutes',
'ignore_existing'
]... | session = stack_context.session |
Given the following code snippet before the placeholder: <|code_start|>
@click.command('validate')
@click.pass_context
@command_exception_handler
<|code_end|>
, predict the next line using imports from the current file:
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import com... | def cli(ctx): |
Given the following code snippet before the placeholder: <|code_start|>
@click.command('validate')
@click.pass_context
@command_exception_handler
<|code_end|>
, predict the next line using imports from the current file:
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import com... | def cli(ctx): |
Given the following code snippet before the placeholder: <|code_start|> ['no_wait',
'use_previous_template',
'ignore_no_update',
'override_policy'])):
pass
class StackU... | parameters['UsePreviousTemplate'] = True |
Given the following code snippet before the placeholder: <|code_start|> CANNED_STACK_POLICIES[self.options.override_policy]
self.ppt.pprint_parameters(parameters)
# termination protection state should be updated no matter
# stack's update succeeded or not
update_terminat... | self.ppt.secho('Stack update complete.', fg='green') |
Here is a snippet: <|code_start|> self.ppt.pprint_session(session)
# manipulate stack parameters for update call
if self.options.use_previous_template:
parameters.pop('TemplateBody', None)
parameters.pop('TemplateURL', None)
parameters['UsePreviousTemplate'] =... | self.ppt) |
Next line prediction: <|code_start|> # create boto3 cfn resource
cfn = session.resource('cloudformation')
self.ppt.pprint_session(session)
# manipulate stack parameters for update call
if self.options.use_previous_template:
parameters.pop('TemplateBody', None)
... | termination_protection, |
Predict the next line for this snippet: <|code_start|># -*- encoding: utf-8 -*-
@click.command()
@click.pass_context
@command_exception_handler
<|code_end|>
with the help of current file imports:
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handl... | def diff(ctx): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
CANNED_STACK_POLICIES = {
'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource"... | 'DENY_DELETE': '{"Statement":[{"Effect":"Allow","NotAction":"Update:Delete","Principal":"*","Resource":"*"}]}', |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
CANNED_STACK_POLICIES = {
'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
... | class ConfigFormat(object): |
Given snippet: <|code_start|> for key, (typ, default) in self.STACK_CONFIG.items():
# skip unknown parameters
if key not in extends:
continue
# overwrite Capabilities parameter
if key == 'Capabilities':
config[key] = copy.deepcopy(... | stack_order = stack_config.get('Order', 0) |
Next line prediction: <|code_start|>
def __init__(self, **context):
self._context = context
def validate(self, config):
schema = load_schema(str(self.VERSION))
jsonschema.validate(config, schema)
def parse(self, config):
raise NotImplementedError
class FormatV2(ConfigForm... | TimeoutInMinutes=(six.integer_types, None), |
Continue the code snippet: <|code_start|>CANNED_STACK_POLICIES = {
'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
'DENY_DELETE': '{"Statement... | raise NotImplementedError |
Based on the snippet: <|code_start|> Order=(six.integer_types, None),
Profile=(six.string_types, None),
Region=(six.string_types, None),
Package=(bool, None),
ArtifactStore=(six.string_types, None),
StackName=(six.string_types, None),
Template=(six.string_types, No... | raise jsonschema.SchemaError( |
Predict the next line after this snippet: <|code_start|> else:
config[key].update(extends[key])
# copy everything else
else:
config[key] = copy.deepcopy(extends[key])
return config
def _build_stack(self, stage_key, stack_key, stage... | if stack_policy and stack_policy not in CANNED_STACK_POLICIES: |
Next line prediction: <|code_start|> STACK_CONFIG = dict(
Order=(six.integer_types, None),
Profile=(six.string_types, None),
Region=(six.string_types, None),
Package=(bool, None),
ArtifactStore=(six.string_types, None),
StackName=(six.string_types, None),
Templ... | if have_parameter_reference_pattern(config): |
Predict the next line after this snippet: <|code_start|>
class DriftDiffOptions(namedtuple('DriftDiffOptions',
[])):
pass
class DriftDiffCommand(Command):
SKIP_UPDATE_REFERENCES = True
def run(self, stack_context):
# stack contexts
session = stack_conte... | metadata = stack_context.metadata |
Given the following code snippet before the placeholder: <|code_start|> client_request_token = 'awscfncli-sync-{}'.format(uuid.uuid1())
self.ppt.secho('Executing ChangeSet...')
client.execute_change_set(
ChangeSetName=changeset_name,
StackName=parameters['StackName'],
... | ) |
Here is a snippet: <|code_start|> termination_protection = parameters.pop(
'EnableTerminationProtection', None)
self.ppt.pprint_parameters(parameters)
# create changeset
echo_pair('ChangeSet Name', changeset_name)
echo_pair('ChangeSet Type', changeset_type)
... | if self.options.confirm: |
Here is a snippet: <|code_start|> def describe_change_set(self, client, changeset_name, parameters):
return client.describe_change_set(
ChangeSetName=changeset_name,
StackName=parameters['StackName'],
)
@backoff.on_exception(backoff.expo, botocore.exceptions.ClientError, ... | return changeset_type, is_new_stack |
Predict the next line after this snippet: <|code_start|>
self.ppt.pprint_parameters(parameters)
# create changeset
echo_pair('ChangeSet Name', changeset_name)
echo_pair('ChangeSet Type', changeset_type)
result = self.create_change_set(client, parameters)
changeset_id = ... | return |
Predict the next line for this snippet: <|code_start|> parameters.pop('TemplateURL', None)
parameters['UsePreviousTemplate'] = True
else:
stack_context.run_packaging()
# create cfn client
client = session.client('cloudformation')
# generate a unique c... | result = self.create_change_set(client, parameters) |
Given snippet: <|code_start|># -*- encoding: utf-8 -*-
@click.command()
@click.option('--no-wait', '-w', is_flag=True, default=False,
help='Exit immediately after operation is started.')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
from awscfncli2.... | @click.pass_context |
Next line prediction: <|code_start|># -*- encoding: utf-8 -*-
@click.command()
@click.option('--no-wait', '-w', is_flag=True, default=False,
help='Exit immediately after operation is started.')
<|code_end|>
. Use current file imports:
(import click
from awscfncli2.cli.context import Context
from aws... | @click.pass_context |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class ConfigError(Exception):
pass
class ConfigParser(object):
def get_format(self, config, **context):
# inspect version
version = config.get('Version')
config_format = load_format(version)
return config_for... | fmt.validate(config) |
Next line prediction: <|code_start|>
@click.command()
@click.option('--no-wait', '-w', is_flag=True, default=False,
help='Exit immediately after operation is started.')
@click.pass_context
@command_exception_handler
def cancel(ctx, no_wait):
"""Cancel current stack update.
Only works if stack be... | 'CancelUpdateStack cannot be called from current stack status'): |
Continue the code snippet: <|code_start|># -*- encoding: utf-8 -*-
@click.command()
@click.option('--no-wait', '-w', is_flag=True, default=False,
help='Exit immediately after operation is started.')
@click.pass_context
@command_exception_handler
<|code_end|>
. Use current file imports:
import botoco... | def cancel(ctx, no_wait): |
Predict the next line for this snippet: <|code_start|> def example_tester_mean(self, solver="cbc", solver_io=None):
model = self.model_runner(solver=solver, solver_io=solver_io, how="mean")
# Full 1-hourly model run: 22312488.670967
assert float(model.results.cost.sum()) == approx(22172253.32... | ) == approx(0.100760, abs=0.000001) |
Given the following code snippet before the placeholder: <|code_start|>
# Full 1-hourly model run: 0.296973
assert float(
model.results.systemwide_levelised_cost.loc[
{"carriers": "power", "techs": "battery"}
].item()
) == approx(0.122564, abs=0.000001)
... | def example_tester(self, resource_unit, solver="cbc", solver_io=None): |
Here is a snippet: <|code_start|>
calliope.set_log_verbosity("CRITICAL", include_solver_output=False)
assert logging.getLogger("calliope").getEffectiveLevel() == 50
assert logging.getLogger("py.warnings").getEffectiveLevel() == 50
assert (
logging.getLogger("calliope.backend... | logger, |
Given the following code snippet before the placeholder: <|code_start|> ("foo", None, None, {"foobar": {"baz": 2}}),
),
)
def test_set_item_observer(
self, observed_from_dict, observer, key1, key2, value, result
):
if key2 is None:
observed_from_dict[key1] = va... | ) |
Based on the snippet: <|code_start|> or (isinstance(v, dict) and len(v.keys()) > 0)
}
return calliope.AttrDict.to_yaml(calliope.AttrDict(_dict))
@pytest.fixture(scope="module")
def model(self):
return calliope.examples.national_scale()
@pytest.fixture(scope="modu... | ): |
Here is a snippet: <|code_start|>
_MODEL_NATIONAL = os.path.join(
os.path.dirname(__file__), "..", "example_models", "national_scale", "model.yaml"
)
_MODEL_URBAN = os.path.join(
os.path.dirname(__file__), "..", "example_models", "urban_scale", "model.yaml"
)
class TestDataset:
@pytest.fixture()
... | }, |
Using the snippet: <|code_start|> assert observer.attrs["test"] == self.as_yaml(
{"foo": 5, "foobar": {"baz": 2}, "baz": 4}
)
def test_model_config(self, model):
assert hasattr(model, "model_config")
assert "model_config" in model._model_data.attrs.keys()
assert m... | def test_load_from_netcdf(self, model): |
Predict the next line after this snippet: <|code_start|> def observed_from_string(self, observer):
initial_dict = {"foo": "bar", "foobar": {"baz": "fob"}}
return observed_dict.UpdateObserverDict(
initial_yaml_string=self.as_yaml(initial_dict),
name="test_2",
observ... | initial_dict=initial_dict, |
Predict the next line for this snippet: <|code_start|> )
@pytest.mark.parametrize(
"key1,key2,value,result",
(
("foo", None, 1, {"foo": 1, "foobar": {"baz": "fob"}}),
("foobar", "baz", 2, {"foo": 1, "foobar": {"baz": 2}}),
(
"foo",
... | observed_from_dict.update({"baz": 4}) |
Given snippet: <|code_start|> initial_dict = {"foo": "bar", "foobar": {"baz": "fob"}}
initial_string = self.as_yaml(initial_dict)
with pytest.raises(ValueError) as error:
observed_dict.UpdateObserverDict(name="test_2", observer=xr.Dataset())
assert check_error_or_warning(
... | ), |
Here is a snippet: <|code_start|> "power", "region1", "ccgt"
] == approx(115569.4354)
assert float(model.results.cost.sum()) > 6.6e7
@pytest.mark.parametrize(
"scenario,cost_class,weight",
[
("monetary_objective", ["monetary"], [1]),
("emissions_o... | model.backend.update_param("objective_cost_class", {"emissions": 0.2}) |
Given snippet: <|code_start|>
class TestIO:
@pytest.fixture(scope="module")
def model(self):
model = calliope.examples.national_scale()
model.run()
return model
def test_save_netcdf(self, model):
bool_attrs = [
k for k, v in model._model_data.attrs.items() if i... | @pytest.mark.parametrize( |
Next line prediction: <|code_start|> "2005-01-02 23:00:00",
"2005-01-02 23:15:00",
"2005-01-02 23:30:00",
"2005-01-02 23:45:00",
]
)
assert dtindex.equals(mask)
def test_15min_to_2h_masking_1D(self):
# The data is i... | "2005-01-02 01:00:00", |
Using the snippet: <|code_start|> "2005-01-02 14:45:00",
"2005-01-02 15:00:00",
"2005-01-02 15:15:00",
"2005-01-02 15:30:00",
"2005-01-02 15:45:00",
"2005-01-02 16:00:00",
"2005-01-02 16:15:00",
... | "2005-01-02 22:15:00", |
Given the following code snippet before the placeholder: <|code_start|> "2005-01-02 05:00:00",
"2005-01-02 06:00:00",
"2005-01-02 16:00:00",
"2005-01-02 17:00:00",
"2005-01-02 18:00:00",
"2005-01-02 19:00:00",
... | "2005-01-04 05:00:00", |
Using the snippet: <|code_start|> with pytest.raises(exceptions.ModelError) as error:
build_test_model(override4, scenario="simple_supply")
assert check_error_or_warning(
error,
"Missing data for the timeseries array(s) [('cluster_days.csv', 'a') ('cluster_days.csv', ... | "2005-01-01 02:00:00", |
Using the snippet: <|code_start|> "2005-01-02 21:45:00",
"2005-01-02 22:00:00",
"2005-01-02 22:15:00",
"2005-01-02 22:30:00",
"2005-01-02 22:45:00",
"2005-01-02 23:00:00",
"2005-01-02 23:15:00",
... | "techs.test_demand_elec.constraints.resource": "file=demand_elec_15mins.csv", |
Based on the snippet: <|code_start|> 1,
1,
2,
2,
2,
2,
2,
1,
1,
2,
2,
2,
],
)
@python36_or_higher
de... | assert np.array_equal( |
Using the snippet: <|code_start|>
@pytest.fixture(scope="class")
def model():
return build_model({}, "simple_supply,two_hours,investment_costs")
class TestGetParam:
<|code_end|>
, determine the next line of code. You have imports:
import pytest # noqa: F401
import pyomo.core as po
from calliope.test.common.u... | def test_get_param_with_timestep_existing(self): |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture(scope="class")
def model():
return build_model({}, "simple_supply,two_hours,investment_costs")
<|code_end|>
, predict the next line using imports from the current file:
import pytest # noqa: F401
import pyomo.core as po
f... | class TestGetParam: |
Given snippet: <|code_start|>
class TestDeprecationWarnings:
def test_get_formatted_array_deprecationwarning(self):
model = build_model(scenario="simple_supply,one_day,investment_costs")
model.run()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytes... | with pytest.warns(DeprecationWarning) as warning: |
Next line prediction: <|code_start|>
class TestDeprecationWarnings:
def test_get_formatted_array_deprecationwarning(self):
model = build_model(scenario="simple_supply,one_day,investment_costs")
model.run()
with pytest.warns(DeprecationWarning) as warning:
model.get_formatted_... | ) |
Here is a snippet: <|code_start|> Parameters
----------
data : xarray Dataset
Dataset with all non-time dependent variables removed
Returns
-------
ds : xarray Dataset
Copy of `data`, with the absolute taken and normalized to 0-1
"""
ds = data.copy(deep=True) # Work off... | return data1 |
Using the snippet: <|code_start|> Parameters
----------
data : xarray Dataset
Dataset with all non-time dependent variables removed
Returns
-------
ds : xarray Dataset
Copy of `data`, with the absolute taken and normalized to 0-1
"""
ds = data.copy(deep=True) # Work off... | return data1 |
Given the code snippet: <|code_start|>
def build_model(override_dict, scenario):
model_path = os.path.join(
os.path.dirname(__file__), "common", "test_model", "model.yaml"
)
return calliope.Model(model_path, override_dict=override_dict, scenario=scenario)
<|code_end|>
, generate the next line ... | class TestExistsFalse: |
Given snippet: <|code_start|>
def build_model(override_dict, scenario):
model_path = os.path.join(
os.path.dirname(__file__), "common", "test_model", "model.yaml"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import pytest # noqa: F401
import calliope
fro... | ) |
Using the snippet: <|code_start|>
# Infeasible case, unmet_demand is required
assert hasattr(model_unmet_demand._backend_model, "unmet_demand")
assert hasattr(model_unmet_demand._backend_model, "unused_supply")
assert model_unmet_demand._model_data["unmet_demand"].sum() == 15
ass... | def test_expected_infeasible_result(self, override, run_model): |
Given the code snippet: <|code_start|>
def test_simple_case(tmpdir):
x = tmpdir.join('f')
x.write('#!/usr/bin/env echo')
make_executable(x.strpath)
assert parse_shebang.parse_filename(x.strpath) == ('echo',)
def test_find_executable_full_path():
assert parse_shebang.find_executable(sys.executable... | @contextlib.contextmanager |
Given the code snippet: <|code_start|>from __future__ import annotations
def _echo_exe() -> str:
exe = shutil.which('echo')
assert exe is not None
return exe
def test_file_doesnt_exist():
assert parse_shebang.parse_filename('herp derp derp') == ()
def test_simple_case(tmpdir):
<|code_end|>
, ge... | x = tmpdir.join('f') |
Given snippet: <|code_start|>
def _echo_exe() -> str:
exe = shutil.which('echo')
assert exe is not None
return exe
def test_file_doesnt_exist():
assert parse_shebang.parse_filename('herp derp derp') == ()
def test_simple_case(tmpdir):
x = tmpdir.join('f')
x.write('#!/usr/bin/env echo')
m... | def write_executable(shebang, filename='run'): |
Given the following code snippet before the placeholder: <|code_start|>
def test_find_executable_full_path():
assert parse_shebang.find_executable(sys.executable) == sys.executable
def test_find_executable_on_path():
assert parse_shebang.find_executable('echo') == _echo_exe()
def test_find_executable_not_fo... | path = os.path.abspath(write_executable('/usr/bin/env sh')) |
Predict the next line for this snippet: <|code_start|> os.name == 'nt',
reason="lua isn't installed or can't be found",
)
skipif_cant_run_swift = pytest.mark.skipif(
parse_shebang.find_executable('swift') is None,
reason="swift isn't installed or can't be found",
)
xfailif_windows = pytest.mark.xfail(os.... | assert not (all_files and files) |
Based on the snippet: <|code_start|> verbose=verbose,
hook=hook,
remote_branch=remote_branch,
local_branch=local_branch,
from_ref=from_ref,
to_ref=to_ref,
remote_name=remote_name,
remote_url=remote_url,
hook_stage=hook_stage,
show_diff_on_fa... | cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args) |
Continue the code snippet: <|code_start|>
def cmd_output_mocked_pre_commit_home(
*args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
):
if pre_commit_home is None:
pre_commit_home = tempdir_factory.get()
env = env if env is not None else os.environ
kwargs.setdefault('stderr', ... | ) |
Given the following code snippet before the placeholder: <|code_start|>
def run_opts(
all_files=False,
files=(),
color=False,
verbose=False,
hook=None,
remote_branch='',
local_branch='',
from_ref='',
to_ref='',
remote_name='',
remot... | from_ref=from_ref, |
Using the snippet: <|code_start|> verbose=False,
hook=None,
remote_branch='',
local_branch='',
from_ref='',
to_ref='',
remote_name='',
remote_url='',
hook_stage='commit',
show_diff_on_failure=False,
commit_msg_filename='',
ch... | show_diff_on_failure=show_diff_on_failure, |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = 'coursier'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
def install_environment(
prefix: Prefix,
<|code_end|>
, predict the next line using... | version: str, |
Predict the next line for this snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = 'coursier'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
def install_environment(
prefix: Prefix,
version: str,
<|code_end|>
with the help of curren... | additional_dependencies: Sequence[str], |
Here is a snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
<|code_end|>
. Write the next line using the current file imports:
from typing import Sequenc... | def run_hook( |
Using the snippet: <|code_start|> tree_hash = cmd_output('git', 'write-tree')[1].strip()
merge_diff_filenames = zsplit(
cmd_output(
'git', 'diff', '--name-only', '--no-ext-diff', '-z',
'-m', tree_hash, 'HEAD', 'MERGE_HEAD',
)[1],
)
return set(merge_conflict_filenam... | if status[0] in {'C', 'R'}: # renames / moves have an additional arg |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
logger = logging.getLogger(__name__)
# see #2046
NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false')
<|code_end|>
using the current file's imports:
import logging
import os.path
import sys
from typing import MutableM... | def zsplit(s: str) -> list[str]: |
Based on the snippet: <|code_start|> return zsplit(
cmd_output(
'git', 'diff', '--staged', '--name-only', '--no-ext-diff', '-z',
# Everything except for D
'--diff-filter=ACMRTUXB',
cwd=cwd,
)[1],
)
def intent_to_add_files() -> list[str]:
_, st... | def get_changed_files(old: str, new: str) -> list[str]: |
Given the following code snippet before the placeholder: <|code_start|>
return zsplit(out)
def head_rev(remote: str) -> str:
_, out, _ = cmd_output('git', 'ls-remote', '--exit-code', remote, 'HEAD')
return out.split()[0]
def has_diff(*args: str, repo: str = '.') -> bool:
cmd = ('git', 'diff', '--qui... | def commit(repo: str = '.') -> None: |
Predict the next line for this snippet: <|code_start|> description: str
language_version: str
log_file: str
minimum_pre_commit_version: str
require_serial: bool
stages: Sequence[str]
verbose: bool
@property
def cmd(self) -> tuple[str, ...]:
return (*shlex.split(self.entry), *... | return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS}) |
Given snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def run_hook(
hook: Hook,
file_args: Sequence[str],
color: bool,
) -> tuple... | cmd = (hook.prefix.path(hook.cmd[0]), *hook.cmd[1:]) |
Continue the code snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def run_hook(
hook: Hook,
<|code_end|>
. Use current file imports:
from typing... | file_args: Sequence[str], |
Given the code snippet: <|code_start|> cmd = ('ninechars',)
# counted as half because of utf-16 encode
varargs = ('😑' * 5,)
ret = xargs.partition(cmd, varargs, 1, _max_length=21)
assert ret == (cmd + varargs,)
def test_partition_limit_linux(linux_mock):
cmd = ('ninechars',)
varargs = ('😑'... | ('foo',) + ('A',) * 6, |
Based on the snippet: <|code_start|> # takes less, they must have run concurrently.
assert elapsed < 2.5
def test_thread_mapper_concurrency_uses_threadpoolexecutor_map():
with xargs._thread_mapper(10) as thread_map:
_self = thread_map.__self__ # type: ignore
assert isinstance(_self, concur... | color=True, |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
def _is_header_line(line: str) -> bool:
return line.startswith(('#', '---')) or not line.strip()
def _migrate_map(contents: str) -> str:
if isinstance(yaml_load(contents), list):
# Find the first non-header... | i += 1 |
Based on the snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def _process_filename_by_line(pattern: Pattern[bytes], filename: str) -> int:
retv = 0
<... | with open(filename, 'rb') as f: |
Given snippet: <|code_start|>from __future__ import annotations
DOCKER_CGROUP_EXAMPLE = b'''\
12:hugetlb:/docker/c33988ec7651ebc867cb24755eaf637a6734088bc7eef59d5799293a9e5450f7
11:blkio:/docker/c33988ec7651ebc867cb24755eaf637a6734088bc7eef59d5799293a9e5450f7
<|code_end|>
, continue by predicting the next line. Con... | 10:freezer:/docker/c33988ec7651ebc867cb24755eaf637a6734088bc7eef59d5799293a9e5450f7 |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_identity(cap_out):
assert not identity.main(('a', 'b', 'c'))
<|code_end|>
, generate the next line using the imports in this file:
from pre_commit.meta_hooks import identity
and context (functions, classes, or occasionally code) ... | assert cap_out.get() == 'a\nb\nc\n' |
Predict the next line for this snippet: <|code_start|> 'repos:\n'
'- repo: local\n'
' hooks:\n'
' - id: foo\n'
' name: foo\n'
' entry: ./bin/foo.sh\n'
' language: script\n'
)
def test_migrate_config_list_literal(tmpdir):
cfg... | ' language: script,\n' |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_init_templatedir(tmpdir, tempdir_factory, store, cap_out):
target = str(tmpdir.join('tmpl'))
init_templatedir(C.CONFIG_FILE, store, target, hook_types=['pre-commit'])
lines = cap_out.get().splitlines()
assert lines[0]... | assert lines[2].startswith( |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_init_templatedir(tmpdir, tempdir_factory, store, cap_out):
target = str(tmpdir.join('tmpl'))
init_templatedir(C.CONFIG_FILE, store, target, hook_types=['pre-commit'])
lines = cap_out.get().splitlines()
assert lines[0]... | assert lines[1] == ( |
Predict the next line for this snippet: <|code_start|> # set HOME to ignore the current `.gitconfig`
with envcontext((('HOME', str(tmpdir)),)):
with tmpdir.join('tmpl').ensure_dir().as_cwd():
# we have not set init.templateDir so this should produce a warning
init_templatedir(
... | def test_init_templatedir_hookspath_set(tmpdir, tempdir_factory, store): |
Given the following code snippet before the placeholder: <|code_start|> )
assert target.join('hooks/pre-commit').exists()
@pytest.mark.parametrize(
('skip', 'commit_retcode', 'commit_output_snippet'),
(
(True, 0, 'Skipping `pre-commit`.'),
(False, 1, f'No {C.CONFIG_FILE} file was fo... | ) |
Given the following code snippet before the placeholder: <|code_start|> if '/*' in dct.get(self.key, ''):
logger.warning(
f'The top-level {self.key!r} field is a regex, not a glob -- '
f"matching '/*' probably isn't what you want here",
)
for fwd_sl... | elif 'sha' in dct and 'rev' in dct: |
Predict the next line after this snippet: <|code_start|> f'Hint: `pre-commit autoupdate` often fixes this.',
)
class OptionalSensibleRegexAtHook(cfgv.OptionalNoDefault):
def check(self, dct: dict[str, Any]) -> None:
super().check(dct)
if '/*' in dct.get(self.key... | f"matching '/*' probably isn't what you want here", |
Predict the next line for this snippet: <|code_start|> f'Try upgrading identify and pre-commit?',
)
def check_min_version(version: str) -> None:
if parse_version(version) > parse_version(C.VERSION):
raise cfgv.ValidationError(
f'pre-commit version {version} is required but v... | cfgv.Optional('files', check_string_regex, ''), |
Here is a snippet: <|code_start|> cfgv.Optional('description', cfgv.check_string, ''),
cfgv.Optional('language_version', cfgv.check_string, C.DEFAULT),
cfgv.Optional('log_file', cfgv.check_string, ''),
cfgv.Optional('minimum_pre_commit_version', cfgv.check_string, '0'),
cfgv.Optional('require_serial'... | try: |
Given snippet: <|code_start|> logger.warning(
f'The {self.key!r} field of repo {dct["repo"]!r} '
f'appears to be a mutable reference '
f'(moving tag / branch). Mutable references are never '
f'updated after first install and... | class OptionalSensibleRegexAtTop(cfgv.OptionalNoDefault): |
Based on the snippet: <|code_start|> assert ACTUAL_GET_DEFAULT_VERSION() == 'system'
@pytest.mark.usefixtures('is_linux')
def test_uses_default_when_node_and_npm_are_not_available(find_exe_mck):
find_exe_mck.return_value = None
assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT
@pytest.mark.usefixtures('is... | prefix_dir = tmpdir.join('prefix').ensure_dir() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.