uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55509e4cc8a161387fd309a3 | train | function | @pytest.mark.parametrize(('arch',), [(arch,) for arch in architecture.ARCH_SUPPORTED])
def test_checks_performed_only_on_s390x_arch(arch, monkeypatch):
"""Tests whether the actor doesn't perform different architectures than s390x."""
should_perform = False
if arch == architecture.ARCH_S390X: # Rescue entri... | @pytest.mark.parametrize(('arch',), [(arch,) for arch in architecture.ARCH_SUPPORTED])
def test_checks_performed_only_on_s390x_arch(arch, monkeypatch):
| """Tests whether the actor doesn't perform different architectures than s390x."""
should_perform = False
if arch == architecture.ARCH_S390X: # Rescue entries should be checked only on s390x.
should_perform = True
monkeypatch.setattr(api, 'current_actor', CurrentActorMocked(arch=arch))
monk... | ', kernel_image='/boot/vmlinuz-rescue-4.18.0-240.1.1.el8_3.x86_64')],)])
def test_inhibition_when_rescue_entries_share_kernel(monkeypatch, boot_entries):
"""
Tests whether the IPU is not inhibited when there are kernel images with the same version shared between rescue
boot entries.
"""
monkeypatch.... | 156 | 156 | 521 | 35 | 120 | tmds/leapp-repository | repos/system_upgrade/el7toel8/actors/ziplcheckbootentries/tests/test_ziplcheckbootentries.py | Python | test_checks_performed_only_on_s390x_arch | test_checks_performed_only_on_s390x_arch | 107 | 143 | 107 | 108 | 28f12c5096588087f5e5e28ce6b6011dc3906bcf | bigcode/the-stack | train |
647b9ee2a4a1a5e5db54d7dd | train | function | @pytest.mark.parametrize(
('boot_entries',),
[([BootEntry(title='Linux', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'),
BootEntry(title='Linux-rescue', kernel_image='/boot/vmlinuz-rescue-4.18.0-240.1.1.el8_3.x86_64')],),
([BootEntry(title='Linux0-rescue', kernel_image='/boot/vmlinuz-resc... | @pytest.mark.parametrize(
('boot_entries',),
[([BootEntry(title='Linux', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'),
BootEntry(title='Linux-rescue', kernel_image='/boot/vmlinuz-rescue-4.18.0-240.1.1.el8_3.x86_64')],),
([BootEntry(title='Linux0-rescue', kernel_image='/boot/vmlinuz-resc... | """
Tests whether the IPU is not inhibited when there are kernel images with the same version shared between rescue
boot entries.
"""
monkeypatch.setattr(reporting, 'create_report', create_report_mocked())
inhibit_if_entries_share_kernel_version(SourceBootLoaderConfiguration(entries=boot_entries... | @pytest.mark.parametrize(
('boot_entries',),
[([BootEntry(title='Linux', kernel_image='/boot/vmlinuz-4.18.0-240.1.1.el8_3.x86_64'),
BootEntry(title='Linux-rescue', kernel_image='/boot/vmlinuz-rescue-4.18.0-240.1.1.el8_3.x86_64')],),
([BootEntry(title='Linux0-rescue', kernel_image='/boot/vmlinuz-resc... | 188 | 77 | 259 | 188 | 0 | tmds/leapp-repository | repos/system_upgrade/el7toel8/actors/ziplcheckbootentries/tests/test_ziplcheckbootentries.py | Python | test_inhibition_when_rescue_entries_share_kernel | test_inhibition_when_rescue_entries_share_kernel | 91 | 104 | 91 | 97 | 7e9840353df158c8d46c0aa6ba66161cca64a0ad | bigcode/the-stack | train |
3060f87c358c2226f0ea05d4 | train | function | def test_inhibition_multiple_rescue_entries_present(monkeypatch):
"""Tests whether the upgrade process is inhibited when multiple rescue boot entries are present."""
mocked_report = create_report_mocked()
monkeypatch.setattr(architecture, 'matches_architecture', lambda dummy: True)
monkeypatch.setattr(r... | def test_inhibition_multiple_rescue_entries_present(monkeypatch):
| """Tests whether the upgrade process is inhibited when multiple rescue boot entries are present."""
mocked_report = create_report_mocked()
monkeypatch.setattr(architecture, 'matches_architecture', lambda dummy: True)
monkeypatch.setattr(reporting, 'create_report', mocked_report)
boot_entries = [
... | _multiple_zipl_rescue_entries_present
)
from leapp.libraries.common.config import architecture
from leapp.libraries.common.testutils import create_report_mocked, CurrentActorMocked
from leapp.libraries.stdlib import api
from leapp.models import BootEntry, SourceBootLoaderConfiguration
from leapp.snactor.fixture import ... | 85 | 85 | 285 | 13 | 71 | tmds/leapp-repository | repos/system_upgrade/el7toel8/actors/ziplcheckbootentries/tests/test_ziplcheckbootentries.py | Python | test_inhibition_multiple_rescue_entries_present | test_inhibition_multiple_rescue_entries_present | 18 | 41 | 18 | 18 | f346de342f73d049f5c218b62784f80a2a23e05c | bigcode/the-stack | train |
60d7c718335612d410f1ddbc | train | class | class Engine(Watched):
def __init__(
self,
formatter,
target_components=None,
extract_timeout=None,
extract_tmp_dir=None,
):
super().__init__()
self.Formatter = formatter or HumanReadableFormat
self.target_components = target_components
sel... | class Engine(Watched):
| def __init__(
self,
formatter,
target_components=None,
extract_timeout=None,
extract_tmp_dir=None,
):
super().__init__()
self.Formatter = formatter or HumanReadableFormat
self.target_components = target_components
self.extract_timeout = ext... | import logging
from io import StringIO
from insights.core import dr
from insights.core.archives import extract
from insights.core.hydration import create_context
from insights.formats.text import HumanReadableFormat
from insights_messaging.watchers import Watched
log = logging.getLogger(__name__)
class Engine(Watched... | 66 | 80 | 269 | 5 | 61 | dpensi/insights-core-messaging | insights_messaging/engine.py | Python | Engine | Engine | 13 | 55 | 13 | 13 | 9c08a20eb5fe2e89784230716b269979a4a36444 | bigcode/the-stack | train |
9adec300b77697fd91a48a88 | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.cron
def test_default_monitor_attach_followed_by_baseline_and_update_monitoring_schedule(
sagemaker_session,
default_monitoring_schedul... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.cron
def test_default_monitor_attach_followed_by_baseline_and_update_monitoring_schedule(
sagemaker_session,
default_monitoring_schedul... | my_attached_monitor = DefaultModelMonitor.attach(
monitor_schedule_name=default_monitoring_schedule_name, sagemaker_session=sagemaker_session
)
output_s3_uri = os.path.join(
"s3://",
sagemaker_session.default_bucket(),
"integ-test-monitoring-output-bucket",
str(uuid.... |
)
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"].get(
"BaselineConfig"
)
is None
)
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"][
"Environment"
].get(ENV_KEY_1)
... | 256 | 256 | 1,073 | 87 | 169 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_default_monitor_attach_followed_by_baseline_and_update_monitoring_schedule | test_default_monitor_attach_followed_by_baseline_and_update_monitoring_schedule | 1,331 | 1,485 | 1,331 | 1,341 | 577d9918b9388affe98c5065da4bf9e378997921 | bigcode/the-stack | train |
62f8135f47f7e835e41d273c | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.canary_quick
def test_default_monitor_suggest_baseline_and_create_monitoring_schedule_with_customizations(
sagemaker_session, output_kms_ke... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.canary_quick
def test_default_monitor_suggest_baseline_and_create_monitoring_schedule_with_customizations(
sagemaker_session, output_kms_ke... | baseline_dataset = os.path.join(DATA_DIR, "monitor/baseline_dataset.csv")
my_default_monitor = DefaultModelMonitor(
role=ROLE,
instance_count=INSTANCE_COUNT,
instance_type=INSTANCE_TYPE,
volume_size_in_gb=VOLUME_SIZE_IN_GB,
volume_kms_key=volume_kms_key,
output_k... | updated_volume_kms_key(sagemaker_session):
role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-volume-kms-key-updated-{}".format(
sagemaker_session.boto_session.regi... | 256 | 256 | 1,450 | 81 | 175 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_default_monitor_suggest_baseline_and_create_monitoring_schedule_with_customizations | test_default_monitor_suggest_baseline_and_create_monitoring_schedule_with_customizations | 273 | 473 | 273 | 280 | c8d730d1c90b43e07e2a64e53fb050410c683e6b | bigcode/the-stack | train |
66fd2d90670b8108197e0a55 | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.cron
def test_byoc_monitor_attach_followed_by_baseline_and_update_monitoring_schedule(
sagemaker_session,
predictor,
byoc_monitorin... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.cron
def test_byoc_monitor_attach_followed_by_baseline_and_update_monitoring_schedule(
sagemaker_session,
predictor,
byoc_monitorin... | baseline_dataset = os.path.join(DATA_DIR, "monitor/baseline_dataset.csv")
byoc_env = ENVIRONMENT.copy()
byoc_env["dataset_format"] = json.dumps(DatasetFormat.csv(header=False))
byoc_env["dataset_source"] = "/opt/ml/processing/input/baseline_dataset_input"
byoc_env["output_path"] = os.path.join("/op... | Definition"]["Environment"][
UPDATED_ENV_KEY_1
]
== UPDATED_ENV_VALUE_1
)
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"]["Environment"][
"publish_cloudwatch_metrics"
]
== "Disabled"
)
assert (
s... | 256 | 256 | 1,632 | 104 | 151 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_byoc_monitor_attach_followed_by_baseline_and_update_monitoring_schedule | test_byoc_monitor_attach_followed_by_baseline_and_update_monitoring_schedule | 2,229 | 2,449 | 2,229 | 2,242 | 24b7402a74c1219e08809aa1e8e691366dc351e4 | bigcode/the-stack | train |
ba3b08720ce251722aac3425 | train | function | @pytest.fixture(scope="module")
def updated_volume_kms_key(sagemaker_session):
role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-volume-kms-key-updated-{}".format(
... | @pytest.fixture(scope="module")
def updated_volume_kms_key(sagemaker_session):
| role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-volume-kms-key-updated-{}".format(
sagemaker_session.boto_session.region_name
),
)
| agemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-output-kms-key-{}".format(
sagemaker_session.boto_session.region_name
),
)
@pytest.fixture(scope="module")
def updated_volume_kms_key(sagemaker_session):
| 64 | 64 | 91 | 17 | 47 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | updated_volume_kms_key | updated_volume_kms_key | 249 | 258 | 249 | 250 | a40cea1a66e34ef626902871eb74f9d83a317671 | bigcode/the-stack | train |
96eca9b32b2150b91d97674f | train | function | @pytest.fixture(scope="module")
def volume_kms_key(sagemaker_session):
role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-volume-kms-key-{}".format(
sagemaker_sessio... | @pytest.fixture(scope="module")
def volume_kms_key(sagemaker_session):
| role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-volume-kms-key-{}".format(
sagemaker_session.boto_session.region_name
),
)
| or=predictor, sagemaker_session=sagemaker_session)
_predict_while_waiting_for_first_monitoring_job_to_complete(predictor, my_byoc_monitor)
return my_byoc_monitor.monitoring_schedule_name
@pytest.fixture(scope="module")
def volume_kms_key(sagemaker_session):
| 64 | 64 | 88 | 16 | 47 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | volume_kms_key | volume_kms_key | 225 | 234 | 225 | 226 | bd6c08483de81791fabc331262f7f1cf94c3068a | bigcode/the-stack | train |
754e2867dd73ef607dd25810 | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_default_monitor_create_and_update_schedule_config_with_customizations(
sagemaker_session,
predictor,
volume_kms_key,
output_kms_key... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_default_monitor_create_and_update_schedule_config_with_customizations(
sagemaker_session,
predictor,
volume_kms_key,
output_kms_key... | my_default_monitor = DefaultModelMonitor(
role=ROLE,
instance_count=INSTANCE_COUNT,
instance_type=INSTANCE_TYPE,
volume_size_in_gb=VOLUME_SIZE_IN_GB,
volume_kms_key=volume_kms_key,
output_kms_key=output_kms_key,
max_runtime_in_seconds=MAX_RUNTIME_IN_SECONDS,
... | schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"][
"NetworkConfig"
]["EnableNetworkIsolation"]
== NETWORK_CONFIG.enable_network_isolation
)
_wait_for_schedule_changes_to_apply(monitor=my_default_monitor)
my_default_monitor.stop_monitoring_sched... | 256 | 256 | 1,900 | 87 | 169 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_default_monitor_create_and_update_schedule_config_with_customizations | test_default_monitor_create_and_update_schedule_config_with_customizations | 820 | 1,103 | 820 | 831 | 98887e3fbef5703c6be6810db07a0799e8b27eae | bigcode/the-stack | train |
f9a1c0de1ba994159cd75585 | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_byoc_monitor_suggest_baseline_and_create_monitoring_schedule_without_customizations(
sagemaker_session, predictor
):
baseline_dataset = os.... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_byoc_monitor_suggest_baseline_and_create_monitoring_schedule_without_customizations(
sagemaker_session, predictor
):
| baseline_dataset = os.path.join(DATA_DIR, "monitor/baseline_dataset.csv")
byoc_env = ENVIRONMENT.copy()
byoc_env["dataset_format"] = json.dumps(DatasetFormat.csv(header=False))
byoc_env["dataset_source"] = "/opt/ml/processing/input/baseline_dataset_input"
byoc_env["output_path"] = os.path.join("/op... | ]["MaxRuntimeInSeconds"]
== MAX_RUNTIME_IN_SECONDS
)
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"]["Environment"][
ENV_KEY_1
]
== ENV_VALUE_1
)
assert (
schedule_description["MonitoringScheduleConfig"]["Monitorin... | 256 | 256 | 1,418 | 65 | 190 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_byoc_monitor_suggest_baseline_and_create_monitoring_schedule_without_customizations | test_byoc_monitor_suggest_baseline_and_create_monitoring_schedule_without_customizations | 1,750 | 1,941 | 1,750 | 1,756 | 21b19992051b7b46cff674573217778f6d6dc8d9 | bigcode/the-stack | train |
608d79db1e910346ee2c3b4c | train | function | def _predict_while_waiting_for_first_monitoring_job_to_complete(predictor, monitor):
"""Waits for the schedule to have an execution in a terminal status.
Args:
monitor (sagemaker.model_monitor.ModelMonitor): The monitor to watch.
"""
for _ in retries(
max_retry_count=200,
excep... | def _predict_while_waiting_for_first_monitoring_job_to_complete(predictor, monitor):
| """Waits for the schedule to have an execution in a terminal status.
Args:
monitor (sagemaker.model_monitor.ModelMonitor): The monitor to watch.
"""
for _ in retries(
max_retry_count=200,
exception_message_prefix="Waiting for the latest execution to be in a terminal status.",
... | retries(
max_retry_count=100,
exception_message_prefix="Waiting for schedule to leave 'Pending' status",
seconds_to_sleep=5,
):
schedule_desc = monitor.describe_schedule()
if schedule_desc["MonitoringScheduleStatus"] != "Pending":
break
def _predict_while_waiting... | 77 | 77 | 259 | 20 | 56 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | _predict_while_waiting_for_first_monitoring_job_to_complete | _predict_while_waiting_for_first_monitoring_job_to_complete | 2,514 | 2,539 | 2,514 | 2,514 | e26fbc3073d4df1e1e71b5fe64f8982d92d1a830 | bigcode/the-stack | train |
6e5697c236a6d0de40bb1a89 | train | function | @pytest.fixture(scope="module")
def updated_output_kms_key(sagemaker_session):
role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-output-kms-key-updated-{}".format(
... | @pytest.fixture(scope="module")
def updated_output_kms_key(sagemaker_session):
| role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-output-kms-key-updated-{}".format(
sagemaker_session.boto_session.region_name
),
)
| _session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-volume-kms-key-updated-{}".format(
sagemaker_session.boto_session.region_name
),
)
@pytest.fixture(scope="module")
def updated_output_kms_key(sagemaker_session):
| 64 | 64 | 91 | 17 | 47 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | updated_output_kms_key | updated_output_kms_key | 261 | 270 | 261 | 262 | 2e6e462053b105e5c1922b607d0341badc8a2f69 | bigcode/the-stack | train |
0dcd89422a7c6a1364ab2ffd | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_byoc_monitor_suggest_baseline_and_create_monitoring_schedule_with_customizations(
sagemaker_session, output_kms_key, volume_kms_key, predictor
... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_byoc_monitor_suggest_baseline_and_create_monitoring_schedule_with_customizations(
sagemaker_session, output_kms_key, volume_kms_key, predictor
... | baseline_dataset = os.path.join(DATA_DIR, "monitor/baseline_dataset.csv")
byoc_env = ENVIRONMENT.copy()
byoc_env["dataset_format"] = json.dumps(DatasetFormat.csv(header=False))
byoc_env["dataset_source"] = "/opt/ml/processing/input/baseline_dataset_input"
byoc_env["output_path"] = os.path.join("/op... | _session=sagemaker_session
)
statistics = my_attached_monitor.latest_monitoring_statistics()
assert statistics.body_dict["dataset"]["item_count"] == 418
with open(os.path.join(tests.integ.DATA_DIR, "monitor/constraint_violations.json"), "r") as f:
file_body = f.read()
file_name = "constra... | 256 | 256 | 1,614 | 75 | 181 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_byoc_monitor_suggest_baseline_and_create_monitoring_schedule_with_customizations | test_byoc_monitor_suggest_baseline_and_create_monitoring_schedule_with_customizations | 1,532 | 1,747 | 1,532 | 1,538 | f7d756ef76edcaa384c93ba2d42d641139a8ff36 | bigcode/the-stack | train |
46cf633b9fb18535e41ba182 | train | function | @pytest.fixture(scope="module")
def default_monitoring_schedule_name(sagemaker_session, output_kms_key, volume_kms_key, predictor):
my_default_monitor = DefaultModelMonitor(
role=ROLE,
instance_count=INSTANCE_COUNT,
instance_type=INSTANCE_TYPE,
volume_size_in_gb=VOLUME_SIZE_IN_GB,
... | @pytest.fixture(scope="module")
def default_monitoring_schedule_name(sagemaker_session, output_kms_key, volume_kms_key, predictor):
| my_default_monitor = DefaultModelMonitor(
role=ROLE,
instance_count=INSTANCE_COUNT,
instance_type=INSTANCE_TYPE,
volume_size_in_gb=VOLUME_SIZE_IN_GB,
volume_kms_key=volume_kms_key,
output_kms_key=output_kms_key,
max_runtime_in_seconds=MAX_RUNTIME_IN_SECONDS,
... | ):
model = TensorFlowModel(
model_data=model_data,
role=ROLE,
framework_version=tensorflow_inference_latest_version,
sagemaker_session=sagemaker_session,
)
predictor = model.deploy(
INSTANCE_COUNT,
INSTANCE_TYPE,
... | 118 | 118 | 396 | 29 | 88 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | default_monitoring_schedule_name | default_monitoring_schedule_name | 115 | 163 | 115 | 116 | 9ad609de95a0b4883989544c99fc586ce9444905 | bigcode/the-stack | train |
974360a939f129339414afa6 | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_default_monitor_create_and_update_schedule_config_without_customizations(
sagemaker_session, predictor
):
my_default_monitor = DefaultModel... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_default_monitor_create_and_update_schedule_config_without_customizations(
sagemaker_session, predictor
):
| my_default_monitor = DefaultModelMonitor(role=ROLE, sagemaker_session=sagemaker_session)
my_default_monitor.create_monitoring_schedule(
endpoint_input=predictor.endpoint_name,
schedule_cron_expression=CronExpressionGenerator.daily(),
)
schedule_description = my_default_monitor.describe... | _description["MonitoringScheduleConfig"]["MonitoringJobDefinition"][
"StoppingCondition"
]["MaxRuntimeInSeconds"]
== UPDATED_MAX_RUNTIME_IN_SECONDS
)
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"]["Environment"][
UPDATED_ENV_K... | 256 | 256 | 1,354 | 60 | 195 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_default_monitor_create_and_update_schedule_config_without_customizations | test_default_monitor_create_and_update_schedule_config_without_customizations | 1,106 | 1,328 | 1,106 | 1,112 | a13fa947b14064eb5cfc4843f13c5f64136198cd | bigcode/the-stack | train |
b20d0e0f72ecc46aa14e18ff | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_byoc_monitor_create_and_update_schedule_config_with_customizations(
sagemaker_session,
predictor,
volume_kms_key,
output_kms_key,
... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_byoc_monitor_create_and_update_schedule_config_with_customizations(
sagemaker_session,
predictor,
volume_kms_key,
output_kms_key,
... | byoc_env = ENVIRONMENT.copy()
byoc_env["dataset_format"] = json.dumps(DatasetFormat.csv(header=False))
byoc_env["dataset_source"] = "/opt/ml/processing/input/baseline_dataset_input"
byoc_env["output_path"] = os.path.join("/opt/ml/processing/output")
byoc_env["publish_cloudwatch_metrics"] = "Disabled... | )
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"]["Environment"][
ENV_KEY_1
]
== ENV_VALUE_1
)
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"]["Environment"][
"publish_cloudw... | 256 | 256 | 1,943 | 88 | 167 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_byoc_monitor_create_and_update_schedule_config_with_customizations | test_byoc_monitor_create_and_update_schedule_config_with_customizations | 1,944 | 2,226 | 1,944 | 1,955 | 73955b40c8081d987b5a51cf6c86d60ce34ec007 | bigcode/the-stack | train |
2a9870a5504e3436d744f06d | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_default_monitor_suggest_baseline_and_create_monitoring_schedule_without_customizations(
sagemaker_session, predictor
):
baseline_dataset = ... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_default_monitor_suggest_baseline_and_create_monitoring_schedule_without_customizations(
sagemaker_session, predictor
):
| baseline_dataset = os.path.join(DATA_DIR, "monitor/baseline_dataset.csv")
my_default_monitor = DefaultModelMonitor(role=ROLE, sagemaker_session=sagemaker_session)
my_default_monitor.suggest_baseline(
baseline_dataset=baseline_dataset,
dataset_format=DatasetFormat.csv(header=False),
... | Config"
]["ConstraintsResource"]["S3Uri"]
is not None
)
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"][
"StoppingCondition"
]["MaxRuntimeInSeconds"]
== MAX_RUNTIME_IN_SECONDS
)
assert (
schedule_description... | 256 | 256 | 1,280 | 64 | 191 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_default_monitor_suggest_baseline_and_create_monitoring_schedule_without_customizations | test_default_monitor_suggest_baseline_and_create_monitoring_schedule_without_customizations | 476 | 651 | 476 | 482 | 1ce6241b6f6effdb8ae5458c78ca27be855e5ecc | bigcode/the-stack | train |
f0ee462ceeb26f50d531f769 | train | function | def _wait_for_schedule_changes_to_apply(monitor):
"""Waits for the monitor to no longer be in the 'Pending' state. Updates take under a minute
to apply.
Args:
monitor (sagemaker.model_monitor.ModelMonitor): The monitor to watch.
"""
for _ in retries(
max_retry_count=100,
ex... | def _wait_for_schedule_changes_to_apply(monitor):
| """Waits for the monitor to no longer be in the 'Pending' state. Updates take under a minute
to apply.
Args:
monitor (sagemaker.model_monitor.ModelMonitor): The monitor to watch.
"""
for _ in retries(
max_retry_count=100,
exception_message_prefix="Waiting for schedule to le... | agemaker_session=sagemaker_session
)
constraint_violations = my_attached_monitor.latest_monitoring_constraint_violations()
assert constraint_violations.body_dict["violations"][0]["feature_name"] == "store_and_fwd_flag"
def _wait_for_schedule_changes_to_apply(monitor):
| 64 | 64 | 121 | 11 | 53 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | _wait_for_schedule_changes_to_apply | _wait_for_schedule_changes_to_apply | 2,496 | 2,511 | 2,496 | 2,496 | adaf75a82845d94f5e8a6599ca67b4ce1a5bfc0c | bigcode/the-stack | train |
bd76609058868cf2a00eaeeb | train | function | @pytest.fixture(scope="module")
def output_kms_key(sagemaker_session):
role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-output-kms-key-{}".format(
sagemaker_sessio... | @pytest.fixture(scope="module")
def output_kms_key(sagemaker_session):
| role_arn = sagemaker_session.expand_role(ROLE)
return get_or_create_kms_key(
sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-output-kms-key-{}".format(
sagemaker_session.boto_session.region_name
),
)
| sagemaker_session=sagemaker_session,
role_arn=role_arn,
alias="integ-test-processing-volume-kms-key-{}".format(
sagemaker_session.boto_session.region_name
),
)
@pytest.fixture(scope="module")
def output_kms_key(sagemaker_session):
| 64 | 64 | 88 | 16 | 48 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | output_kms_key | output_kms_key | 237 | 246 | 237 | 238 | 817cc84e83d6032063f83c6c6096503df8939f93 | bigcode/the-stack | train |
04c894e458b15c496a12e3fe | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_default_monitor_create_stop_and_start_monitoring_schedule_with_customizations(
sagemaker_session, output_kms_key, volume_kms_key, predictor
):
... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
def test_default_monitor_create_stop_and_start_monitoring_schedule_with_customizations(
sagemaker_session, output_kms_key, volume_kms_key, predictor
):
... | my_default_monitor = DefaultModelMonitor(
role=ROLE,
instance_count=INSTANCE_COUNT,
instance_type=INSTANCE_TYPE,
volume_size_in_gb=VOLUME_SIZE_IN_GB,
volume_kms_key=volume_kms_key,
output_kms_key=output_kms_key,
max_runtime_in_seconds=MAX_RUNTIME_IN_SECONDS,
... | (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"].get(
"BaselineConfig"
)
is None
)
assert (
schedule_description["MonitoringScheduleConfig"]["MonitoringJobDefinition"].get(
"BaselineConfig"
)
is None
)
... | 256 | 256 | 1,099 | 72 | 183 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_default_monitor_create_stop_and_start_monitoring_schedule_with_customizations | test_default_monitor_create_stop_and_start_monitoring_schedule_with_customizations | 654 | 817 | 654 | 661 | fdd0a985eace7472bcd2272815a35d44749ef8d3 | bigcode/the-stack | train |
f77582512be6f257f4942037 | train | function | def _upload_captured_data_to_endpoint(sagemaker_session, predictor):
current_hour_date_time = datetime.now()
previous_hour_date_time = datetime.now() - timedelta(hours=1)
current_hour_folder_structure = current_hour_date_time.strftime("%Y/%m/%d/%H")
previous_hour_folder_structure = previous_hour_date_ti... | def _upload_captured_data_to_endpoint(sagemaker_session, predictor):
| current_hour_date_time = datetime.now()
previous_hour_date_time = datetime.now() - timedelta(hours=1)
current_hour_folder_structure = current_hour_date_time.strftime("%Y/%m/%d/%H")
previous_hour_folder_structure = previous_hour_date_time.strftime("%Y/%m/%d/%H")
s3_uri_base = os.path.join(
"s... | it.
if schedule_desc["MonitoringScheduleStatus"] not in ["Pending", "Stopped"]:
monitor.stop_monitoring_schedule()
# End this loop once the execution has reached a terminal state.
if last_execution_status in ["Completed", "CompletedWithViolations", "Failed", "Stopped"]:
... | 79 | 79 | 264 | 15 | 63 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | _upload_captured_data_to_endpoint | _upload_captured_data_to_endpoint | 2,542 | 2,566 | 2,542 | 2,542 | f23b11d8f3d3956037ec5414ae13ea9049d10b2e | bigcode/the-stack | train |
9ab9e4b7309ddea8bfc3ef02 | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.cron
def test_default_monitor_monitoring_execution_interactions(
sagemaker_session, default_monitoring_schedule_name
):
my_attached_mon... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.cron
def test_default_monitor_monitoring_execution_interactions(
sagemaker_session, default_monitoring_schedule_name
):
| my_attached_monitor = DefaultModelMonitor.attach(
monitor_schedule_name=default_monitoring_schedule_name, sagemaker_session=sagemaker_session
)
description = my_attached_monitor.describe_schedule()
assert description["MonitoringScheduleName"] == default_monitoring_schedule_name
executions =... | ]["EnableNetworkIsolation"]
== UPDATED_NETWORK_CONFIG.enable_network_isolation
)
_wait_for_schedule_changes_to_apply(monitor=my_attached_monitor)
my_attached_monitor.stop_monitoring_schedule()
_wait_for_schedule_changes_to_apply(monitor=my_attached_monitor)
@pytest.mark.skipif(
te... | 125 | 125 | 417 | 66 | 59 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_default_monitor_monitoring_execution_interactions | test_default_monitor_monitoring_execution_interactions | 1,488 | 1,529 | 1,488 | 1,495 | 21d33d377f4bdd3caa3a9414ed7e484bccc6c838 | bigcode/the-stack | train |
ed2263f89c195ce79a9ae426 | train | function | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.cron
def test_byoc_monitor_monitoring_execution_interactions(
sagemaker_session, byoc_monitoring_schedule_name
):
my_attached_monitor =... | @pytest.mark.skipif(
tests.integ.test_region() in tests.integ.NO_MODEL_MONITORING_REGIONS,
reason="ModelMonitoring is not yet supported in this region.",
)
@pytest.mark.cron
def test_byoc_monitor_monitoring_execution_interactions(
sagemaker_session, byoc_monitoring_schedule_name
):
| my_attached_monitor = ModelMonitor.attach(
monitor_schedule_name=byoc_monitoring_schedule_name, sagemaker_session=sagemaker_session
)
description = my_attached_monitor.describe_schedule()
assert description["MonitoringScheduleName"] == byoc_monitoring_schedule_name
executions = my_attached_... | ]["EnableNetworkIsolation"]
== UPDATED_NETWORK_CONFIG.enable_network_isolation
)
_wait_for_schedule_changes_to_apply(monitor=my_attached_monitor)
my_attached_monitor.stop_monitoring_schedule()
_wait_for_schedule_changes_to_apply(monitor=my_attached_monitor)
@pytest.mark.skipif(
tests.int... | 126 | 126 | 420 | 68 | 58 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | test_byoc_monitor_monitoring_execution_interactions | test_byoc_monitor_monitoring_execution_interactions | 2,452 | 2,493 | 2,452 | 2,459 | c3ff0240e62795e890def52c3e32ffc1c1963b36 | bigcode/the-stack | train |
216ea0125d1024113c058207 | train | function | @pytest.fixture(scope="module")
def predictor(sagemaker_session, tensorflow_inference_latest_version):
endpoint_name = unique_name_from_base("sagemaker-tensorflow-serving")
model_data = sagemaker_session.upload_data(
path=os.path.join(tests.integ.DATA_DIR, "tensorflow-serving-test-model.tar.gz"),
... | @pytest.fixture(scope="module")
def predictor(sagemaker_session, tensorflow_inference_latest_version):
| endpoint_name = unique_name_from_base("sagemaker-tensorflow-serving")
model_data = sagemaker_session.upload_data(
path=os.path.join(tests.integ.DATA_DIR, "tensorflow-serving-test-model.tar.gz"),
key_prefix="tensorflow-serving/models",
)
with tests.integ.timeout.timeout_and_delete_endpoin... | /jsontype2"]
INTEG_TEST_MONITORING_OUTPUT_BUCKET = "integ-test-monitoring-output-bucket"
FIVE_MIN_CRON_EXPRESSION = "cron(0/5 * ? * * *)"
@pytest.fixture(scope="module")
def predictor(sagemaker_session, tensorflow_inference_latest_version):
| 64 | 64 | 199 | 19 | 45 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | predictor | predictor | 90 | 112 | 90 | 91 | 85dc7d3ec13807690e2cd1bd4fa1024c053c6ef2 | bigcode/the-stack | train |
30cfb04480d3dfe8f8a7ee30 | train | function | @pytest.fixture(scope="module")
def byoc_monitoring_schedule_name(sagemaker_session, output_kms_key, volume_kms_key, predictor):
byoc_env = ENVIRONMENT.copy()
byoc_env["dataset_format"] = json.dumps(DatasetFormat.csv(header=False))
byoc_env["dataset_source"] = "/opt/ml/processing/input/baseline_dataset_inpu... | @pytest.fixture(scope="module")
def byoc_monitoring_schedule_name(sagemaker_session, output_kms_key, volume_kms_key, predictor):
| byoc_env = ENVIRONMENT.copy()
byoc_env["dataset_format"] = json.dumps(DatasetFormat.csv(header=False))
byoc_env["dataset_source"] = "/opt/ml/processing/input/baseline_dataset_input"
byoc_env["output_path"] = os.path.join("/opt/ml/processing/output")
byoc_env["publish_cloudwatch_metrics"] = "Disabled... | output_s3_uri=output_s3_uri,
statistics=statistics,
constraints=constraints,
schedule_cron_expression=FIVE_MIN_CRON_EXPRESSION,
enable_cloudwatch_metrics=ENABLE_CLOUDWATCH_METRICS,
)
_wait_for_schedule_changes_to_apply(monitor=my_default_monitor)
_upload_captured_da... | 151 | 151 | 504 | 30 | 120 | wuchih-amazon/sagemaker-python-sdk | tests/integ/test_model_monitor.py | Python | byoc_monitoring_schedule_name | byoc_monitoring_schedule_name | 166 | 222 | 166 | 167 | 538b17e53978462249c8fd9334935be08e6dc969 | bigcode/the-stack | train |
89ccb25e21002f692d4b4946 | train | function | def get_graph_obj(W, K=10, res = 400):
"""
Return an object corresponding to a nearest neighbor graph
Parameters
----------
W: ndarray(N, N)
The N x N time-ordered similarity matrix
K: int
Number of nearest neighbors to use in graph representation
res: int
Target reso... | def get_graph_obj(W, K=10, res = 400):
| """
Return an object corresponding to a nearest neighbor graph
Parameters
----------
W: ndarray(N, N)
The N x N time-ordered similarity matrix
K: int
Number of nearest neighbors to use in graph representation
res: int
Target resolution of resized image
"""
fac... | stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
class PrettyFloat(float):
def __repr__(self):
return '%.4g' % self
def pretty_floats(obj):
if isinstance(obj, float):
return PrettyFloat(obj)
elif isinstance(obj, dict):
return dict((k, pretty_floats(v)) for ... | 126 | 126 | 420 | 15 | 110 | ctralie/GraphDitty | SongStructureGUI.py | Python | get_graph_obj | get_graph_obj | 78 | 116 | 78 | 78 | fb508ce9befbdd34bf3101ac8c8683ff7d2ebee0 | bigcode/the-stack | train |
be8d3f2af7fa1c0f35194b3b | train | function | def pretty_floats(obj):
if isinstance(obj, float):
return PrettyFloat(obj)
elif isinstance(obj, dict):
return dict((k, pretty_floats(v)) for k, v in obj.items())
elif isinstance(obj, (list, tuple)):
return map(pretty_floats, obj)
return obj
| def pretty_floats(obj):
| if isinstance(obj, float):
return PrettyFloat(obj)
elif isinstance(obj, dict):
return dict((k, pretty_floats(v)) for k, v in obj.items())
elif isinstance(obj, (list, tuple)):
return map(pretty_floats, obj)
return obj
| .png")
return "data:image/png;base64, " + b
#http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
class PrettyFloat(float):
def __repr__(self):
return '%.4g' % self
def pretty_floats(obj):
| 64 | 64 | 72 | 7 | 56 | ctralie/GraphDitty | SongStructureGUI.py | Python | pretty_floats | pretty_floats | 69 | 76 | 69 | 69 | 5a99d2b716a46a600a417e1ff65101933919cb01 | bigcode/the-stack | train |
92d60dc3dfcc320d6aa89d30 | train | class | class PrettyFloat(float):
def __repr__(self):
return '%.4g' % self
| class PrettyFloat(float):
| def __repr__(self):
return '%.4g' % self
| imsave("temp.png", C)
b = getBase64File("temp.png")
os.remove("temp.png")
return "data:image/png;base64, " + b
#http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
class PrettyFloat(float):
| 64 | 64 | 22 | 5 | 58 | ctralie/GraphDitty | SongStructureGUI.py | Python | PrettyFloat | PrettyFloat | 66 | 68 | 66 | 66 | 6d0ef506a9489326cf9054a3563fcc098c184b30 | bigcode/the-stack | train |
fd53e57c5141a3a3ed7b1028 | train | function | def imresize(D, dims, kind='cubic'):
"""
Resize a floating point image
Parameters
----------
D : ndarray(M1, N1)
Original image
dims : tuple(M2, N2)
The dimensions to which to resize
kind : string
The kind of interpolation to use
Returns
-------
D2 : ndarr... | def imresize(D, dims, kind='cubic'):
| """
Resize a floating point image
Parameters
----------
D : ndarray(M1, N1)
Original image
dims : tuple(M2, N2)
The dimensions to which to resize
kind : string
The kind of interpolation to use
Returns
-------
D2 : ndarray(M2, N2)
A resized array
... | numpy as np
import os
import skimage
import skimage.io
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import json
import base64
from SimilarityFusion import *
from DiffusionMaps import *
from Laplacian import *
import time
def imresize(D, dims, kind='cubic'):
| 69 | 69 | 231 | 12 | 56 | ctralie/GraphDitty | SongStructureGUI.py | Python | imresize | imresize | 16 | 38 | 16 | 16 | a4298ec686b1e2b91cb4027cea934fcf613679d8 | bigcode/the-stack | train |
50af87813fd0798a612da043 | train | function | def getBase64File(filename):
fin = open(filename, "rb")
b = fin.read()
b = base64.b64encode(b)
fin.close()
return b.decode("ASCII")
| def getBase64File(filename):
| fin = open(filename, "rb")
b = fin.read()
b = base64.b64encode(b)
fin.close()
return b.decode("ASCII")
| .float32)/N
y2 = np.array(0.5 + np.arange(M), dtype=np.float32)/M
f = scipy.interpolate.interp2d(x1, y1, D, kind=kind)
return f(x2, y2)
def getBase64File(filename):
| 64 | 64 | 43 | 7 | 57 | ctralie/GraphDitty | SongStructureGUI.py | Python | getBase64File | getBase64File | 40 | 45 | 40 | 40 | 6d1225f4c7ce0199e080bb64ed3805ec993b1a2b | bigcode/the-stack | train |
4f3ae98701b709abe7488c6a | train | function | def saveResultsJSON(filename, times, Ws, neigs, jsonfilename, diffusion_znormalize):
"""
Save a JSON file holding the audio and structure information, which can
be parsed by SongStructureGUI.html. Audio and images are stored as
base64 for simplicity
Parameters
----------
filename: str... | def saveResultsJSON(filename, times, Ws, neigs, jsonfilename, diffusion_znormalize):
| """
Save a JSON file holding the audio and structure information, which can
be parsed by SongStructureGUI.html. Audio and images are stored as
base64 for simplicity
Parameters
----------
filename: string
Path to audio
times: ndarray(N)
A list of times corresponding... | =np.int32))
C = np.array(np.round(C[:, 0:3]*255), dtype=int)
colors = C.tolist()
K = min(int(np.round(K*2.0/fac)), res) # Use slightly more edges
print("res = %i, K = %i"%(res, K))
S = getS(WRes, K).tocoo()
I, J, V = S.row, S.col, S.data
V *= 10
ret = {}
ret["nodes"] = [{"id":"%i"%i... | 211 | 211 | 706 | 22 | 188 | ctralie/GraphDitty | SongStructureGUI.py | Python | saveResultsJSON | saveResultsJSON | 118 | 187 | 118 | 118 | f17fe02ec1346f38a97d7eb1f2bd246df6194c7d | bigcode/the-stack | train |
3b5624c5ae1ceea973796342 | train | function | def getBase64PNGImage(pD, cmapstr, logfloor_quantile = 0):
"""
Get an image as a base64 string
"""
D = np.array(pD)
if logfloor_quantile > 0:
floor = np.quantile(pD.flatten(), logfloor_quantile)
D = np.log(D + floor)
c = plt.get_cmap(cmapstr)
D = D-np.min(D)
D = np.round(... | def getBase64PNGImage(pD, cmapstr, logfloor_quantile = 0):
| """
Get an image as a base64 string
"""
D = np.array(pD)
if logfloor_quantile > 0:
floor = np.quantile(pD.flatten(), logfloor_quantile)
D = np.log(D + floor)
c = plt.get_cmap(cmapstr)
D = D-np.min(D)
D = np.round(255.0*D/np.max(D))
C = c(np.array(D, dtype=np.int32))
... | )
def getBase64File(filename):
fin = open(filename, "rb")
b = fin.read()
b = base64.b64encode(b)
fin.close()
return b.decode("ASCII")
def getBase64PNGImage(pD, cmapstr, logfloor_quantile = 0):
| 64 | 64 | 185 | 20 | 44 | ctralie/GraphDitty | SongStructureGUI.py | Python | getBase64PNGImage | getBase64PNGImage | 47 | 63 | 47 | 47 | 98bcfb4199b2714fd466b3d0f236bbf74c68a77f | bigcode/the-stack | train |
cc5fc85507c91404a29bab9a | train | function | @optimizer
def outer2D(a, b, c, symmetric):
c[0] = a[0]*b[0]
c[1] = a[0]*b[1]
if symmetric:
c[2] = c[1]
else:
c[2] = a[1]*b[0]
c[3] = a[1]*b[1]
| @optimizer
def outer2D(a, b, c, symmetric):
| c[0] = a[0]*b[0]
c[1] = a[0]*b[1]
if symmetric:
c[2] = c[1]
else:
c[2] = a[1]*b[0]
c[3] = a[1]*b[1]
| if av.shape[0] == 2:
outer2D(av, bv, cv, symmetric)
elif av.shape[0] == 3:
outer3D(av, bv, cv, symmetric)
return c
@optimizer
def outer2D(a, b, c, symmetric):
| 64 | 64 | 88 | 15 | 48 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | outer2D | outer2D | 154 | 162 | 154 | 155 | a8fb2fbaba6224d3cee6562582f7eeaa3b405035 | bigcode/the-stack | train |
0c0ffc73ebdb62495fb4be26 | train | class | class CachedArrayDict(MutableMapping):
"""Dictionary for caching Numpy arrays (work arrays)
Example
-------
>>> import numpy as np
>>> from shenfun.utilities import CachedArrayDict
>>> work = CachedArrayDict()
>>> a = np.ones((3, 4), dtype=int)
>>> w = work[(a, 0, True)] # create work ... | class CachedArrayDict(MutableMapping):
| """Dictionary for caching Numpy arrays (work arrays)
Example
-------
>>> import numpy as np
>>> from shenfun.utilities import CachedArrayDict
>>> work = CachedArrayDict()
>>> a = np.ones((3, 4), dtype=int)
>>> w = work[(a, 0, True)] # create work array with shape as a
>>> print(w.s... | w[1::2] = 0
ak = dct(u, 1)
ak /= (N-1)
return np.sqrt(np.sum(ak*w))
assert quad == 'GC'
d = np.zeros(N)
k = 2*(1 + np.arange((N-1)//2))
d[::2] = (2./N)/np.hstack((1., 1.-k*k))
w = dct(d, type=3)
return np.sqrt(np.sum(u*w))
class CachedArrayDict(MutableMapping):
| 122 | 122 | 409 | 8 | 114 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | CachedArrayDict | CachedArrayDict | 78 | 130 | 78 | 78 | 3f07ff8493bae74ffad7a6517e949c0b4ab331b8 | bigcode/the-stack | train |
08dedb1e905c2eb202bc4d2b | train | function | def mayavi_show():
"""
Return show function that updates the mayavi figure in the background.
"""
from pyface.api import GUI
from mayavi import mlab
return mlab.show(GUI().stop_event_loop)
| def mayavi_show():
| """
Return show function that updates the mayavi figure in the background.
"""
from pyface.api import GUI
from mayavi import mlab
return mlab.show(GUI().stop_event_loop)
| (measures).expand()
result = []
if isinstance(ms, sp.Add):
for arg in ms.args:
result.append(_split([arg], defaultdict(lambda: 1)))
else:
result.append(_split([ms], defaultdict(lambda: 1)))
return result
def mayavi_show():
| 64 | 64 | 51 | 5 | 58 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | mayavi_show | mayavi_show | 448 | 454 | 448 | 448 | 3111e5383386a0dea90f35ea0a184e18fcaabb79 | bigcode/the-stack | train |
734a270eef7d28bee831fa2c | train | function | def surf3D(u, mesh=None, backend='plotly', wrapaxes=(), slices=None, fig=None, kind='normal', **kw):
"""Plot surface embedded in 3D
Parameters
----------
u : Function or Array
mesh : list of Cartesian meshes [x, y, z], optional
backend : str, optional
plotly or mayavi
wrapaxes : seq... | def surf3D(u, mesh=None, backend='plotly', wrapaxes=(), slices=None, fig=None, kind='normal', **kw):
| """Plot surface embedded in 3D
Parameters
----------
u : Function or Array
mesh : list of Cartesian meshes [x, y, z], optional
backend : str, optional
plotly or mayavi
wrapaxes : sequence of integers, optional
For domains that wrap around, extend mesh/u by one in given direc... | , (list, tuple)) else [xs]
ys = []
for x in xs:
if 0 in axes:
x = np.vstack([x, x[0]])
if 1 in axes:
x = np.hstack([x, x[:, 0][:, None]])
if 2 in axes:
x = np.concatenate([x, x[:, :, 0][:, :, None]], axis=2)
ys.append(x)
if len(ys) == 1:
... | 148 | 148 | 494 | 31 | 116 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | surf3D | surf3D | 477 | 532 | 477 | 477 | 604e704be0599885867158dca6a76e1c6bc9dd2d | bigcode/the-stack | train |
a7b4b698910461d920467e8a | train | function | def outer(a, b, c):
r"""Return outer product $c_{i,j} = a_i b_j$
Parameters
----------
a : Array of shape (N, ...)
b : Array of shape (N, ...)
c : Array of shape (N*N, ...)
The outer product is taken over the first index of a and b,
for all remaining indices.
"""
av = a.v
b... | def outer(a, b, c):
| r"""Return outer product $c_{i,j} = a_i b_j$
Parameters
----------
a : Array of shape (N, ...)
b : Array of shape (N, ...)
c : Array of shape (N*N, ...)
The outer product is taken over the first index of a and b,
for all remaining indices.
"""
av = a.v
bv = b.v
cv = c.v... | value
def __delitem__(self, key):
del self._data[self.__keytransform__(key)[0]]
def __iter__(self):
return iter(self._data)
def values(self):
raise TypeError('Cached work arrays not iterable')
def outer(a, b, c):
| 64 | 64 | 161 | 8 | 56 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | outer | outer | 132 | 152 | 132 | 132 | 624d20f9b26fa0a0f22ddde6edcede44c2db860f | bigcode/the-stack | train |
4a87680b13d024a7b979b716 | train | function | def dot(u, v, output_array=None, forward_output=True):
"""Return dot product of u and v
Parameters
----------
u : Function or Array
v : Function or Array
output_array : Function or Array
Must be of correct shape
forward_output : bool, optional
Return the result as a Function... | def dot(u, v, output_array=None, forward_output=True):
| """Return dot product of u and v
Parameters
----------
u : Function or Array
v : Function or Array
output_array : Function or Array
Must be of correct shape
forward_output : bool, optional
Return the result as a Function if True, and an Array if
False.
Note
... | ]*b[0]
c[1] = a[0]*b[1]
if symmetric:
c[2] = c[1]
else:
c[2] = a[1]*b[0]
c[3] = a[1]*b[1]
@optimizer
def outer3D(a, b, c, symmetric):
c[0] = a[0]*b[0]
c[1] = a[0]*b[1]
c[2] = a[0]*b[2]
if symmetric:
c[3] = c[1]
c[6] = c[2]
c[7] = c[5]
else:
... | 256 | 256 | 1,249 | 14 | 242 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | dot | dot | 181 | 358 | 181 | 181 | 35c6046714cd861cd5ade06672ecc4b876253c44 | bigcode/the-stack | train |
0b43ad282a0857f948dadf44 | train | function | def clenshaw_curtis1D(u, quad="GC"): # pragma: no cover
"""Clenshaw-Curtis integration in 1D"""
assert u.ndim == 1
N = u.shape[0]
if quad == 'GL':
w = np.arange(0, N, 1, dtype=float)
w[2:] = 2./(1-w[2:]**2)
w[0] = 1
w[1::2] = 0
ak = dct(u, 1)
ak /= (N-1)
... | def clenshaw_curtis1D(u, quad="GC"): # pragma: no cover
| """Clenshaw-Curtis integration in 1D"""
assert u.ndim == 1
N = u.shape[0]
if quad == 'GL':
w = np.arange(0, N, 1, dtype=float)
w[2:] = 2./(1-w[2:]**2)
w[0] = 1
w[1::2] = 0
ak = dct(u, 1)
ak /= (N-1)
return np.sqrt(np.sum(ak*w))
assert quad == ... | )], axis=ax)
sl = [slice(None)]*len(uc.shape)
sl[ax] = np.newaxis
uc[:] = uu[tuple(sl)]
return uc.flat[0]
def clenshaw_curtis1D(u, quad="GC"): # pragma: no cover
| 65 | 65 | 217 | 22 | 43 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | clenshaw_curtis1D | clenshaw_curtis1D | 58 | 76 | 58 | 58 | a0db85736970189c9c9980427810d833e382e8a4 | bigcode/the-stack | train |
d810eb54ae6dc8c048b48d38 | train | function | def quiver3D(u, mesh=None, wrapaxes=(), new_figure=False, slices=None, fig=None, kind='normal', **kw):
"""
Parameters
----------
u : Array
mesh : list of Cartesian meshes [x, y, z], optional
backend : str, optional
plotly or mayavi
wrapaxes : sequence of integers, optional
F... | def quiver3D(u, mesh=None, wrapaxes=(), new_figure=False, slices=None, fig=None, kind='normal', **kw):
| """
Parameters
----------
u : Array
mesh : list of Cartesian meshes [x, y, z], optional
backend : str, optional
plotly or mayavi
wrapaxes : sequence of integers, optional
For domains that wrap around, extend mesh/u by one in given direction
fig : None, optional
I... | igure(s)
d = {'visible': False, 'showgrid': False, 'zeroline': False}
fig.update_layout(scene={'xaxis': d, 'yaxis': d, 'zaxis': d})
elif backend == 'mayavi':
from mayavi import mlab
fig = mlab.figure(bgcolor=(1, 1, 1))
mlab.mesh(x, y, z, scalars=u, colormap='jet')
retur... | 134 | 134 | 449 | 32 | 101 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | quiver3D | quiver3D | 534 | 583 | 534 | 534 | 5c8aae63d4dbc95287c61f7d361a404a8c319ffb | bigcode/the-stack | train |
0d9ed437241bfc8b827def2f | train | function | def wrap_periodic(xs, axes=()):
"""Return arrays wrapped around periodically
xs : array or sequence of arrays
axes : sequence of integers, optional
Extend arrays in xs by one in direction given by wrap
"""
xs = xs if isinstance(xs, (list, tuple)) else [xs]
ys = []
for x in xs:
... | def wrap_periodic(xs, axes=()):
| """Return arrays wrapped around periodically
xs : array or sequence of arrays
axes : sequence of integers, optional
Extend arrays in xs by one in direction given by wrap
"""
xs = xs if isinstance(xs, (list, tuple)) else [xs]
ys = []
for x in xs:
if 0 in axes:
x =... | return result
def mayavi_show():
"""
Return show function that updates the mayavi figure in the background.
"""
from pyface.api import GUI
from mayavi import mlab
return mlab.show(GUI().stop_event_loop)
def wrap_periodic(xs, axes=()):
| 64 | 64 | 174 | 9 | 55 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | wrap_periodic | wrap_periodic | 456 | 475 | 456 | 456 | 04d05becd4354f81eab9b56224943284765bd388 | bigcode/the-stack | train |
46fc7b3b6d0c975f9b3ca954 | train | function | @optimizer
def apply_mask(u_hat, mask):
if mask is not None:
u_hat *= mask
return u_hat
| @optimizer
def apply_mask(u_hat, mask):
| if mask is not None:
u_hat *= mask
return u_hat
| forward_output is True:
if isinstance(output_array, Function):
output_array = uv.forward(output_array)
return output_array
uv_hat = Function(To)
uv_hat = uv.forward(uv_hat)
return uv_hat
return uv
@optimizer
def apply_mask(u_hat, mask):
| 64 | 64 | 29 | 11 | 52 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | apply_mask | apply_mask | 361 | 365 | 361 | 362 | 094c36a80de39498d8b91aab89364b9f1c514b26 | bigcode/the-stack | train |
f117ab30b4d1b0c254b0572a | train | function | def integrate_sympy(f, d):
"""Exact definite integral using sympy
Try to convert expression `f` to a polynomial before integrating.
See sympy issue https://github.com/sympy/sympy/pull/18613 to why this is
needed. Poly().integrate() is much faster than sympy.integrate() when applicable.
Parameters... | def integrate_sympy(f, d):
| """Exact definite integral using sympy
Try to convert expression `f` to a polynomial before integrating.
See sympy issue https://github.com/sympy/sympy/pull/18613 to why this is
needed. Poly().integrate() is much faster than sympy.integrate() when applicable.
Parameters
----------
f : sym... |
uv_hat = Function(To)
uv_hat = uv.forward(uv_hat)
return uv_hat
return uv
@optimizer
def apply_mask(u_hat, mask):
if mask is not None:
u_hat *= mask
return u_hat
def integrate_sympy(f, d):
| 64 | 64 | 178 | 8 | 55 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | integrate_sympy | integrate_sympy | 367 | 386 | 367 | 367 | 9982a7b53db9ec62998432e9daa999576c87259f | bigcode/the-stack | train |
1472af61ad7020cfe9d167ab | train | function | @optimizer
def outer3D(a, b, c, symmetric):
c[0] = a[0]*b[0]
c[1] = a[0]*b[1]
c[2] = a[0]*b[2]
if symmetric:
c[3] = c[1]
c[6] = c[2]
c[7] = c[5]
else:
c[3] = a[1]*b[0]
c[6] = a[2]*b[0]
c[7] = a[2]*b[1]
c[4] = a[1]*b[1]
c[5] = a[1]*b[2]
c[8]... | @optimizer
def outer3D(a, b, c, symmetric):
| c[0] = a[0]*b[0]
c[1] = a[0]*b[1]
c[2] = a[0]*b[2]
if symmetric:
c[3] = c[1]
c[6] = c[2]
c[7] = c[5]
else:
c[3] = a[1]*b[0]
c[6] = a[2]*b[0]
c[7] = a[2]*b[1]
c[4] = a[1]*b[1]
c[5] = a[1]*b[2]
c[8] = a[2]*b[2]
| b[1]
if symmetric:
c[2] = c[1]
else:
c[2] = a[1]*b[0]
c[3] = a[1]*b[1]
@optimizer
def outer3D(a, b, c, symmetric):
| 64 | 64 | 178 | 15 | 49 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | outer3D | outer3D | 164 | 179 | 164 | 165 | d104bf61c297fae79b2ef469f5e6e6dad4ab2401 | bigcode/the-stack | train |
c7d44e5470091e6f2c8af44d | train | function | def oldsplit(measures):
def _split(mss, result):
for ms in mss:
ms = sp.sympify(ms)
if isinstance(ms, sp.Mul):
# Multiplication of two or more terms
result = _split(ms.args, result)
continue
# Something else with only one ... | def oldsplit(measures):
| def _split(mss, result):
for ms in mss:
ms = sp.sympify(ms)
if isinstance(ms, sp.Mul):
# Multiplication of two or more terms
result = _split(ms.args, result)
continue
# Something else with only one symbol
sym = ... | sp.Add) or (isinstance(ms, sp.Mul) and np.all([isinstance(s, sp.Add) for s in ms.args])):
for arg in ms.args:
result.append(_split(arg))
else:
result.append(_split(ms))
return result
def oldsplit(measures):
| 64 | 64 | 209 | 6 | 57 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | oldsplit | oldsplit | 418 | 446 | 418 | 419 | d92fc3d2845da2635a19403784bba2865f116ced | bigcode/the-stack | train |
f94bf5fb4a8fcef2ead17068 | train | function | def split(measures):
def _split(ms):
ms = sp.sympify(ms)
if isinstance(ms, Number):
d = {'coeff': ms}
elif len(ms.free_symbols) == 0:
d = {'coeff': ms.evalf()}
else:
d = sp.separatevars(ms.factor(), dict=True)
if d is None:
rai... | def split(measures):
| def _split(ms):
ms = sp.sympify(ms)
if isinstance(ms, Number):
d = {'coeff': ms}
elif len(ms.free_symbols) == 0:
d = {'coeff': ms.evalf()}
else:
d = sp.separatevars(ms.factor(), dict=True)
if d is None:
raise RuntimeError('Could... |
"""
try:
p = sp.Poly(f, d[0]).integrate()
return p(d[2]) - p(d[1])
except sp.PolynomialError:
#return sp.Integral(f, d).evalf()
return sp.integrate(f, d).evalf()
def split(measures):
| 73 | 73 | 246 | 5 | 68 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | split | split | 388 | 416 | 388 | 389 | ce8a53fc176db3fc606ec64b8a527cb073306f4b | bigcode/the-stack | train |
7a0f998a70b8c620dc23aaab | train | function | def dx(u, weighted=False):
r"""Compute integral of u over domain
.. math::
\int_{\Omega} u dx
Parameters
----------
u : Array
The Array to integrate
Note
----
This function assumes a standard reference domain. If the domain
is not standard, then modify th... | def dx(u, weighted=False):
| r"""Compute integral of u over domain
.. math::
\int_{\Omega} u dx
Parameters
----------
u : Array
The Array to integrate
Note
----
This function assumes a standard reference domain. If the domain
is not standard, then modify the result accordingly.
... | ization import optimizer
__all__ = ['dx', 'clenshaw_curtis1D', 'CachedArrayDict', 'surf3D', 'wrap_periodic',
'outer', 'dot', 'apply_mask', 'integrate_sympy', 'mayavi_show',
'quiver3D']
def dx(u, weighted=False):
| 72 | 72 | 241 | 7 | 65 | spectralDNS/shenfun | shenfun/utilities/__init__.py | Python | dx | dx | 21 | 56 | 21 | 21 | e367a45f910fece5b6b439f62c38b3e7cadfa9fe | bigcode/the-stack | train |
b721c6d84c0a4089e37d9798 | train | function | def _read_extended_ch_info(chs, parent, fid):
ch_infos = dir_tree_find(parent, FIFF.FIFFB_CH_INFO)
if len(ch_infos) == 0:
return
_check_option('length of channel infos', len(ch_infos), [len(chs)])
logger.info(' Reading extended channel information')
# Here we assume that ``remap`` is in ... | def _read_extended_ch_info(chs, parent, fid):
| ch_infos = dir_tree_find(parent, FIFF.FIFFB_CH_INFO)
if len(ch_infos) == 0:
return
_check_option('length of channel infos', len(ch_infos), [len(chs)])
logger.info(' Reading extended channel information')
# Here we assume that ``remap`` is in the same order as the channels
# themselve... | info['acq_stim'] = acq_stim
info['custom_ref_applied'] = custom_ref_applied
info['xplotter_layout'] = xplotter_layout
info['kit_system_id'] = kit_system_id
info._check_consistency()
info._unlocked = False
return info, meas
def _read_extended_ch_info(chs, parent, fid):
| 87 | 87 | 293 | 13 | 73 | twang5/mne-python | mne/io/meas_info.py | Python | _read_extended_ch_info | _read_extended_ch_info | 1,714 | 1,744 | 1,714 | 1,714 | db34b7111572daaf2fbdd01a8a32b2c109a32445 | bigcode/the-stack | train |
b04ebb69cfcc92f87b02299d | train | function | @verbose
def _merge_info(infos, force_update_to_first=False, verbose=None):
"""Merge multiple measurement info dictionaries.
- Fields that are present in only one info object will be used in the
merged info.
- Fields that are present in multiple info objects and are the same
will be used in... | @verbose
def _merge_info(infos, force_update_to_first=False, verbose=None):
| """Merge multiple measurement info dictionaries.
- Fields that are present in only one info object will be used in the
merged info.
- Fields that are present in multiple info objects and are the same
will be used in the merged info.
- Fields that are present in multiple info objects an... | [0], x) for x in values[1:])
if is_qual:
return values[0]
elif key == 'meas_date':
logger.info('Found multiple entries for %s. '
'Setting value to `None`' % key)
return None
else:
raise RuntimeError(msg)
elif _check_isin... | 256 | 256 | 968 | 19 | 237 | twang5/mne-python | mne/io/meas_info.py | Python | _merge_info | _merge_info | 2,160 | 2,261 | 2,160 | 2,161 | 39b54b68506b6c1e7dd85eb798ab3eb674cd18b1 | bigcode/the-stack | train |
e63ab750024d158bf7fb0308 | train | function | def _check_dev_head_t(dev_head_t):
_validate_type(dev_head_t, (Transform, None), "info['dev_head_t']")
if dev_head_t is not None:
dev_head_t = _ensure_trans(dev_head_t, 'meg', 'head')
return dev_head_t
| def _check_dev_head_t(dev_head_t):
| _validate_type(dev_head_t, (Transform, None), "info['dev_head_t']")
if dev_head_t is not None:
dev_head_t = _ensure_trans(dev_head_t, 'meg', 'head')
return dev_head_t
| updated
def _check_bads(bads):
_validate_type(bads, list, 'bads')
return bads
def _check_description(description):
_validate_type(description, (None, str), "info['description']")
return description
def _check_dev_head_t(dev_head_t):
| 64 | 64 | 63 | 10 | 53 | twang5/mne-python | mne/io/meas_info.py | Python | _check_dev_head_t | _check_dev_head_t | 222 | 226 | 222 | 222 | fec03d56b45530c0c79ead370bbec34f84766a09 | bigcode/the-stack | train |
3deffaac08e5686c48557cb2 | train | function | @verbose
def anonymize_info(info, daysback=None, keep_his=False, verbose=None):
"""Anonymize measurement information in place.
.. warning:: If ``info`` is part of an object like
:class:`raw.info <mne.io.Raw>`, you should directly use
the method :meth:`raw.anonymize() <mne.io.R... | @verbose
def anonymize_info(info, daysback=None, keep_his=False, verbose=None):
| """Anonymize measurement information in place.
.. warning:: If ``info`` is part of an object like
:class:`raw.info <mne.io.Raw>`, you should directly use
the method :meth:`raw.anonymize() <mne.io.Raw.anonymize>`
to ensure that all parts of the data are anonymi... | objects.
info_target : mne.Info | list of mne.Info
The Info object(s) you wish to overwrite using info_base. These objects
will be modified in-place.
"""
exclude_keys = ['chs', 'ch_names', 'nchan']
info_target = np.atleast_1d(info_target).ravel()
all_infos = np.hstack([info_base, in... | 256 | 256 | 1,458 | 21 | 234 | twang5/mne-python | mne/io/meas_info.py | Python | anonymize_info | anonymize_info | 2,428 | 2,588 | 2,428 | 2,429 | 64061f541426e684a263a0eb627474ea4dd4068a | bigcode/the-stack | train |
53e6ef7dea0bff8c5e995c34 | train | function | def _write_ch_infos(fid, chs, reset_range, ch_names_mapping):
ch_names_mapping = dict() if ch_names_mapping is None else ch_names_mapping
for k, c in enumerate(chs):
# Scan numbers may have been messed up
c = c.copy()
c['ch_name'] = ch_names_mapping.get(c['ch_name'], c['ch_name'])
... | def _write_ch_infos(fid, chs, reset_range, ch_names_mapping):
| ch_names_mapping = dict() if ch_names_mapping is None else ch_names_mapping
for k, c in enumerate(chs):
# Scan numbers may have been messed up
c = c.copy()
c['ch_name'] = ch_names_mapping.get(c['ch_name'], c['ch_name'])
assert len(c['ch_name']) <= 15
c['scanno'] = k + 1... | ch_names = orig_ch_names.copy()
_unique_channel_names(ch_names, max_length=15, verbose='error')
ch_names_mapping = dict()
if orig_ch_names != ch_names:
ch_names_mapping.update(zip(orig_ch_names, ch_names))
return ch_names_mapping
def _write_ch_infos(fid, chs, reset_range, ch_names_mapping):
| 78 | 78 | 260 | 17 | 60 | twang5/mne-python | mne/io/meas_info.py | Python | _write_ch_infos | _write_ch_infos | 2,701 | 2,723 | 2,701 | 2,701 | d70f5caf24f3ab7e72a3a8612db5bafda2ed124b | bigcode/the-stack | train |
7e289f50d656332f1b49636a | train | class | class MontageMixin(object):
"""Mixin for Montage setting."""
@verbose
def set_montage(self, montage, match_case=True, match_alias=False,
on_missing='raise', verbose=None):
"""Set %(montage_types)s channel positions and digitization points.
Parameters
----------
... | class MontageMixin(object):
| """Mixin for Montage setting."""
@verbose
def set_montage(self, montage, match_case=True, match_alias=False,
on_missing='raise', verbose=None):
"""Set %(montage_types)s channel positions and digitization points.
Parameters
----------
%(montage)s
... | ch_stem + '-%s' % suffix
if ch_name not in ch_names:
break
if ch_name not in ch_names:
ch_names[ch_idx] = ch_name
else:
raise ValueError('Adding a single alphanumeric for a '
... | 86 | 86 | 288 | 5 | 80 | twang5/mne-python | mne/io/meas_info.py | Python | MontageMixin | MontageMixin | 148 | 185 | 148 | 148 | 07afbaa7d55e8003d6bdf09eeb72f06a59dbea29 | bigcode/the-stack | train |
edbe1eb48e3d22aaf2cb5d05 | train | function | def _read_bad_channels(fid, node, ch_names_mapping):
ch_names_mapping = {} if ch_names_mapping is None else ch_names_mapping
nodes = dir_tree_find(node, FIFF.FIFFB_MNE_BAD_CHANNELS)
bads = []
if len(nodes) > 0:
for node in nodes:
tag = find_tag(fid, node, FIFF.FIFF_MNE_CH_NAME_LIST)... | def _read_bad_channels(fid, node, ch_names_mapping):
| ch_names_mapping = {} if ch_names_mapping is None else ch_names_mapping
nodes = dir_tree_find(node, FIFF.FIFFB_MNE_BAD_CHANNELS)
bads = []
if len(nodes) > 0:
for node in nodes:
tag = find_tag(fid, node, FIFF.FIFF_MNE_CH_NAME_LIST)
if tag is not None and tag.data is not N... | node : dict
The node of the FIF tree that contains info on the bad channels.
Returns
-------
bads : list
A list of bad channel's names.
"""
return _read_bad_channels(fid, node)
def _read_bad_channels(fid, node, ch_names_mapping):
| 64 | 64 | 130 | 13 | 51 | twang5/mne-python | mne/io/meas_info.py | Python | _read_bad_channels | _read_bad_channels | 1,219 | 1,230 | 1,219 | 1,219 | 3f8b40bd62dff547538d463075572d327634a7b2 | bigcode/the-stack | train |
f38d10476c12606c2c05c13f | train | function | def _check_description(description):
_validate_type(description, (None, str), "info['description']")
return description
| def _check_description(description):
| _validate_type(description, (None, str), "info['description']")
return description
| missing for {name}[{ci}]: {bad}',)
# As options are added here, test_meas_info.py:test_info_bad should be updated
def _check_bads(bads):
_validate_type(bads, list, 'bads')
return bads
def _check_description(description):
| 64 | 64 | 26 | 6 | 57 | twang5/mne-python | mne/io/meas_info.py | Python | _check_description | _check_description | 217 | 219 | 217 | 217 | 2d464748ba56638d128f36968a42815b87991a11 | bigcode/the-stack | train |
48d6bdc4e5c5b8ed42599463 | train | function | @verbose
def _unique_channel_names(ch_names, max_length=None, verbose=None):
"""Ensure unique channel names."""
suffixes = tuple(string.ascii_lowercase)
if max_length is not None:
ch_names[:] = [name[:max_length] for name in ch_names]
unique_ids = np.unique(ch_names, return_index=True)[1]
if... | @verbose
def _unique_channel_names(ch_names, max_length=None, verbose=None):
| """Ensure unique channel names."""
suffixes = tuple(string.ascii_lowercase)
if max_length is not None:
ch_names[:] = [name[:max_length] for name in ch_names]
unique_ids = np.unique(ch_names, return_index=True)[1]
if len(unique_ids) != len(ch_names):
dups = {ch_names[x]
... | ])
valid_units += ([''.join([prefix, unit]) for prefix in valid_prefix_symbols
for unit in valid_unit_symbols])
# units are also valid without a prefix
valid_units += valid_unit_names
valid_units += valid_unit_symbols
# we also accept "n/a" as a unit, which is the default miss... | 113 | 113 | 377 | 18 | 95 | twang5/mne-python | mne/io/meas_info.py | Python | _unique_channel_names | _unique_channel_names | 110 | 145 | 110 | 111 | 683163b2535a6ae50723065cd43819f9189ae4f7 | bigcode/the-stack | train |
40e2019fe9604020eebdcfd4 | train | function | def _rename_comps(comps, ch_names_mapping):
if not (comps and ch_names_mapping):
return
for comp in comps:
data = comp['data']
for key in ('row_names', 'col_names'):
data[key][:] = _rename_list(data[key], ch_names_mapping)
| def _rename_comps(comps, ch_names_mapping):
| if not (comps and ch_names_mapping):
return
for comp in comps:
data = comp['data']
for key in ('row_names', 'col_names'):
data[key][:] = _rename_list(data[key], ch_names_mapping)
| ch_names_mapping[ch[key]] = data
ch[key] = data
_update_ch_info_named(ch)
# we need to return ch_names_mapping so that we can also rename the
# bad channels
return ch_names_mapping
def _rename_comps(comps, ch_names_mapping):
| 64 | 64 | 67 | 12 | 51 | twang5/mne-python | mne/io/meas_info.py | Python | _rename_comps | _rename_comps | 1,747 | 1,753 | 1,747 | 1,747 | b4f1559e62bb06a2a2cf5f644ac6e1b89e9b3dd1 | bigcode/the-stack | train |
fdcc67606dbc7ac554185dd0 | train | function | def _check_dates(info, prepend_error=''):
"""Check dates before writing as fif files.
It's needed because of the limited integer precision
of the fix standard.
"""
for key in ('file_id', 'meas_id'):
value = info.get(key)
if value is not None:
assert 'msecs' not in value
... | def _check_dates(info, prepend_error=''):
| """Check dates before writing as fif files.
It's needed because of the limited integer precision
of the fix standard.
"""
for key in ('file_id', 'meas_id'):
value = info.get(key)
if value is not None:
assert 'msecs' not in value
for key_2 in ('secs', 'usecs')... | ']
for key in ('row_names', 'col_names'):
data[key][:] = _rename_list(data[key], ch_names_mapping)
def _ensure_meas_date_none_or_dt(meas_date):
if meas_date is None or np.array_equal(meas_date, DATE_NONE):
meas_date = None
elif not isinstance(meas_date, datetime.datetime):
... | 103 | 103 | 346 | 10 | 92 | twang5/mne-python | mne/io/meas_info.py | Python | _check_dates | _check_dates | 1,764 | 1,795 | 1,764 | 1,764 | d9f2615d1a131efc29eda3bc1b0c237192afae27 | bigcode/the-stack | train |
d027a64716e2bf33eae06b6a | train | function | def _ensure_meas_date_none_or_dt(meas_date):
if meas_date is None or np.array_equal(meas_date, DATE_NONE):
meas_date = None
elif not isinstance(meas_date, datetime.datetime):
meas_date = _stamp_to_dt(meas_date)
return meas_date
| def _ensure_meas_date_none_or_dt(meas_date):
| if meas_date is None or np.array_equal(meas_date, DATE_NONE):
meas_date = None
elif not isinstance(meas_date, datetime.datetime):
meas_date = _stamp_to_dt(meas_date)
return meas_date
| comps and ch_names_mapping):
return
for comp in comps:
data = comp['data']
for key in ('row_names', 'col_names'):
data[key][:] = _rename_list(data[key], ch_names_mapping)
def _ensure_meas_date_none_or_dt(meas_date):
| 64 | 64 | 64 | 13 | 51 | twang5/mne-python | mne/io/meas_info.py | Python | _ensure_meas_date_none_or_dt | _ensure_meas_date_none_or_dt | 1,756 | 1,761 | 1,756 | 1,756 | 313e3e8666224dd234b62f360f7eec3fecd56769 | bigcode/the-stack | train |
5bf214df478b74f7d243b6ca | train | function | def _dict_pack(obj, casts):
# pack a list of dict into dict of array
return {key: np.array([o[key] for o in obj]) for key in casts}
| def _dict_pack(obj, casts):
# pack a list of dict into dict of array
| return {key: np.array([o[key] for o in obj]) for key in casts}
| ']['ch_name'], encoding='utf8')
yield
finally:
if orig_dig is not None:
info['dig'] = orig_dig
info['chs'] = orig_chs
def _dict_pack(obj, casts):
# pack a list of dict into dict of array
| 64 | 64 | 41 | 20 | 43 | twang5/mne-python | mne/io/meas_info.py | Python | _dict_pack | _dict_pack | 2,679 | 2,681 | 2,679 | 2,680 | 207e627929171d98863fb254dbfb7d16ab80555b | bigcode/the-stack | train |
7706801bca4c266d540f88ee | train | function | @fill_doc
def write_meas_info(fid, info, data_type=None, reset_range=True):
"""Write measurement info into a file id (from a fif file).
Parameters
----------
fid : file
Open file descriptor.
%(info_not_none)s
data_type : int
The data_type in case it is necessary. Should be 4 (FI... | @fill_doc
def write_meas_info(fid, info, data_type=None, reset_range=True):
| """Write measurement info into a file id (from a fif file).
Parameters
----------
fid : file
Open file descriptor.
%(info_not_none)s
data_type : int
The data_type in case it is necessary. Should be 4 (FIFFT_FLOAT),
5 (FIFFT_DOUBLE), or 16 (FIFFT_DAU_PACK16) for
r... | _2] > np.iinfo('>i4').max):
raise RuntimeError('%sinfo[%s][%s] must be between '
'"%r" and "%r", got "%r"'
% (prepend_error, key, key_2,
np.iinfo('>i4').min,
... | 256 | 256 | 2,956 | 21 | 235 | twang5/mne-python | mne/io/meas_info.py | Python | write_meas_info | write_meas_info | 1,798 | 2,047 | 1,798 | 1,799 | 7a55c227617dbd0ccc9f05dfc93313acc9337e51 | bigcode/the-stack | train |
e451c34705b7c5a76239dc7d | train | function | def _check_bads(bads):
_validate_type(bads, list, 'bads')
return bads
| def _check_bads(bads):
| _validate_type(bads, list, 'bads')
return bads
| .difference(ch_keys))
if bad:
raise KeyError(
f'key{_pl(bad)} missing for {name}[{ci}]: {bad}',)
# As options are added here, test_meas_info.py:test_info_bad should be updated
def _check_bads(bads):
| 64 | 64 | 26 | 8 | 55 | twang5/mne-python | mne/io/meas_info.py | Python | _check_bads | _check_bads | 212 | 214 | 212 | 212 | 277c908ea9633d0254dac5684cf9dfe105be8369 | bigcode/the-stack | train |
32ae1899876030ddc891ba6e | train | function | def _empty_info(sfreq):
"""Create an empty info dictionary."""
_none_keys = (
'acq_pars', 'acq_stim', 'ctf_head_t', 'description',
'dev_ctf_t', 'dig', 'experimenter', 'utc_offset', 'device_info',
'file_id', 'highpass', 'hpi_subsystem', 'kit_system_id', 'helium_info',
'line_freq',... | def _empty_info(sfreq):
| """Create an empty info dictionary."""
_none_keys = (
'acq_pars', 'acq_stim', 'ctf_head_t', 'description',
'dev_ctf_t', 'dig', 'experimenter', 'utc_offset', 'device_info',
'file_id', 'highpass', 'hpi_subsystem', 'kit_system_id', 'helium_info',
'line_freq', 'lowpass', 'meas_date',... | _meas', 'hpi_results', 'helium_info',
'hpi_subsystem', 'kit_system_id', 'line_freq', 'lowpass', 'meas_date',
'meas_id', 'nchan', 'proj_id', 'proj_name', 'projs', 'sfreq',
'subject_info', 'xplotter_layout', 'proc_history', 'gantry_angle',
)
def _empty_info(sfreq):
| 92 | 92 | 309 | 7 | 85 | twang5/mne-python | mne/io/meas_info.py | Python | _empty_info | _empty_info | 2,364 | 2,388 | 2,364 | 2,364 | 9ec9f789d2ea110f37233440a27ec59a3463da00 | bigcode/the-stack | train |
c82162ea98016c1b276232ea | train | function | @fill_doc
def write_info(fname, info, data_type=None, reset_range=True):
"""Write measurement info in fif file.
Parameters
----------
fname : str
The name of the file. Should end by -info.fif.
%(info_not_none)s
data_type : int
The data_type in case it is necessary. Should be 4 (... | @fill_doc
def write_info(fname, info, data_type=None, reset_range=True):
| """Write measurement info in fif file.
Parameters
----------
fname : str
The name of the file. Should end by -info.fif.
%(info_not_none)s
data_type : int
The data_type in case it is necessary. Should be 4 (FIFFT_FLOAT),
5 (FIFFT_DOUBLE), or 16 (FIFFT_DAU_PACK16) for
... | FF.FIFF_MNE_KIT_SYSTEM_ID, info['kit_system_id'])
end_block(fid, FIFF.FIFFB_MEAS_INFO)
# Processing history
_write_proc_history(fid, info)
@fill_doc
def write_info(fname, info, data_type=None, reset_range=True):
| 64 | 64 | 188 | 19 | 45 | twang5/mne-python | mne/io/meas_info.py | Python | write_info | write_info | 2,050 | 2,069 | 2,050 | 2,051 | 1508515830faedfeb291593b2eea1319618eed1c | bigcode/the-stack | train |
cefcff48bb5d4167c43742fe | train | function | def _dict_unpack(obj, casts):
# unpack a dict of array into a list of dict
n = len(obj[list(casts)[0]])
return [{key: cast(obj[key][ii]) for key, cast in casts.items()}
for ii in range(n)]
| def _dict_unpack(obj, casts):
# unpack a dict of array into a list of dict
| n = len(obj[list(casts)[0]])
return [{key: cast(obj[key][ii]) for key, cast in casts.items()}
for ii in range(n)]
| s
def _dict_pack(obj, casts):
# pack a list of dict into dict of array
return {key: np.array([o[key] for o in obj]) for key in casts}
def _dict_unpack(obj, casts):
# unpack a dict of array into a list of dict
| 64 | 64 | 58 | 21 | 43 | twang5/mne-python | mne/io/meas_info.py | Python | _dict_unpack | _dict_unpack | 2,684 | 2,688 | 2,684 | 2,685 | 8b8617aaa249c6e32cacc2ab5fa19c55dcf87f29 | bigcode/the-stack | train |
0a5979f7e6011c598b0dfcab | train | function | def _check_subject_info(subject_info):
_validate_type(subject_info, (None, dict), 'subject_info')
return subject_info
| def _check_subject_info(subject_info):
| _validate_type(subject_info, (None, dict), 'subject_info')
return subject_info
| experimenter')
return experimenter
def _check_line_freq(line_freq):
_validate_type(line_freq, (None, 'numeric'), 'line_freq')
line_freq = float(line_freq) if line_freq is not None else line_freq
return line_freq
def _check_subject_info(subject_info):
| 64 | 64 | 29 | 8 | 55 | twang5/mne-python | mne/io/meas_info.py | Python | _check_subject_info | _check_subject_info | 240 | 242 | 240 | 240 | f8e4f3e497dd963bc66c136fadf86ae18d13c2bb | bigcode/the-stack | train |
6a3340bf155925c50e020e6b | train | function | def read_bad_channels(fid, node):
"""Read bad channels.
Parameters
----------
fid : file
The file descriptor.
node : dict
The node of the FIF tree that contains info on the bad channels.
Returns
-------
bads : list
A list of bad channel's names.
"""
retu... | def read_bad_channels(fid, node):
| """Read bad channels.
Parameters
----------
fid : file
The file descriptor.
node : dict
The node of the FIF tree that contains info on the bad channels.
Returns
-------
bads : list
A list of bad channel's names.
"""
return _read_bad_channels(fid, node)
| name.
%(verbose)s
Returns
-------
%(info_not_none)s
"""
f, tree, _ = fiff_open(fname)
with f as fid:
info = read_meas_info(fid, tree)[0]
return info
def read_bad_channels(fid, node):
| 64 | 64 | 81 | 8 | 55 | twang5/mne-python | mne/io/meas_info.py | Python | read_bad_channels | read_bad_channels | 1,201 | 1,216 | 1,201 | 1,201 | 638f36a9a48d3c24ed1424f03c52c808a07fdfc9 | bigcode/the-stack | train |
84486ec36cc2a74cc63586c9 | train | function | @fill_doc
def _bad_chans_comp(info, ch_names):
"""Check if channel names are consistent with current compensation status.
Parameters
----------
%(info_not_none)s
ch_names : list of str
The channel names to check.
Returns
-------
status : bool
True if compensation is *c... | @fill_doc
def _bad_chans_comp(info, ch_names):
| """Check if channel names are consistent with current compensation status.
Parameters
----------
%(info_not_none)s
ch_names : list of str
The channel names to check.
Returns
-------
status : bool
True if compensation is *currently* in use but some compensation
... | inconsistent info object. '
'Underlying Error:\n')
info._check_consistency(prepend_error=err_mesg)
err_mesg = ('anonymize_info generated an inconsistent info object. '
'daysback parameter was too large. '
'Underlying Error:\n')
_check_dates(info, prepend_erro... | 92 | 92 | 307 | 15 | 76 | twang5/mne-python | mne/io/meas_info.py | Python | _bad_chans_comp | _bad_chans_comp | 2,591 | 2,634 | 2,591 | 2,592 | 1da492a8a116aa22297647e275b74b5741379fd1 | bigcode/the-stack | train |
63c26db3f0a695ebe68e1941 | train | function | def _check_helium_info(helium_info):
_validate_type(helium_info, (None, dict, ), 'helium_info')
return helium_info
| def _check_helium_info(helium_info):
| _validate_type(helium_info, (None, dict, ), 'helium_info')
return helium_info
| ):
_validate_type(subject_info, (None, dict), 'subject_info')
return subject_info
def _check_device_info(device_info):
_validate_type(device_info, (None, dict, ), 'device_info')
return device_info
def _check_helium_info(helium_info):
| 64 | 64 | 37 | 12 | 51 | twang5/mne-python | mne/io/meas_info.py | Python | _check_helium_info | _check_helium_info | 250 | 252 | 250 | 250 | 8f19de721f987ee0ef82413ffbed4c36813133b5 | bigcode/the-stack | train |
7092f90d741a77e46b063068 | train | class | class Info(dict, MontageMixin):
"""Measurement information.
This data structure behaves like a dictionary. It contains all metadata
that is available for a recording. However, its keys are restricted to
those provided by the
`FIF format specification <https://github.com/mne-tools/fiff-constants>`__... | class Info(dict, MontageMixin):
| """Measurement information.
This data structure behaves like a dictionary. It contains all metadata
that is available for a recording. However, its keys are restricted to
those provided by the
`FIF format specification <https://github.com/mne-tools/fiff-constants>`__,
so new entries should not ... | ), "info['description']")
return description
def _check_dev_head_t(dev_head_t):
_validate_type(dev_head_t, (Transform, None), "info['dev_head_t']")
if dev_head_t is not None:
dev_head_t = _ensure_trans(dev_head_t, 'meg', 'head')
return dev_head_t
def _check_experimenter(experimenter):
_v... | 256 | 256 | 7,599 | 7 | 248 | twang5/mne-python | mne/io/meas_info.py | Python | Info | Info | 255 | 1,101 | 255 | 255 | c8366aa053ecea2ca950fe72614147a9259d8ee6 | bigcode/the-stack | train |
f1630184335c58722e79bbce | train | function | @verbose
def read_meas_info(fid, tree, clean_bads=False, verbose=None):
"""Read the measurement info.
Parameters
----------
fid : file
Open file descriptor.
tree : tree
FIF tree structure.
clean_bads : bool
If True, clean info['bads'] before running consistency check.
... | @verbose
def read_meas_info(fid, tree, clean_bads=False, verbose=None):
| """Read the measurement info.
Parameters
----------
fid : file
Open file descriptor.
tree : tree
FIF tree structure.
clean_bads : bool
If True, clean info['bads'] before running consistency check.
Should only be needed for old files where we did not check bads
... | (fname)
with f as fid:
info = read_meas_info(fid, tree)[0]
return info
def read_bad_channels(fid, node):
"""Read bad channels.
Parameters
----------
fid : file
The file descriptor.
node : dict
The node of the FIF tree that contains info on the bad channels.
Re... | 256 | 256 | 4,854 | 20 | 235 | twang5/mne-python | mne/io/meas_info.py | Python | read_meas_info | read_meas_info | 1,233 | 1,711 | 1,233 | 1,234 | 0a1f38161de6c3ebc5392c49eb91113d52ebc9c0 | bigcode/the-stack | train |
d329be974412359ffde47d77 | train | function | def _check_device_info(device_info):
_validate_type(device_info, (None, dict, ), 'device_info')
return device_info
| def _check_device_info(device_info):
| _validate_type(device_info, (None, dict, ), 'device_info')
return device_info
| 'line_freq')
line_freq = float(line_freq) if line_freq is not None else line_freq
return line_freq
def _check_subject_info(subject_info):
_validate_type(subject_info, (None, dict), 'subject_info')
return subject_info
def _check_device_info(device_info):
| 64 | 64 | 30 | 8 | 55 | twang5/mne-python | mne/io/meas_info.py | Python | _check_device_info | _check_device_info | 245 | 247 | 245 | 245 | 5da600e4e1e6bfa368150f6ef1858d349351230d | bigcode/the-stack | train |
ce3044300dfe22a3e43947bc | train | function | def _check_line_freq(line_freq):
_validate_type(line_freq, (None, 'numeric'), 'line_freq')
line_freq = float(line_freq) if line_freq is not None else line_freq
return line_freq
| def _check_line_freq(line_freq):
| _validate_type(line_freq, (None, 'numeric'), 'line_freq')
line_freq = float(line_freq) if line_freq is not None else line_freq
return line_freq
| dev_head_t = _ensure_trans(dev_head_t, 'meg', 'head')
return dev_head_t
def _check_experimenter(experimenter):
_validate_type(experimenter, (None, str), 'experimenter')
return experimenter
def _check_line_freq(line_freq):
| 64 | 64 | 48 | 8 | 55 | twang5/mne-python | mne/io/meas_info.py | Python | _check_line_freq | _check_line_freq | 234 | 237 | 234 | 234 | 61c53c6e3c4de615d91dabb79fc62345a1c3f878 | bigcode/the-stack | train |
4ae544f1d563d30c89a1cf09 | train | function | def _check_experimenter(experimenter):
_validate_type(experimenter, (None, str), 'experimenter')
return experimenter
| def _check_experimenter(experimenter):
| _validate_type(experimenter, (None, str), 'experimenter')
return experimenter
| ):
_validate_type(dev_head_t, (Transform, None), "info['dev_head_t']")
if dev_head_t is not None:
dev_head_t = _ensure_trans(dev_head_t, 'meg', 'head')
return dev_head_t
def _check_experimenter(experimenter):
| 64 | 64 | 32 | 10 | 53 | twang5/mne-python | mne/io/meas_info.py | Python | _check_experimenter | _check_experimenter | 229 | 231 | 229 | 229 | 924029a38e603602411655e6e3521080e48e610f | bigcode/the-stack | train |
eabd34cd3f6d7534acff7456 | train | function | def _format_trans(obj, key):
try:
t = obj[key]
except KeyError:
pass
else:
if t is not None:
obj[key] = Transform(t['from'], t['to'], t['trans'])
| def _format_trans(obj, key):
| try:
t = obj[key]
except KeyError:
pass
else:
if t is not None:
obj[key] = Transform(t['from'], t['to'], t['trans'])
| 07d3df
from ..channels.montage import _set_montage
info = self if isinstance(self, Info) else self.info
_set_montage(info, montage, match_case, match_alias, on_missing)
return self
def _format_trans(obj, key):
| 64 | 64 | 53 | 8 | 55 | twang5/mne-python | mne/io/meas_info.py | Python | _format_trans | _format_trans | 188 | 195 | 188 | 188 | 4fbd8e73ba3f64de83bd04f416be2a23dc727dc4 | bigcode/the-stack | train |
1197ccaac62e682e63507b97 | train | function | def _ensure_infos_match(info1, info2, name, *, on_mismatch='raise'):
"""Check if infos match.
Parameters
----------
info1, info2 : instance of Info
The infos to compare.
name : str
The name of the object appearing in the error message of the comparison
fails.
on_mismatch... | def _ensure_infos_match(info1, info2, name, *, on_mismatch='raise'):
| """Check if infos match.
Parameters
----------
info1, info2 : instance of Info
The infos to compare.
name : str
The name of the object appearing in the error message of the comparison
fails.
on_mismatch : 'raise' | 'warn' | 'ignore'
What to do in case of a mismat... |
# for float/double, the "range" param is unnecessary
if reset_range:
c['range'] = 1.0
write_ch_info(fid, c)
# only write new-style channel information if necessary
if len(ch_names_mapping):
logger.info(
' Writing channel names to FIF truncated to 15 ch... | 174 | 174 | 581 | 20 | 154 | twang5/mne-python | mne/io/meas_info.py | Python | _ensure_infos_match | _ensure_infos_match | 2,726 | 2,771 | 2,726 | 2,726 | f3096f5a4cc024e99e5c54fdcefa02f0e8b6c3ef | bigcode/the-stack | train |
b6e168f93076e27dbbc7f716 | train | function | def _check_ch_keys(ch, ci, name='info["chs"]', check_min=True):
ch_keys = set(ch)
bad = sorted(ch_keys.difference(_ALL_CH_KEYS_SET))
if bad:
raise KeyError(
f'key{_pl(bad)} errantly present for {name}[{ci}]: {bad}')
if check_min:
bad = sorted(_MIN_CH_KEYS_SET.difference(ch_ke... | def _check_ch_keys(ch, ci, name='info["chs"]', check_min=True):
| ch_keys = set(ch)
bad = sorted(ch_keys.difference(_ALL_CH_KEYS_SET))
if bad:
raise KeyError(
f'key{_pl(bad)} errantly present for {name}[{ci}]: {bad}')
if check_min:
bad = sorted(_MIN_CH_KEYS_SET.difference(ch_keys))
if bad:
raise KeyError(
... | :
t = obj[key]
except KeyError:
pass
else:
if t is not None:
obj[key] = Transform(t['from'], t['to'], t['trans'])
def _check_ch_keys(ch, ci, name='info["chs"]', check_min=True):
| 63 | 64 | 125 | 20 | 43 | twang5/mne-python | mne/io/meas_info.py | Python | _check_ch_keys | _check_ch_keys | 198 | 208 | 198 | 198 | a9a7c2cb3d7937806a0fcb2b178b7942e3e24d68 | bigcode/the-stack | train |
f513ae76a2e8ea9580369522 | train | function | @verbose
def create_info(ch_names, sfreq, ch_types='misc', verbose=None):
"""Create a basic Info instance suitable for use with create_raw.
Parameters
----------
ch_names : list of str | int
Channel names. If an int, a list of channel names will be created
from ``range(ch_names)``.
... | @verbose
def create_info(ch_names, sfreq, ch_types='misc', verbose=None):
| """Create a basic Info instance suitable for use with create_raw.
Parameters
----------
ch_names : list of str | int
Channel names. If an int, a list of channel names will be created
from ``range(ch_names)``.
sfreq : float
Sample rate of the data.
ch_types : list of str ... | [0]
elif all(object_diff(values[0], v) == '' for v in values[1:]):
info[k] = values[0]
else:
msg = ("Measurement infos are inconsistent for %s" % k)
raise ValueError(msg)
# other fields
other_fields = ['acq_pars', 'acq_stim', 'bads',
'comp... | 256 | 256 | 925 | 20 | 235 | twang5/mne-python | mne/io/meas_info.py | Python | create_info | create_info | 2,264 | 2,350 | 2,264 | 2,265 | a9189e1adf81c27c536cde0920adade7bc9ce174 | bigcode/the-stack | train |
da8f8bf7480088bdad9fcb2c | train | function | def _add_timedelta_to_stamp(meas_date_stamp, delta_t):
"""Add a timedelta to a meas_date tuple."""
if meas_date_stamp is not None:
meas_date_stamp = _dt_to_stamp(_stamp_to_dt(meas_date_stamp) + delta_t)
return meas_date_stamp
| def _add_timedelta_to_stamp(meas_date_stamp, delta_t):
| """Add a timedelta to a meas_date tuple."""
if meas_date_stamp is not None:
meas_date_stamp = _dt_to_stamp(_stamp_to_dt(meas_date_stamp) + delta_t)
return meas_date_stamp
| type(ii))
for key, val in info_base.items():
if key in exclude_keys:
continue
for i_targ in info_target:
with i_targ._unlock():
i_targ[key] = val
def _add_timedelta_to_stamp(meas_date_stamp, delta_t):
| 64 | 64 | 63 | 15 | 48 | twang5/mne-python | mne/io/meas_info.py | Python | _add_timedelta_to_stamp | _add_timedelta_to_stamp | 2,421 | 2,425 | 2,421 | 2,421 | 3cc315326c2bbdd7377896900547c739fd8bcac3 | bigcode/the-stack | train |
f6d4de8e92fd6c65fce7967f | train | function | def _force_update_info(info_base, info_target):
"""Update target info objects with values from info base.
Note that values in info_target will be overwritten by those in info_base.
This will overwrite all fields except for: 'chs', 'ch_names', 'nchan'.
Parameters
----------
info_base : mne.Info... | def _force_update_info(info_base, info_target):
| """Update target info objects with values from info base.
Note that values in info_target will be overwritten by those in info_base.
This will overwrite all fields except for: 'chs', 'ch_names', 'nchan'.
Parameters
----------
info_base : mne.Info
The Info object you want to use for ove... | '] = 0.
info['sfreq'] = float(sfreq)
info['lowpass'] = info['sfreq'] / 2.
info['dev_head_t'] = Transform('meg', 'head')
info._update_redundant()
info._check_consistency()
return info
def _force_update_info(info_base, info_target):
| 78 | 78 | 261 | 11 | 66 | twang5/mne-python | mne/io/meas_info.py | Python | _force_update_info | _force_update_info | 2,391 | 2,418 | 2,391 | 2,391 | 6e99577101ef0b3e6770e4f6a74cbe758e4ae1fe | bigcode/the-stack | train |
e0b4bda034e56c7a9c4b2daa | train | function | def _simplify_info(info):
"""Return a simplified info structure to speed up picking."""
chs = [{key: ch[key]
for key in ('ch_name', 'kind', 'unit', 'coil_type', 'loc', 'cal')}
for ch in info['chs']]
sub_info = Info(chs=chs, bads=info['bads'], comps=info['comps'],
p... | def _simplify_info(info):
| """Return a simplified info structure to speed up picking."""
chs = [{key: ch[key]
for key in ('ch_name', 'kind', 'unit', 'coil_type', 'loc', 'cal')}
for ch in info['chs']]
sub_info = Info(chs=chs, bads=info['bads'], comps=info['comps'],
projs=info['projs'],
... | html += info_template.substitute(
caption=caption, info=self, meas_date=meas_date, ecg=ecg,
eog=eog, good_channels=good_channels, bad_channels=bad_channels,
projs=projs)
return html
def _simplify_info(info):
| 64 | 64 | 123 | 7 | 56 | twang5/mne-python | mne/io/meas_info.py | Python | _simplify_info | _simplify_info | 1,104 | 1,113 | 1,104 | 1,104 | 20dafe55495d0c24dbb00dbb980a8ae0e2e43fbe | bigcode/the-stack | train |
277da58dc901149845358fab | train | function | def _get_valid_units():
"""Get valid units according to the International System of Units (SI).
The International System of Units (SI, :footcite:`WikipediaSI`) is the
default system for describing units in the Brain Imaging Data Structure
(BIDS). For more information, see the BIDS specification
:fo... | def _get_valid_units():
| """Get valid units according to the International System of Units (SI).
The International System of Units (SI, :footcite:`WikipediaSI`) is the
default system for describing units in the Brain Imaging Data Structure
(BIDS). For more information, see the BIDS specification
:footcite:`BIDSdocs` and th... | pl, _is_numeric, deprecated,
_check_option, _on_missing, _check_on_missing, fill_doc)
from ._digitization import (_format_dig_points, _dig_kind_proper, DigPoint,
_dig_kind_rev, _dig_kind_ints, _read_dig_fif)
from ._digitization import write_dig
from .compensator import g... | 207 | 208 | 695 | 6 | 201 | twang5/mne-python | mne/io/meas_info.py | Python | _get_valid_units | _get_valid_units | 57 | 107 | 57 | 57 | 55efabd6eb7fc2973841d04262e7ccfd509179dc | bigcode/the-stack | train |
08dd5f5e6babbff3afe2a91d | train | function | @verbose
def read_fiducials(fname, verbose=None):
"""Read fiducials from a fiff file.
Parameters
----------
fname : str
The filename to read.
%(verbose)s
Returns
-------
pts : list of dicts
List of digitizer points (each point in a dict).
coord_frame : int
T... | @verbose
def read_fiducials(fname, verbose=None):
| """Read fiducials from a fiff file.
Parameters
----------
fname : str
The filename to read.
%(verbose)s
Returns
-------
pts : list of dicts
List of digitizer points (each point in a dict).
coord_frame : int
The coordinate frame of the points (one of
... | 'coil_type', 'loc', 'cal')}
for ch in info['chs']]
sub_info = Info(chs=chs, bads=info['bads'], comps=info['comps'],
projs=info['projs'],
custom_ref_applied=info['custom_ref_applied'])
sub_info._update_redundant()
return sub_info
@verbose
def read_fiducials... | 94 | 94 | 315 | 14 | 79 | twang5/mne-python | mne/io/meas_info.py | Python | read_fiducials | read_fiducials | 1,116 | 1,155 | 1,116 | 1,117 | 8f412a561b79b3e9520fc656ae02a73017b5e644 | bigcode/the-stack | train |
e327f1dec17900c3a1797072 | train | function | @verbose
def _merge_info_values(infos, key, verbose=None):
"""Merge things together.
Fork for {'dict', 'list', 'array', 'other'}
and consider cases where one or all are of the same type.
Does special things for "projs", "bads", and "meas_date".
"""
values = [d[key] for d in infos]
msg = ("... | @verbose
def _merge_info_values(infos, key, verbose=None):
| """Merge things together.
Fork for {'dict', 'list', 'array', 'other'}
and consider cases where one or all are of the same type.
Does special things for "projs", "bads", and "meas_date".
"""
values = [d[key] for d in infos]
msg = ("Don't know how to merge '%s'. Make sure values are "
... | B_MEAS_INFO)
# Processing history
_write_proc_history(fid, info)
@fill_doc
def write_info(fname, info, data_type=None, reset_range=True):
"""Write measurement info in fif file.
Parameters
----------
fname : str
The name of the file. Should end by -info.fif.
%(info_not_none)s
... | 224 | 224 | 748 | 16 | 208 | twang5/mne-python | mne/io/meas_info.py | Python | _merge_info_values | _merge_info_values | 2,072 | 2,157 | 2,072 | 2,073 | 0a585bbdbf088dfad16e3a2572fbbe5c07fd0654 | bigcode/the-stack | train |
ecd1722210490f5029f3eca0 | train | function | def _make_ch_names_mapping(chs):
orig_ch_names = [c['ch_name'] for c in chs]
ch_names = orig_ch_names.copy()
_unique_channel_names(ch_names, max_length=15, verbose='error')
ch_names_mapping = dict()
if orig_ch_names != ch_names:
ch_names_mapping.update(zip(orig_ch_names, ch_names))
retur... | def _make_ch_names_mapping(chs):
| orig_ch_names = [c['ch_name'] for c in chs]
ch_names = orig_ch_names.copy()
_unique_channel_names(ch_names, max_length=15, verbose='error')
ch_names_mapping = dict()
if orig_ch_names != ch_names:
ch_names_mapping.update(zip(orig_ch_names, ch_names))
return ch_names_mapping
| (obj, casts):
# unpack a dict of array into a list of dict
n = len(obj[list(casts)[0]])
return [{key: cast(obj[key][ii]) for key, cast in casts.items()}
for ii in range(n)]
def _make_ch_names_mapping(chs):
| 63 | 64 | 87 | 9 | 54 | twang5/mne-python | mne/io/meas_info.py | Python | _make_ch_names_mapping | _make_ch_names_mapping | 2,691 | 2,698 | 2,691 | 2,691 | b6e1c632e269aaae1e73a2b85401132881607820 | bigcode/the-stack | train |
e996688267fc536043fbdf01 | train | function | @verbose
def write_fiducials(fname, pts, coord_frame=FIFF.FIFFV_COORD_UNKNOWN, *,
overwrite=False, verbose=None):
"""Write fiducials to a fiff file.
Parameters
----------
fname : str
Destination file name.
pts : iterator of dict
Iterator through digitizer points.... | @verbose
def write_fiducials(fname, pts, coord_frame=FIFF.FIFFV_COORD_UNKNOWN, *,
overwrite=False, verbose=None):
| """Write fiducials to a fiff file.
Parameters
----------
fname : str
Destination file name.
pts : iterator of dict
Iterator through digitizer points. Each point is a dictionary with
the keys 'kind', 'ident' and 'r'.
coord_frame : int
The coordinate frame of the p... | coord_frame is not stored in the tag
for pt in pts:
pt['coord_frame'] = coord_frame
return pts, coord_frame
@verbose
def write_fiducials(fname, pts, coord_frame=FIFF.FIFFV_COORD_UNKNOWN, *,
overwrite=False, verbose=None):
| 64 | 64 | 161 | 32 | 31 | twang5/mne-python | mne/io/meas_info.py | Python | write_fiducials | write_fiducials | 1,158 | 1,178 | 1,158 | 1,160 | b6d405d12f233be99e1d11069cd6cc1420853cff | bigcode/the-stack | train |
890e935ff4d884c5cc6ed9e4 | train | function | @contextlib.contextmanager
def _writing_info_hdf5(info):
# Make info writing faster by packing chs and dig into numpy arrays
orig_dig = info.get('dig', None)
orig_chs = info['chs']
with info._unlock():
try:
if orig_dig is not None and len(orig_dig) > 0:
info['dig'] = ... | @contextlib.contextmanager
def _writing_info_hdf5(info):
# Make info writing faster by packing chs and dig into numpy arrays
| orig_dig = info.get('dig', None)
orig_chs = info['chs']
with info._unlock():
try:
if orig_dig is not None and len(orig_dig) > 0:
info['dig'] = _dict_pack(info['dig'], _DIG_CAST)
info['chs'] = _dict_pack(info['chs'], _CH_CAST)
info['chs']['ch_name']... | , cast
_CH_READ_MAP = OrderedDict((val[0], (key, val[1]))
for key, val in _CH_INFO_MAP.items())
@contextlib.contextmanager
def _writing_info_hdf5(info):
# Make info writing faster by packing chs and dig into numpy arrays
| 64 | 64 | 174 | 31 | 33 | twang5/mne-python | mne/io/meas_info.py | Python | _writing_info_hdf5 | _writing_info_hdf5 | 2,660 | 2,676 | 2,660 | 2,662 | f7c2b9904e92479118c4dfec14810542bf85d92b | bigcode/the-stack | train |
be0d20e7ca9ebb688fd84f05 | train | function | @verbose
def read_info(fname, verbose=None):
"""Read measurement info from a file.
Parameters
----------
fname : str
File name.
%(verbose)s
Returns
-------
%(info_not_none)s
"""
f, tree, _ = fiff_open(fname)
with f as fid:
info = read_meas_info(fid, tree)[0]... | @verbose
def read_info(fname, verbose=None):
| """Read measurement info from a file.
Parameters
----------
fname : str
File name.
%(verbose)s
Returns
-------
%(info_not_none)s
"""
f, tree, _ = fiff_open(fname)
with f as fid:
info = read_meas_info(fid, tree)[0]
return info
| of
mne.io.constants.FIFF.FIFFV_COORD_...).
%(overwrite)s
.. versionadded:: 1.0
%(verbose)s
"""
write_dig(fname, pts, coord_frame, overwrite=overwrite)
@verbose
def read_info(fname, verbose=None):
| 64 | 64 | 88 | 11 | 53 | twang5/mne-python | mne/io/meas_info.py | Python | read_info | read_info | 1,181 | 1,198 | 1,181 | 1,182 | 9096a09bcfa0bd1336f28670b643067b28d47f37 | bigcode/the-stack | train |
30fdecd2f9c4fbba251e33c1 | train | function | def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'static',
'dest': 'vispy',
'require': 'vispy/extension'
}]
| def _jupyter_nbextension_paths():
| return [{
'section': 'notebook',
'src': 'static',
'dest': 'vispy',
'require': 'vispy/extension'
}]
| , the user only needs to run %load_ext vispy.ipython rather that
# %load_ext vispy.ipython.ipython
from .ipython import load_ipython_extension, unload_ipython_extension # noqa
# Allow for Jupyter extension to be enabled
def _jupyter_nbextension_paths():
| 64 | 64 | 46 | 8 | 55 | 3DAlgoLab/vispy | vispy/__init__.py | Python | _jupyter_nbextension_paths | _jupyter_nbextension_paths | 36 | 42 | 36 | 36 | 3c85c3e4acb0c5f3c20db68edaa9c3a72ed3925a | bigcode/the-stack | train |
4fc9cbc36f7deeee2160dc46 | train | function | def infer_depth(rgb_image, params):
"""Runs depth inference given an RGB frame.
Args:
rgb_image: A tf.Tensor or shape [B, H, W, 3] containing RGB images.
params: A dictionary of parameters contraining overrides for
DEFAULT_PARAMS.
Returns:
A tf.Tensor of shape [B, H, W, 1] containing the infer... | def infer_depth(rgb_image, params):
| """Runs depth inference given an RGB frame.
Args:
rgb_image: A tf.Tensor or shape [B, H, W, 3] containing RGB images.
params: A dictionary of parameters contraining overrides for
DEFAULT_PARAMS.
Returns:
A tf.Tensor of shape [B, H, W, 1] containing the inferred depths.
"""
if rgb_image.sha... | _mask):
return tf.reduce_all(tf.not_equal(0, input_mask), axis=2, keepdims=True)
output = dict(endpoints)
output['mask'] = tuple([create_mobile_mask(m) for m in endpoints['mask']])
return output
def infer_depth(rgb_image, params):
| 64 | 64 | 194 | 8 | 55 | deepneuralmachine/google-research | depth_and_motion_learning/depth_motion_field_model.py | Python | infer_depth | infer_depth | 414 | 433 | 414 | 414 | 0e28ae094e892ac53f7df6941ea72025e9af45c7 | bigcode/the-stack | train |
fe2338942579d4e6663289ec | train | function | def infer_egomotion(rgb_image1, rgb_image2, params):
"""Runs egomotion inference given two RGB frames.
Args:
rgb_image1: A tf.Tensor or shape [B, H, W, 3] containing RGB images, the
first frame.
rgb_image2: A tf.Tensor or shape [B, H, W, 3] containing RGB images, the
second frame.
params: A... | def infer_egomotion(rgb_image1, rgb_image2, params):
| """Runs egomotion inference given two RGB frames.
Args:
rgb_image1: A tf.Tensor or shape [B, H, W, 3] containing RGB images, the
first frame.
rgb_image2: A tf.Tensor or shape [B, H, W, 3] containing RGB images, the
second frame.
params: A dictionary of parameters contraining overrides for D... | DEFAULT_PARAMS.
Returns:
A tf.Tensor of shape [B, H, W, 1] containing the inferred depths.
"""
if rgb_image.shape.rank != 4:
raise ValueError('rgb_image should have rank 4, not %d.' %
rgb_image.shape.rank)
params = parameter_container.ParameterContainer.from_defaults_and_overrides... | 153 | 153 | 513 | 16 | 137 | deepneuralmachine/google-research | depth_and_motion_learning/depth_motion_field_model.py | Python | infer_egomotion | infer_egomotion | 436 | 475 | 436 | 436 | dc7492e303900939a121b16330a16df9cf8a48c6 | bigcode/the-stack | train |
622359deb55cea7ce3cadda7 | train | function | def loss_fn(features, mode, params):
"""Computes the training loss for depth and egomotion training.
This function is written with TPU-friendlines in mind.
Args:
features: A dictionary mapping strings to tuples of (tf.Tensor, tf.Tensor),
representing pairs of frames. The loss will be calculated from t... | def loss_fn(features, mode, params):
| """Computes the training loss for depth and egomotion training.
This function is written with TPU-friendlines in mind.
Args:
features: A dictionary mapping strings to tuples of (tf.Tensor, tf.Tensor),
representing pairs of frames. The loss will be calculated from these
tensors. The expected endp... | # given video_id (works with the YouTube format in /dataset).
'per_video': False,
# If per_video is true, this is the maximal number of video ids for
# which the hash table that keeps track of the intrsinsics.
'max_number_of_videos': 1000,
},
# True to feed depth predic... | 256 | 256 | 1,953 | 9 | 247 | deepneuralmachine/google-research | depth_and_motion_learning/depth_motion_field_model.py | Python | loss_fn | loss_fn | 124 | 294 | 124 | 124 | d363a774e75787a0dff009abb3b08197dd9a7334 | bigcode/the-stack | train |
941eb636b5fbd25ad11f1d90 | train | function | def preprocess_masks(endpoints):
def create_mobile_mask(input_mask):
return tf.reduce_all(tf.not_equal(0, input_mask), axis=2, keepdims=True)
output = dict(endpoints)
output['mask'] = tuple([create_mobile_mask(m) for m in endpoints['mask']])
return output
| def preprocess_masks(endpoints):
| def create_mobile_mask(input_mask):
return tf.reduce_all(tf.not_equal(0, input_mask), axis=2, keepdims=True)
output = dict(endpoints)
output['mask'] = tuple([create_mobile_mask(m) for m in endpoints['mask']])
return output
| = name.replace('moving_variance', 'sigma')
vars_to_restore[name[len('depth_prediction') + 1:]] = v
return vars_to_restore
return vars_to_restore_fn
else:
raise ValueError('Unknown initialization %s' % initialization)
def preprocess_masks(endpoints):
| 64 | 64 | 68 | 6 | 58 | deepneuralmachine/google-research | depth_and_motion_learning/depth_motion_field_model.py | Python | preprocess_masks | preprocess_masks | 404 | 411 | 404 | 405 | 98da17ff29f43250ecff2fa674a279e77e30f198 | bigcode/the-stack | train |
6c2c108b85166fb6027855d6 | train | function | def input_fn(params):
"""An Estimator's input_fn for reading and preprocessing training data.
Reads pairs of RGBD frames from sstables, filters out near duplicates and
performs data augmentation.
Args:
params: A dictionary with hyperparameters.
Returns:
A tf.data.Dataset object.
"""
params = p... | def input_fn(params):
| """An Estimator's input_fn for reading and preprocessing training data.
Reads pairs of RGBD frames from sstables, filters out near duplicates and
performs data augmentation.
Args:
params: A dictionary with hyperparameters.
Returns:
A tf.data.Dataset object.
"""
params = parameter_container.Par... | gt_disp1)
depth_proximity_weight0, depth_proximity_weight1 = tf.split(
aggregator.output_endpoints['depth_proximity_weight'], 2, axis=0)
maybe_summary.image('consistency_weight0',
tf.expand_dims(depth_proximity_weight0, -1))
maybe_summary.image('consistency_weight1',
... | 158 | 158 | 528 | 5 | 152 | deepneuralmachine/google-research | depth_and_motion_learning/depth_motion_field_model.py | Python | input_fn | input_fn | 297 | 363 | 297 | 297 | 5cce49bb49434b1a5650daf6d1c9002afcfe2388 | bigcode/the-stack | train |
321b5a765e2dd3aa64875633 | train | function | def get_vars_to_restore_fn(initialization):
"""Returns a vars_to_restore_fn for various types of `initialization`.
Args:
initialization: A string, the type of the initialization. Currently only
'imagenet' is supported.
Raises:
ValueError: `initialization` is not supported
"""
if initializatio... | def get_vars_to_restore_fn(initialization):
| """Returns a vars_to_restore_fn for various types of `initialization`.
Args:
initialization: A string, the type of the initialization. Currently only
'imagenet' is supported.
Raises:
ValueError: `initialization` is not supported
"""
if initialization == 'imagenet':
def is_blacklisted(nam... | , params.image_preprocessing.image_height,
params.image_preprocessing.image_width)
augmentation_fn = resize_fn
dataset = dataset.map(augmentation_fn)
dataset = dataset.shuffle(params.input.shuffle_queue_size)
dataset = dataset.batch(params.batch_size, drop_remainder=True)
return dataset.prefetch... | 77 | 77 | 259 | 9 | 68 | deepneuralmachine/google-research | depth_and_motion_learning/depth_motion_field_model.py | Python | get_vars_to_restore_fn | get_vars_to_restore_fn | 366 | 401 | 366 | 366 | 17cb7eb24cf3b086790292316b3fa1b11b4d63b8 | bigcode/the-stack | train |
19a812df872f512c9440b4c7 | train | class | class Migration(migrations.Migration):
dependencies = [
('controller', '0002_auto_20210517_1754'),
]
operations = [
migrations.AlterField(
model_name='jmeterserver',
name='loadgenerator',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCAD... | class Migration(migrations.Migration):
| dependencies = [
('controller', '0002_auto_20210517_1754'),
]
operations = [
migrations.AlterField(
model_name='jmeterserver',
name='loadgenerator',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='controller.LoadGenerator'),
... | # Generated by Django 2.2.20 on 2021-06-03 14:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 45 | 64 | 117 | 7 | 37 | v0devil/jltom | ltc/controller/migrations/0003_auto_20210603_1631.py | Python | Migration | Migration | 7 | 24 | 7 | 8 | 084d36761ac9554fcb2fd169babf8db43c6f0d21 | bigcode/the-stack | train |
f91b5f1fd908b0b1d5b5d877 | train | class | @admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
list_display = ['image', 'title', 'slug','created']
list_filter = ['created']
| @admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
| list_display = ['image', 'title', 'slug','created']
list_filter = ['created']
| from django.contrib import admin
from .models import Image
@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
| 24 | 64 | 34 | 12 | 11 | KwabenaYeboah/photoshare | images/admin.py | Python | ImageAdmin | ImageAdmin | 4 | 7 | 4 | 5 | 19e66b590d69205dd631c665765e6a2b30b8831f | bigcode/the-stack | train |
ffcb7abdeff0ac3894fc534f | train | class | class Graph:
def __init__(self, num=1, mode="train"):
'''
Args:
num: Either 1 or 2. 1 for Text2Mel 2 for SSRN.
mode: Either "train" or "synthesize".
'''
# Load vocabulary
self.char2idx, self.idx2char = load_vocab()
# Set flag
training = Tr... | class Graph:
| def __init__(self, num=1, mode="train"):
'''
Args:
num: Either 1 or 2. 1 for Text2Mel 2 for SSRN.
mode: Either "train" or "synthesize".
'''
# Load vocabulary
self.char2idx, self.idx2char = load_vocab()
# Set flag
training = True if mode=="... | # -*- coding: utf-8 -*-
# /usr/bin/python2
'''
By kyubyong park. kbpark.linguist@gmail.com.
https://www.github.com/kyubyong/multi-speech-corpora/dc_tts
'''
from __future__ import print_function
from tqdm import tqdm
from data_load import get_batch, load_vocab
from hyperparams import Hyperparams as hp
from modules i... | 137 | 256 | 1,323 | 3 | 134 | gusrud1103/kss_hk_mac | train.py | Python | Graph | Graph | 23 | 136 | 23 | 23 | 644191be9d4b9ff6970cfcdf7b44b310db0bb177 | bigcode/the-stack | train |
d17fb434c0712016e69d9b60 | train | function | @Client.on_callback_query()
async def cb_handler(client: Client, query: CallbackQuery):
if query.from_user.id not in Config.ADMINS and query.data != "help":
await query.answer(
"Who the hell you are",
show_alert=True
)
return
else:
await query.answer()... | @Client.on_callback_query()
async def cb_handler(client: Client, query: CallbackQuery):
| if query.from_user.id not in Config.ADMINS and query.data != "help":
await query.answer(
"Who the hell you are",
show_alert=True
)
return
else:
await query.answer()
if query.data == "replay":
group_call = mp.group_call
if not playli... | /dplay <song name> to play a song from Deezer.</b>
**Common Commands**:
**/play** Reply to an audio file or YouTube link to play it or use /play <song name>.
**/dplay** Play music from Deezer, Use /dplay <song name>
**/player** Show current playing song.
**/help** Show help for commands
**/playlist** Shows the pla... | 256 | 256 | 959 | 19 | 237 | SMILE-KILLER10/MUSIC-BOT | plugins/callback.py | Python | cb_handler | cb_handler | 65 | 187 | 65 | 66 | af01e3916ba571b826cb10b524ae2c5089ecf507 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.