text
stringlengths 3
1.05M
|
|---|
##############################################################################
#
# Copyright (c) 2001-2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Buffers
"""
from io import BytesIO
# copy_bytes controls the size of temp. strings for shuffling data around.
COPY_BYTES = 1 << 18 # 256K
# The maximum number of bytes to buffer in a simple string.
STRBUF_LIMIT = 8192
class FileBasedBuffer(object):
remain = 0
def __init__(self, file, from_buffer=None):
self.file = file
if from_buffer is not None:
from_file = from_buffer.getfile()
read_pos = from_file.tell()
from_file.seek(0)
while True:
data = from_file.read(COPY_BYTES)
if not data:
break
file.write(data)
self.remain = int(file.tell() - read_pos)
from_file.seek(read_pos)
file.seek(read_pos)
def __len__(self):
return self.remain
def __nonzero__(self):
return self.remain > 0
__bool__ = __nonzero__ # py3
def append(self, s):
file = self.file
read_pos = file.tell()
file.seek(0, 2)
file.write(s)
file.seek(read_pos)
self.remain = self.remain + len(s)
def get(self, numbytes=-1, skip=False):
file = self.file
if not skip:
read_pos = file.tell()
if numbytes < 0:
# Read all
res = file.read()
else:
res = file.read(numbytes)
if skip:
self.remain -= len(res)
else:
file.seek(read_pos)
return res
def skip(self, numbytes, allow_prune=0):
if self.remain < numbytes:
raise ValueError("Can't skip %d bytes in buffer of %d bytes" % (
numbytes, self.remain)
)
self.file.seek(numbytes, 1)
self.remain = self.remain - numbytes
def newfile(self):
raise NotImplementedError()
def prune(self):
file = self.file
if self.remain == 0:
read_pos = file.tell()
file.seek(0, 2)
sz = file.tell()
file.seek(read_pos)
if sz == 0:
# Nothing to prune.
return
nf = self.newfile()
while True:
data = file.read(COPY_BYTES)
if not data:
break
nf.write(data)
self.file = nf
def getfile(self):
return self.file
def _close(self):
# named _close because ReadOnlyFileBasedBuffer is used as
# wsgi file.wrapper, and its protocol reserves "close"
if hasattr(self.file, 'close'):
self.file.close()
self.remain = 0
class TempfileBasedBuffer(FileBasedBuffer):
def __init__(self, from_buffer=None):
FileBasedBuffer.__init__(self, self.newfile(), from_buffer)
def newfile(self):
from tempfile import TemporaryFile
return TemporaryFile('w+b')
class BytesIOBasedBuffer(FileBasedBuffer):
def __init__(self, from_buffer=None):
if from_buffer is not None:
FileBasedBuffer.__init__(self, BytesIO(), from_buffer)
else:
# Shortcut. :-)
self.file = BytesIO()
def newfile(self):
return BytesIO()
class ReadOnlyFileBasedBuffer(FileBasedBuffer):
# used as wsgi.file_wrapper
def __init__(self, file, block_size=32768):
self.file = file
self.block_size = block_size # for __iter__
def prepare(self, size=None):
if hasattr(self.file, 'seek') and hasattr(self.file, 'tell'):
start_pos = self.file.tell()
self.file.seek(0, 2)
end_pos = self.file.tell()
self.file.seek(start_pos)
fsize = end_pos - start_pos
if size is None:
self.remain = fsize
else:
self.remain = min(fsize, size)
elif hasattr(self.file, 'close'):
# called by task if self.filelike has no seek/tell
self.close = self.file.close
return self.remain
def get(self, numbytes=-1, skip=False):
# never read more than self.remain (it can be user-specified)
if numbytes == -1 or numbytes > self.remain:
numbytes = self.remain
file = self.file
if not skip:
read_pos = file.tell()
res = file.read(numbytes)
if skip:
self.remain -= len(res)
else:
file.seek(read_pos)
return res
def __iter__(self): # called by task if self.filelike has no seek/tell
return self
def next(self):
val = self.file.read(self.block_size)
if not val:
raise StopIteration
return val
__next__ = next # py3
def append(self, s):
raise NotImplementedError
class OverflowableBuffer(object):
"""
This buffer implementation has four stages:
- No data
- String-based buffer
- StringIO-based buffer
- Temporary file storage
The first two stages are fastest for simple transfers.
"""
overflowed = False
buf = None
strbuf = b'' # Bytes-based buffer.
def __init__(self, overflow):
# overflow is the maximum to be stored in a StringIO buffer.
self.overflow = overflow
def __len__(self):
buf = self.buf
if buf is not None:
return buf.__len__()
else:
return self.strbuf.__len__()
def __nonzero__(self):
return self.__len__() > 0
__bool__ = __nonzero__ # py3
def _create_buffer(self):
strbuf = self.strbuf
if len(strbuf) >= self.overflow:
self._set_large_buffer()
else:
self._set_small_buffer()
buf = self.buf
if strbuf:
buf.append(self.strbuf)
self.strbuf = b''
return buf
def _set_small_buffer(self):
self.buf = BytesIOBasedBuffer(self.buf)
self.overflowed = False
def _set_large_buffer(self):
self.buf = TempfileBasedBuffer(self.buf)
self.overflowed = True
def append(self, s):
buf = self.buf
if buf is None:
strbuf = self.strbuf
if len(strbuf) + len(s) < STRBUF_LIMIT:
self.strbuf = strbuf + s
return
buf = self._create_buffer()
buf.append(s)
sz = len(buf)
if not self.overflowed:
if sz >= self.overflow:
self._set_large_buffer()
def get(self, numbytes=-1, skip=False):
buf = self.buf
if buf is None:
strbuf = self.strbuf
if not skip:
return strbuf
buf = self._create_buffer()
return buf.get(numbytes, skip)
def skip(self, numbytes, allow_prune=False):
buf = self.buf
if buf is None:
if allow_prune and numbytes == len(self.strbuf):
# We could slice instead of converting to
# a buffer, but that would eat up memory in
# large transfers.
self.strbuf = b''
return
buf = self._create_buffer()
buf.skip(numbytes, allow_prune)
def prune(self):
"""
A potentially expensive operation that removes all data
already retrieved from the buffer.
"""
buf = self.buf
if buf is None:
self.strbuf = b''
return
buf.prune()
if self.overflowed:
sz = len(buf)
if sz < self.overflow:
# Revert to a faster buffer.
self._set_small_buffer()
def getfile(self):
buf = self.buf
if buf is None:
buf = self._create_buffer()
return buf.getfile()
def _close(self):
buf = self.buf
if buf is not None:
buf._close()
|
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "../Vq.h"
#include "../common/Macros.h"
namespace Vq {
class AbstractPlugin;
class VQ_API PluginBundle
{
public:
PluginBundle( const std::string &bundleId,
const std::string &bundleName );
PluginBundle( PluginBundle &other ) = delete;
PluginBundle & operator=( PluginBundle &other ) = delete;
const std::string & bundleId() const;
const std::string & bundleName() const;
virtual void addPlugin( std::unique_ptr< AbstractPlugin > plugin );
std::size_t pluginCount() const;
AbstractPlugin * pluginAt( const std::size_t index ) const;
virtual void addDependency( const std::string &bundleId );
const std::vector< std::string > & dependencies() const;
virtual ~PluginBundle();
protected:
std::vector< std::unique_ptr< AbstractPlugin >> & mutablePluginList();
std::vector< std::string > & mutalbleDependencyList();
private:
class Impl;
std::unique_ptr< Impl > m_impl;
};
}
struct VQ_API BundleWrapper {
Vq::PluginBundle *theBundle;
};
|
var Plane = function () {
};
|
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pickle
from argparse import ArgumentParser, Namespace
from dataclasses import dataclass
from typing import Any, Dict
from unittest import mock
from unittest.mock import call, Mock, PropertyMock
import pytest
import torch
from pytorch_lightning import LightningDataModule, Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.trainer.states import TrainerFn
from pytorch_lightning.utilities import _OMEGACONF_AVAILABLE, AttributeDict
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from pytorch_lightning.utilities.model_helpers import is_overridden
from tests.helpers import BoringDataModule, BoringModel
from tests.helpers.datamodules import ClassifDataModule
from tests.helpers.runif import RunIf
from tests.helpers.simple_models import ClassificationModel
from tests.helpers.utils import reset_seed
if _OMEGACONF_AVAILABLE:
from omegaconf import OmegaConf
@mock.patch("pytorch_lightning.trainer.trainer.Trainer.node_rank", new_callable=PropertyMock)
@mock.patch("pytorch_lightning.trainer.trainer.Trainer.local_rank", new_callable=PropertyMock)
def test_can_prepare_data(local_rank, node_rank):
dm = Mock(spec=LightningDataModule)
dm.prepare_data_per_node = True
trainer = Trainer()
trainer.datamodule = dm
# 1 no DM
# prepare_data_per_node = True
# local rank = 0 (True)
dm.prepare_data.assert_not_called()
local_rank.return_value = 0
assert trainer.local_rank == 0
trainer._data_connector.prepare_data()
dm.prepare_data.assert_called_once()
# local rank = 1 (False)
dm.reset_mock()
local_rank.return_value = 1
assert trainer.local_rank == 1
trainer._data_connector.prepare_data()
dm.prepare_data.assert_not_called()
# prepare_data_per_node = False (prepare across all nodes)
# global rank = 0 (True)
dm.reset_mock()
dm.prepare_data_per_node = False
node_rank.return_value = 0
local_rank.return_value = 0
trainer._data_connector.prepare_data()
dm.prepare_data.assert_called_once()
# global rank = 1 (False)
dm.reset_mock()
node_rank.return_value = 1
local_rank.return_value = 0
trainer._data_connector.prepare_data()
dm.prepare_data.assert_not_called()
node_rank.return_value = 0
local_rank.return_value = 1
trainer._data_connector.prepare_data()
dm.prepare_data.assert_not_called()
# 2 dm
# prepar per node = True
# local rank = 0 (True)
dm.prepare_data_per_node = True
local_rank.return_value = 0
# is_overridden prepare data = True
trainer._data_connector.prepare_data()
dm.prepare_data.assert_called_once()
def test_hooks_no_recursion_error():
# hooks were appended in cascade every tine a new data module was instantiated leading to a recursion error.
# See https://github.com/PyTorchLightning/pytorch-lightning/issues/3652
class DummyDM(LightningDataModule):
def setup(self, *args, **kwargs):
pass
def prepare_data(self, *args, **kwargs):
pass
for i in range(1005):
dm = DummyDM()
dm.setup()
dm.prepare_data()
def test_helper_boringdatamodule():
dm = BoringDataModule()
dm.prepare_data()
dm.setup()
def test_helper_boringdatamodule_with_verbose_setup():
dm = BoringDataModule()
dm.prepare_data()
dm.setup("fit")
dm.setup("test")
def test_dm_add_argparse_args(tmpdir):
parser = ArgumentParser()
parser = BoringDataModule.add_argparse_args(parser)
args = parser.parse_args(["--data_dir", str(tmpdir)])
assert args.data_dir == str(tmpdir)
def test_dm_init_from_argparse_args(tmpdir):
parser = ArgumentParser()
parser = BoringDataModule.add_argparse_args(parser)
args = parser.parse_args(["--data_dir", str(tmpdir)])
dm = BoringDataModule.from_argparse_args(args)
dm.prepare_data()
dm.setup()
assert dm.data_dir == args.data_dir == str(tmpdir)
def test_dm_pickle_after_init():
dm = BoringDataModule()
pickle.dumps(dm)
def test_train_loop_only(tmpdir):
reset_seed()
dm = ClassifDataModule()
model = ClassificationModel()
model.validation_step = None
model.validation_step_end = None
model.validation_epoch_end = None
model.test_step = None
model.test_step_end = None
model.test_epoch_end = None
trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, enable_model_summary=False)
# fit model
trainer.fit(model, datamodule=dm)
assert trainer.state.finished, f"Training failed with {trainer.state}"
assert trainer.callback_metrics["train_loss"] < 1.0
def test_train_val_loop_only(tmpdir):
reset_seed()
dm = ClassifDataModule()
model = ClassificationModel()
model.validation_step = None
model.validation_step_end = None
model.validation_epoch_end = None
trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, enable_model_summary=False)
# fit model
trainer.fit(model, datamodule=dm)
assert trainer.state.finished, f"Training failed with {trainer.state}"
assert trainer.callback_metrics["train_loss"] < 1.0
def test_dm_checkpoint_save_and_load(tmpdir):
class CustomBoringModel(BoringModel):
def validation_step(self, batch, batch_idx):
out = super().validation_step(batch, batch_idx)
self.log("early_stop_on", out["x"])
return out
class CustomBoringDataModule(BoringDataModule):
def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None:
checkpoint[self.__class__.__name__] = self.__class__.__name__
def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None:
self.checkpoint_state = checkpoint.get(self.__class__.__name__)
reset_seed()
dm = CustomBoringDataModule()
model = CustomBoringModel()
trainer = Trainer(
default_root_dir=tmpdir,
max_epochs=1,
limit_train_batches=2,
limit_val_batches=1,
enable_model_summary=False,
callbacks=[ModelCheckpoint(dirpath=tmpdir, monitor="early_stop_on")],
)
# fit model
trainer.fit(model, datamodule=dm)
assert trainer.state.finished, f"Training failed with {trainer.state}"
checkpoint_path = list(trainer.checkpoint_callback.best_k_models.keys())[0]
checkpoint = torch.load(checkpoint_path)
assert dm.__class__.__name__ in checkpoint
assert checkpoint[dm.__class__.__name__] == dm.__class__.__name__
for trainer_fn in TrainerFn:
trainer.state.fn = trainer_fn
with mock.patch.object(dm, "on_load_checkpoint") as dm_mock:
trainer._restore_modules_and_callbacks(checkpoint_path)
dm_mock.assert_called_once()
def test_full_loop(tmpdir):
reset_seed()
dm = ClassifDataModule()
model = ClassificationModel()
trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, enable_model_summary=False, deterministic=True)
# fit model
trainer.fit(model, dm)
assert trainer.state.finished, f"Training failed with {trainer.state}"
assert dm.trainer is not None
# validate
result = trainer.validate(model, dm)
assert dm.trainer is not None
assert result[0]["val_acc"] > 0.7
# test
result = trainer.test(model, dm)
assert dm.trainer is not None
assert result[0]["test_acc"] > 0.6
@RunIf(min_gpus=1)
@mock.patch(
"pytorch_lightning.strategies.training_type_plugin.Strategy.lightning_module",
new_callable=PropertyMock,
)
def test_dm_apply_batch_transfer_handler(get_module_mock):
expected_device = torch.device("cuda", 0)
class CustomBatch:
def __init__(self, data):
self.samples = data[0]
self.targets = data[1]
class CurrentTestDM(LightningDataModule):
rank = 0
transfer_batch_to_device_hook_rank = None
on_before_batch_transfer_hook_rank = None
on_after_batch_transfer_hook_rank = None
def on_before_batch_transfer(self, batch, dataloader_idx):
assert dataloader_idx == 0
self.on_before_batch_transfer_hook_rank = self.rank
self.rank += 1
batch.samples += 1
return batch
def on_after_batch_transfer(self, batch, dataloader_idx):
assert dataloader_idx == 0
assert batch.samples.device == batch.targets.device == expected_device
self.on_after_batch_transfer_hook_rank = self.rank
self.rank += 1
batch.targets *= 2
return batch
def transfer_batch_to_device(self, batch, device, dataloader_idx):
assert dataloader_idx == 0
self.transfer_batch_to_device_hook_rank = self.rank
self.rank += 1
batch.samples = batch.samples.to(device)
batch.targets = batch.targets.to(device)
return batch
dm = CurrentTestDM()
model = BoringModel()
batch = CustomBatch((torch.zeros(5, 32), torch.ones(5, 1, dtype=torch.long)))
trainer = Trainer(gpus=1)
# running .fit() would require us to implement custom data loaders, we mock the model reference instead
get_module_mock.return_value = model
if is_overridden("transfer_batch_to_device", dm):
model.transfer_batch_to_device = dm.transfer_batch_to_device
model.on_before_batch_transfer = dm.on_before_batch_transfer
model.transfer_batch_to_device = dm.transfer_batch_to_device
model.on_after_batch_transfer = dm.on_after_batch_transfer
batch_gpu = trainer.strategy.batch_to_device(batch, expected_device)
assert dm.on_before_batch_transfer_hook_rank == 0
assert dm.transfer_batch_to_device_hook_rank == 1
assert dm.on_after_batch_transfer_hook_rank == 2
assert batch_gpu.samples.device == batch_gpu.targets.device == expected_device
assert torch.allclose(batch_gpu.samples.cpu(), torch.ones(5, 32))
assert torch.allclose(batch_gpu.targets.cpu(), torch.ones(5, 1, dtype=torch.long) * 2)
def test_dm_reload_dataloaders_every_n_epochs(tmpdir):
"""Test datamodule, where trainer argument reload_dataloaders_every_n_epochs is set to a non negative
integer."""
class CustomBoringDataModule(BoringDataModule):
def __init__(self):
super().__init__()
self._epochs_called_for = []
def train_dataloader(self):
assert self.trainer.current_epoch not in self._epochs_called_for
self._epochs_called_for.append(self.trainer.current_epoch)
return super().train_dataloader()
dm = CustomBoringDataModule()
model = BoringModel()
model.validation_step = None
model.validation_step_end = None
model.validation_epoch_end = None
model.test_step = None
model.test_step_end = None
model.test_epoch_end = None
trainer = Trainer(default_root_dir=tmpdir, max_epochs=3, limit_train_batches=2, reload_dataloaders_every_n_epochs=2)
trainer.fit(model, dm)
class DummyDS(torch.utils.data.Dataset):
def __getitem__(self, index):
return 1
def __len__(self):
return 100
class DummyIDS(torch.utils.data.IterableDataset):
def __iter__(self):
yield 1
@pytest.mark.parametrize("iterable", (False, True))
def test_dm_init_from_datasets_dataloaders(iterable):
ds = DummyIDS if iterable else DummyDS
train_ds = ds()
dm = LightningDataModule.from_datasets(train_ds, batch_size=4, num_workers=0)
with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock:
dm.train_dataloader()
dl_mock.assert_called_once_with(train_ds, batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True)
with pytest.raises(NotImplementedError):
_ = dm.val_dataloader()
with pytest.raises(NotImplementedError):
_ = dm.test_dataloader()
train_ds_sequence = [ds(), ds()]
dm = LightningDataModule.from_datasets(train_ds_sequence, batch_size=4, num_workers=0)
with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock:
dm.train_dataloader()
dl_mock.assert_has_calls(
[
call(train_ds_sequence[0], batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True),
call(train_ds_sequence[1], batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True),
]
)
with pytest.raises(NotImplementedError):
_ = dm.val_dataloader()
with pytest.raises(NotImplementedError):
_ = dm.test_dataloader()
valid_ds = ds()
test_ds = ds()
dm = LightningDataModule.from_datasets(val_dataset=valid_ds, test_dataset=test_ds, batch_size=2, num_workers=0)
with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock:
dm.val_dataloader()
dl_mock.assert_called_with(valid_ds, batch_size=2, shuffle=False, num_workers=0, pin_memory=True)
dm.test_dataloader()
dl_mock.assert_called_with(test_ds, batch_size=2, shuffle=False, num_workers=0, pin_memory=True)
with pytest.raises(NotImplementedError):
_ = dm.train_dataloader()
valid_dss = [ds(), ds()]
test_dss = [ds(), ds()]
dm = LightningDataModule.from_datasets(train_ds, valid_dss, test_dss, batch_size=4, num_workers=0)
with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock:
dm.val_dataloader()
dm.test_dataloader()
dl_mock.assert_has_calls(
[
call(valid_dss[0], batch_size=4, shuffle=False, num_workers=0, pin_memory=True),
call(valid_dss[1], batch_size=4, shuffle=False, num_workers=0, pin_memory=True),
call(test_dss[0], batch_size=4, shuffle=False, num_workers=0, pin_memory=True),
call(test_dss[1], batch_size=4, shuffle=False, num_workers=0, pin_memory=True),
]
)
# all args
class DataModuleWithHparams_0(LightningDataModule):
def __init__(self, arg0, arg1, kwarg0=None):
super().__init__()
self.save_hyperparameters()
# single arg
class DataModuleWithHparams_1(LightningDataModule):
def __init__(self, arg0, *args, **kwargs):
super().__init__()
self.save_hyperparameters(arg0)
def test_hyperparameters_saving():
data = DataModuleWithHparams_0(10, "foo", kwarg0="bar")
assert data.hparams == AttributeDict({"arg0": 10, "arg1": "foo", "kwarg0": "bar"})
data = DataModuleWithHparams_1(Namespace(**{"hello": "world"}), "foo", kwarg0="bar")
assert data.hparams == AttributeDict({"hello": "world"})
data = DataModuleWithHparams_1({"hello": "world"}, "foo", kwarg0="bar")
assert data.hparams == AttributeDict({"hello": "world"})
if _OMEGACONF_AVAILABLE:
data = DataModuleWithHparams_1(OmegaConf.create({"hello": "world"}), "foo", kwarg0="bar")
assert data.hparams == OmegaConf.create({"hello": "world"})
def test_define_as_dataclass():
class BoringDataModule(LightningDataModule):
def __init__(self, foo=None):
super().__init__()
# makes sure that no functionality is broken and the user can still manually make
# super().__init__ call with parameters
# also tests all the dataclass features that can be enabled without breaking anything
@dataclass(init=True, repr=True, eq=True, order=True, unsafe_hash=True, frozen=False)
class BoringDataModule1(BoringDataModule):
batch_size: int
foo: int = 2
def __post_init__(self):
super().__init__(foo=self.foo)
# asserts for the different dunder methods added by dataclass, when __init__ is implemented, i.e.
# __repr__, __eq__, __lt__, __le__, etc.
assert BoringDataModule1(batch_size=64).foo == 2
assert BoringDataModule1(batch_size=32)
assert hasattr(BoringDataModule1, "__repr__")
assert BoringDataModule1(batch_size=32) == BoringDataModule1(batch_size=32)
# asserts inherent calling of super().__init__ in case user doesn't make the call
@dataclass
class BoringDataModule2(LightningDataModule):
batch_size: int
# asserts for the different dunder methods added by dataclass, when super class is inherently initialized, i.e.
# __init__, __repr__, __eq__, __lt__, __le__, etc.
assert BoringDataModule2(batch_size=32)
assert hasattr(BoringDataModule2, "__repr__")
assert BoringDataModule2(batch_size=32).prepare_data() is None
assert BoringDataModule2(batch_size=32) == BoringDataModule2(batch_size=32)
def test_inconsistent_prepare_data_per_node(tmpdir):
with pytest.raises(MisconfigurationException, match="Inconsistent settings found for `prepare_data_per_node`."):
model = BoringModel()
dm = BoringDataModule()
with pytest.deprecated_call(match="prepare_data_per_node` with the trainer flag is deprecated"):
trainer = Trainer(prepare_data_per_node=False)
trainer.model = model
trainer.datamodule = dm
trainer._data_connector.prepare_data()
|
import os
import time
import argparse
import torch
def get_options(args=None):
parser = argparse.ArgumentParser(
description="Attention based model for solving the Travelling Salesman Problem with Reinforcement Learning")
# Data
parser.add_argument('--problem', default='tsp', help="The problem to solve, default 'tsp'")
parser.add_argument('--graph_size', type=int, default=20, help="The size of the problem graph")
parser.add_argument('--batch_size', type=int, default=512, help='Number of instances per batch during training')
parser.add_argument('--epoch_size', type=int, default=1280000, help='Number of instances per epoch during training')
parser.add_argument('--val_size', type=int, default=10000,
help='Number of instances used for reporting validation performance')
parser.add_argument('--val_dataset', type=str, default=None, help='Dataset file to use for validation')
# Model
parser.add_argument('--model', default='attention', help="Model, 'attention' (default) or 'pointer'")
parser.add_argument('--embedding_dim', type=int, default=128, help='Dimension of input embedding')
parser.add_argument('--hidden_dim', type=int, default=128, help='Dimension of hidden layers in Enc/Dec')
parser.add_argument('--n_encode_layers', type=int, default=3,
help='Number of layers in the encoder/critic network')
parser.add_argument('--tanh_clipping', type=float, default=10.,
help='Clip the parameters to within +- this value using tanh. '
'Set to 0 to not perform any clipping.')
parser.add_argument('--normalization', default='batch', help="Normalization type, 'batch' (default) or 'instance'")
# Training
parser.add_argument('--lr_model', type=float, default=1e-4, help="Set the learning rate for the actor network")
parser.add_argument('--lr_critic', type=float, default=1e-4, help="Set the learning rate for the critic network")
parser.add_argument('--lr_decay', type=float, default=1.0, help='Learning rate decay per epoch')
parser.add_argument('--eval_only', action='store_true', help='Set this value to only evaluate model')
parser.add_argument('--n_epochs', type=int, default=100, help='The number of epochs to train')
parser.add_argument('--seed', type=int, default=1234, help='Random seed to use')
parser.add_argument('--max_grad_norm', type=float, default=1.0,
help='Maximum L2 norm for gradient clipping, default 1.0 (0 to disable clipping)')
parser.add_argument('--no_cuda', action='store_true', help='Disable CUDA')
parser.add_argument('--exp_beta', type=float, default=0.8,
help='Exponential moving average baseline decay (default 0.8)')
parser.add_argument('--baseline', default=None,
help="Baseline to use: 'rollout', 'critic' or 'exponential'. Defaults to no baseline.")
parser.add_argument('--bl_alpha', type=float, default=0.05,
help='Significance in the t-test for updating rollout baseline')
parser.add_argument('--bl_warmup_epochs', type=int, default=None,
help='Number of epochs to warmup the baseline, default None means 1 for rollout (exponential '
'used for warmup phase), 0 otherwise. Can only be used with rollout baseline.')
parser.add_argument('--eval_batch_size', type=int, default=1024,
help="Batch size to use during (baseline) evaluation")
# Misc
parser.add_argument('--log_step', type=int, default=50, help='Log info every log_step steps')
parser.add_argument('--log_dir', default='logs', help='Directory to write TensorBoard information to')
parser.add_argument('--run_name', default='run', help='Name to identify the run')
parser.add_argument('--output_dir', default='outputs', help='Directory to write output models to')
parser.add_argument('--epoch_start', type=int, default=0,
help='Start at epoch # (relevant for learning rate decay)')
parser.add_argument('--checkpoint_epochs', type=int, default=1,
help='Save checkpoint every n epochs (default 1), 0 to save no checkpoints')
parser.add_argument('--load_path', help='Path to load model parameters and optimizer state from')
parser.add_argument('--resume', help='Resume from previous checkpoint file')
parser.add_argument('--no_tensorboard', action='store_true', help='Disable logging TensorBoard files')
parser.add_argument('--no_progress_bar', action='store_true', help='Disable progress bar')
opts = parser.parse_args(args)
opts.use_cuda = torch.cuda.is_available() and not opts.no_cuda
opts.run_name = "{}_{}".format(opts.run_name, time.strftime("%Y%m%dT%H%M%S"))
opts.save_dir = os.path.join(
opts.output_dir,
"{}_{}".format(opts.problem, opts.graph_size),
opts.run_name
)
if opts.bl_warmup_epochs is None:
opts.bl_warmup_epochs = 1 if opts.baseline == 'rollout' else 0
assert (opts.bl_warmup_epochs == 0) or (opts.baseline == 'rollout')
assert opts.epoch_size % opts.batch_size == 0, "Epoch size must be integer multiple of batch size!"
return opts
|
# -*- coding: utf-8 -*-
info = {
"%%number-times": {
"1": "isáng;",
"2": "dalawáng;",
"3": "tatlóng;",
"4": "ápat na;",
"5": "limáng;",
"6": "anim na;",
"7": "pitóng;",
"8": "walóng;",
"9": "siyám na;",
"10": "sampûng;",
"(11, 19)": "labíng->>;",
"(20, 99)": "<%%number-times< pû[’t >>];",
"(100, 999)": "<%%number-times< daán[ at >>];",
"(1000, 'inf')": "<%%number-times< libó[’t >>];"
},
"%spellout-cardinal": {
"0": "walâ;",
"1": "isá;",
"2": "dalawá;",
"3": "tatló;",
"4": "ápat;",
"5": "limá;",
"6": "anim;",
"7": "pitó;",
"8": "waló;",
"9": "siyám;",
"10": "sampû;",
"(11, 19)": "labíng->>;",
"(20, 99)": "<%%number-times< pû[’t >>];",
"(100, 999)": "<%%number-times< daán[ at >>];",
"(1000, 999999)": "<%%number-times< libó[’t >>];",
"(1000000, 999999999)": "<%%number-times< milyón[ at >>];",
"(1000000000, 999999999999)": "<%%number-times< bilyón[ at >>];",
"(1000000000000, 999999999999999)": "<%%number-times< trilyón[ at >>];",
"(1000000000000000, 999999999999999999)": "<%%number-times< katrilyón[ at >>];",
"(1000000000000000000, 'inf')": "=#,##0=;"
},
"%spellout-numbering": {
"(0, 'inf')": "=%spellout-cardinal=;"
},
"%spellout-numbering-year": {
"(0, 'inf')": "=%spellout-numbering=;"
},
"%spellout-ordinal": {
"(0, 'inf')": "ika =%spellout-cardinal=;"
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file grid_generator-inl.h
* \brief
* The operator generate sampling grid
* \author Xu Dong
*/
#ifndef MXNET_OPERATOR_GRID_GENERATOR_INL_H_
#define MXNET_OPERATOR_GRID_GENERATOR_INL_H_
#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <mxnet/operator.h>
#include <vector>
#include <map>
#include <utility>
#include <string>
#include "./mshadow_op.h"
#include "./operator_common.h"
namespace mxnet {
namespace op {
namespace grid {
enum GridGeneratorOpInputs {kData};
enum GridGeneratorOpOutputs {kOut, kGridDst};
enum GridGeneratorOpResource {kTempSpace};
enum GridGeneratorTransformType {kAffine, kWarp};
}
struct GridGeneratorParam : public dmlc::Parameter<GridGeneratorParam> {
int transform_type;
TShape target_shape;
DMLC_DECLARE_PARAMETER(GridGeneratorParam) {
int shape[] = {0, 0};
DMLC_DECLARE_FIELD(transform_type)
.add_enum("affine", grid::kAffine)
.add_enum("warp", grid::kWarp)
.describe("The type of transformation. For `affine`, input data should be an affine matrix "
"of size (batch, 6). For `warp`, input data should be an optical flow of size "
"(batch, 2, h, w).");
DMLC_DECLARE_FIELD(target_shape).set_default(TShape(shape, shape + 2))
.describe("Specifies the output shape (H, W). This is required if transformation type is "
"`affine`. If transformation type is `warp`, this parameter is ignored.");
}
};
template<typename xpu, typename DType>
class GridGeneratorOp : public Operator {
public:
explicit GridGeneratorOp(GridGeneratorParam p) {
this->param_ = p;
}
virtual void Forward(const OpContext &ctx,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &out_data,
const std::vector<TBlob> &aux_args) {
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(req[grid::kOut], kWriteTo);
CHECK_EQ(in_data.size(), 1U);
CHECK_EQ(out_data.size(), 2U);
Stream<xpu> *s = ctx.get_stream<xpu>();
switch (param_.transform_type) {
case grid::kAffine: {
// if transform_type is affine, data is affine matrix, input shape : (batch, 2, 3)
Tensor<xpu, 2, DType> out = out_data[grid::kOut].
get_with_shape<xpu, 2, DType>(Shape2(out_data[grid::kOut].shape_[0] * 2,
out_data[grid::kOut].shape_[2] * out_data[grid::kOut].shape_[3]), s);
Tensor<xpu, 2, DType> grid_dst = out_data[grid::kGridDst].get<xpu, 2, DType>(s);
Shape<2> data_shape = Shape2(out_data[grid::kOut].shape_[0] * 2, 3);
Tensor<xpu, 2, DType> data = in_data[grid::kData]
.get_with_shape<xpu, 2, DType>(data_shape, s);
// x, y, 1
grid_dst[0] = range<DType>(0, grid_dst.shape_[1]);
grid_dst[0] = grid_dst[0] - tcast<DType>(tcast<int>(grid_dst[0] /
scalar<DType>(param_.target_shape[1]))) * scalar<DType>(param_.target_shape[1]);
grid_dst[0] = scalar<DType>(-1.0) + grid_dst[0] *
scalar<DType>(2.0 / (param_.target_shape[1] - 1));
grid_dst[1] = range<DType>(0, grid_dst.shape_[1]);
grid_dst[1] = scalar<DType>(-1.0) + tcast<DType>(tcast<int>(grid_dst[1] /
scalar<DType>(param_.target_shape[1]))) * scalar<DType>(2.0/(param_.target_shape[0] - 1));
grid_dst[2] = scalar<DType>(1.0);
Assign(out, req[grid::kOut], dot(data, grid_dst));
break;
}
// Warping transformation
case grid::kWarp: {
// if transform_type is warp, data is optical flow, input shape : (batch, 2, height, width)
// grid_src = grid_dst + optical flow
Tensor<xpu, 4, DType> data = in_data[grid::kData].get<xpu, 4, DType>(s);
Tensor<xpu, 4, DType> out = out_data[grid::kOut].get<xpu, 4, DType>(s);
// grid_dst : (2, H, W)
Tensor<xpu, 3, DType> grid_dst = out_data[grid::kGridDst].get<xpu, 3, DType>(s);
Tensor<xpu, 2, DType> workspace = ctx.requested[grid::kTempSpace]
.get_space_typed<xpu, 2, DType>(Shape2(2, 1), s);
grid_dst[0] = repmat(range<DType>(0, data.size(3)), data.size(2));
grid_dst[1] = reshape(range<DType>(0, data.size(2), 1, data.size(3)),
Shape2(data.size(2), data.size(3)));
workspace[0] = scalar<DType>((DType(data.size(3)) - 1.0) / 2.0);
workspace[1] = scalar<DType>((DType(data.size(2)) - 1.0) / 2.0);
Assign(out, req[grid::kOut],
(data + broadcast_with_axis(grid_dst, -1, data.shape_[0])) /
broadcast_to(reshape(workspace, Shape4(1, 2, 1, 1)),
TShape(data.shape_)) - scalar<DType>(1));
break;
}
}
}
virtual void Backward(const OpContext &ctx,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &in_data,
const std::vector<TBlob> &out_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &in_grad,
const std::vector<TBlob> &aux_args) {
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(in_data.size(), 1U);
CHECK_EQ(out_data.size(), 2U);
Stream<xpu> *s = ctx.get_stream<xpu>();
switch (param_.transform_type) {
case grid::kAffine: {
Tensor<xpu, 2, DType> grid_dst = out_data[grid::kGridDst].get<xpu, 2, DType>(s);
Shape<2> data_shape = Shape2(in_grad[grid::kData].shape_[0] * 2, 3);
Tensor<xpu, 2, DType> gdata = in_grad[grid::kData]
.get_with_shape<xpu, 2, DType>(data_shape, s);
Shape<2> grad_shape = Shape2(out_grad[grid::kOut].shape_[0] * 2,
param_.target_shape[0] * param_.target_shape[1]);
Tensor<xpu, 2, DType> grad = out_grad[grid::kOut]
.get_with_shape<xpu, 2, DType>(grad_shape, s);
// grad : (batch * 2, H * W) grid_dst.T : (H * W, 3)
Assign(gdata, req[grid::kData] , dot(grad, grid_dst.T()));
break;
}
case grid::kWarp: {
Tensor<xpu, 4, DType> grad = out_grad[grid::kOut].get<xpu, 4, DType>(s);
Tensor<xpu, 4, DType> gdata = in_grad[grid::kData].get<xpu, 4, DType>(s);
Tensor<xpu, 2, DType> workspace = ctx.requested[grid::kTempSpace]
.get_space_typed<xpu, 2, DType>(Shape2(2, 1), s);
workspace[0] = scalar<DType>((DType(gdata.size(3)) - 1.0) / 2.0);
workspace[1] = scalar<DType>((DType(gdata.size(2)) - 1.0) / 2.0);
Assign(gdata, req[grid::kData],
grad / broadcast_to(reshape(workspace, Shape4(1, 2, 1, 1)),
TShape(gdata.shape_)));
break;
}
}
}
private:
GridGeneratorParam param_;
}; // class GridGeneratorOp
template<typename xpu>
Operator* CreateOp(GridGeneratorParam param, int dtype);
#if DMLC_USE_CXX11
class GridGeneratorProp : public OperatorProperty {
public:
int NumVisibleOutputs() const override {
return 1;
}
int NumOutputs() const override {
return 2;
}
std::vector<std::string> ListArguments() const override {
return {"data"};
}
std::vector<std::string> ListOutputs() const override {
return {"output", "grid_dst"};
}
void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) override {
param_.Init(kwargs);
}
std::map<std::string, std::string> GetParams() const override {
return param_.__DICT__();
}
bool InferShape(std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape,
std::vector<TShape> *aux_shape) const override {
using namespace mshadow;
CHECK_EQ(in_shape->size(), 1U) << "Input:[data]";
const TShape &lshape = (*in_shape)[grid::kData];
if (lshape.ndim() == 0) return false;
out_shape->clear();
switch (param_.transform_type) {
case grid::kAffine: {
CHECK_EQ(lshape.ndim(), 2U) \
<< "if transform_type is affine, data is affine matrix"
"affine matrix should be 2D in batch-num_hidden";
CHECK_EQ(lshape[1], 6U) << "incorrect data shape[1], should be 6";
CHECK_GT(param_.target_shape[0], 0U) \
<< "incorrect target_shape: " << param_.target_shape[0];
CHECK_GT(param_.target_shape[1], 0U) \
<< "incorrect target_shape: " << param_.target_shape[1];
out_shape->push_back(Shape4(lshape[0], 2, param_.target_shape[0], param_.target_shape[1]));
out_shape->push_back(Shape2(3, param_.target_shape[0] * param_.target_shape[1]));
break;
}
case grid::kWarp: {
CHECK_EQ(lshape.ndim(), 4U) \
<< "if transform_type is warp, data is optical flow"
"optical flow should be 4D in batch-num_hidden-y-x";
CHECK_EQ(lshape[1], 2U) << "incorrect data shape[1], should be 2";
out_shape->push_back(lshape);
out_shape->push_back(Shape3(2, lshape[2], lshape[3]));
break;
}
}
return true;
}
bool InferType(std::vector<int> *in_type,
std::vector<int> *out_type,
std::vector<int> *aux_type) const override {
int dtype = -1;
for (size_t i = 0; i < in_type->size(); ++i) {
if (dtype == -1) {
dtype = in_type->at(i);
} else {
CHECK(in_type->at(i) == dtype ||
in_type->at(i) == -1) <<
"Non-uniform data type in GridGenerator";
}
}
if (dtype == -1) {
LOG(FATAL) << "Not enough information to infer type in GridGenerator.";
return false;
}
size_t nin = this->ListArguments().size();
in_type->clear();
for (size_t i = 0; i < nin; ++i) in_type->push_back(dtype);
size_t naux = this->ListAuxiliaryStates().size();
aux_type->clear();
for (size_t i = 0; i < naux; ++i) aux_type->push_back(dtype);
size_t nout = this->ListOutputs().size();
out_type->clear();
for (size_t i = 0; i < nout; ++i) out_type->push_back(dtype);
return true;
}
OperatorProperty* Copy() const override {
auto ptr = new GridGeneratorProp();
ptr->param_ = param_;
return ptr;
}
std::string TypeString() const override {
return "GridGenerator";
}
std::vector<int> DeclareBackwardDependency(
const std::vector<int> &out_grad,
const std::vector<int> &in_data,
const std::vector<int> &out_data) const override {
switch (param_.transform_type) {
case grid::kAffine: {
return {out_grad[grid::kOut],
out_data[grid::kGridDst]};
}
case grid::kWarp: {
return {out_grad[grid::kOut]};
}
}
return {};
}
std::vector<ResourceRequest> ForwardResource(
const std::vector<TShape> &in_shape) const override {
switch (param_.transform_type) {
case grid::kAffine: {
return{};
}
case grid::kWarp: {
return{ ResourceRequest::kTempSpace };
}
}
return{};
}
std::vector<ResourceRequest> BackwardResource(
const std::vector<TShape> &in_shape) const override {
switch (param_.transform_type) {
case grid::kAffine: {
return {};
}
case grid::kWarp: {
return {ResourceRequest::kTempSpace};
}
}
return {};
}
Operator* CreateOperator(Context ctx) const override {
LOG(FATAL) << "Not Implemented.";
return NULL;
}
Operator* CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape,
std::vector<int> *in_type) const override;
private:
GridGeneratorParam param_;
}; // class GridGeneratorProp
#endif // DMLC_USE_CXX11
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_GRID_GENERATOR_INL_H_
|
const fs = require('fs')
const sax = require("sax")
const http = require('http')
const moment = require('moment')
moment.locale('en')
const itemTemplate = {
episode: '',
status: 'PUBLISHED',
title: '',
description: '',
guid: '',
pubDate: '',
mediaFileName: '',
mediaSize: '',
mediaDuration: '',
mediaType: '',
imageUrl: '',
explicit: '',
author: '',
creator: '',
downloadTotal: 0
}
const items = []
const saxStream = sax.createStream(false, {
trim: true,
normalize: true,
lowercase: true
})
saxStream.on('error', (e) => {
// unhandled errors will throw, since this is a proper node
// event emitter.
console.error("error!", e)
// clear the error
this._parser.error = null
this._parser.resume()
})
let currentItem = undefined
let currentTag = undefined
saxStream.on('opentag', (node) => {
//console.log(node.name)
currentTag = node.name
if (currentTag == 'item') {
//console.log('new item')
currentItem = Object.assign({}, itemTemplate)
items.push(currentItem)
}
if (!currentItem) return
if (currentTag == 'enclosure') {
currentItem.mediaFileName = node.attributes.url
currentItem.mediaSize = node.attributes.length
currentItem.mediaType = node.attributes.type
}
})
const setData = (data) => {
//console.log(`[${currentTag}]: ${data}`)
if (!currentItem) return
if (currentTag == 'title') {
currentItem.title = data
}
if (currentTag == 'description') {
currentItem.description = data
}
if (currentTag == 'guid') {
currentItem.guid = data
}
if (currentTag == 'dc:creator') {
currentItem.creator = data
}
if (currentTag == 'pubdate') {
//RSS format : RFC 2822
//mongo format : ISO
currentItem.pubDate = moment(data).toISOString()
}
if (currentTag == 'itunes:explicit') {
currentItem.explicit = data
}
if (currentTag == 'itunes:duration') {
currentItem.mediaDuration = data
}
if (currentTag == 'itunes:author') {
currentItem.author = data
}
if (currentTag == 'itunes:episode') {
currentItem.episode = data
}
}
saxStream.on('cdata', (data) => {
setData(data)
})
saxStream.on('text', (data) => {
setData(data)
})
const wait = (ms) => {
return new Promise((resolve, reject) => {
return setTimeout(() => resolve(), ms)
})
}
const getPodCloudRedirection = (url) => {
return new Promise((resolve, reject) => {
try {
http.get(url, (res) => {
const {
statusCode
} = res;
if (statusCode != 302) {
reject(statusCode)
return
}
resolve(res.headers.location)
})
} catch (e) {
reject(e)
}
})
}
saxStream.on('end', async () => {
//"mediaFileName": "http://stats.podcloud.fr/lavis-des-moutons/lavis-des-moutons-ep-081-bonjour-mathilde-linterview-live-at-podrennes/enclosure.mp3?p=f",
console.log('Guess missing episode number')
for (let item of items) {
//console.log(item.mediaFileName)
//console.log(item.episode)
if (item.mediaFileName == '') {
if (item.episode == '') item.episode = 'hs-txt-1'
} else {
//http://stats.podcloud.fr/lavis-des-moutons/lavis-des-moutons-ep-083-1-y-croire-ou-etre-lucide/enclosure.mp3?p=f
//http://stats.podcloud.fr/lavis-des-moutons/lavis-des-moutons-ep-180-b-au-fond-je-crois-que-la-terre-est-ronde/enclosure.mp3?p=f
//http://stats.podcloud.fr/lavis-des-moutons/lavis-des-moutons-ep-066-audio-opinion-1-app-de-podcastage-ios/enclosure.mp3?p=f
//http://stats.podcloud.fr/lavis-des-moutons/lavis-des-moutons-ep-066-video-opinion-1-app-de-podcastage-ios/enclosure.m4v?p=f
let stringToRemove = 'http://stats.podcloud.fr/lavis-des-moutons/lavis-des-moutons-ep-'
if (item.mediaFileName.startsWith(stringToRemove)) {
let start = stringToRemove.length
let end = item.mediaFileName.indexOf('-', start + 1)
let num = item.mediaFileName.substring(start, end)
if (num.charAt(0) == '0') num = num.substring(1)
if (num.charAt(0) == '0') num = num.substring(1)
// cas particuliers
if (item.mediaFileName.substring(start, start + 5) == '083-1') {
num = '83b'
}
if (item.mediaFileName.substring(start, start + 5) == '180-b') {
num = '180b'
}
if (item.mediaFileName.substring(start, start + 9) == '066-audio') {
num = '66'
}
if (item.mediaFileName.substring(start, start + 9) == '066-video') {
num = '66b'
}
if (item.episode == '') {
item.episode = num
} else {
if (item.episode != num) {
console.log(' Warning. episode: ' + item.episode + ' num:' + num)
item.episode = num
}
}
} else {
console.log(' !!!!!!!!!!!!!!!!!! WRONG start string')
}
}
}
console.log('Get original media url')
for (let item of items) {
//console.log(item.mediaFileName)
if (item.mediaFileName) {
try {
let url = await getPodCloudRedirection(item.mediaFileName)
let stringToRemove = 'http://lavis-des-moutons.fr/mp3/'
if (url.startsWith(stringToRemove)) {
item.mediaFileName = url.substring(stringToRemove.length)
//console.log(item.mediaFileName)
} else {
console.log(' !!!!!!!!!!!!!!!!!! WRONG start string')
}
} catch (e) {
console.log(e)
} finally {
await wait(0)
}
}
}
fs.writeFileSync('ladm-db.json', JSON.stringify(items, null, ' '))
})
const filename = "rss-podcloud.xml"
console.log('Parsing ' + filename)
fs.createReadStream(filename).pipe(saxStream)
|
from django.test import TestCase
from posthog.models import Event
from posthog.api.test.base import BaseTest
from posthog.utils import relative_date_parse, properties_to_Q
from freezegun import freeze_time # type: ignore
class TestRelativeDateParse(TestCase):
@freeze_time('2020-01-31')
def test_day(self):
self.assertEqual(relative_date_parse('dStart').strftime("%Y-%m-%d"), '2020-01-31')
self.assertEqual(relative_date_parse('-1d').strftime("%Y-%m-%d"), '2020-01-30')
self.assertEqual(relative_date_parse('-2d').strftime("%Y-%m-%d"), '2020-01-29')
@freeze_time('2020-01-31')
def test_month(self):
self.assertEqual(relative_date_parse('-1m').strftime("%Y-%m-%d"), '2019-12-31')
self.assertEqual(relative_date_parse('-2m').strftime("%Y-%m-%d"), '2019-11-30')
self.assertEqual(relative_date_parse('mStart').strftime("%Y-%m-%d"), '2020-01-01')
self.assertEqual(relative_date_parse('-1mStart').strftime("%Y-%m-%d"), '2019-12-01')
self.assertEqual(relative_date_parse('-2mStart').strftime("%Y-%m-%d"), '2019-11-01')
self.assertEqual(relative_date_parse('-1mEnd').strftime("%Y-%m-%d"), '2019-12-31')
self.assertEqual(relative_date_parse('-2mEnd').strftime("%Y-%m-%d"), '2019-11-30')
@freeze_time('2020-01-31')
def test_year(self):
self.assertEqual(relative_date_parse('-1y').strftime("%Y-%m-%d"), '2019-01-31')
self.assertEqual(relative_date_parse('-2y').strftime("%Y-%m-%d"), '2018-01-31')
self.assertEqual(relative_date_parse('yStart').strftime("%Y-%m-%d"), '2020-01-01')
self.assertEqual(relative_date_parse('-1yStart').strftime("%Y-%m-%d"), '2019-01-01')
@freeze_time('2020-01-31')
def test_normal_date(self):
self.assertEqual(relative_date_parse('2019-12-31').strftime("%Y-%m-%d"), '2019-12-31')
class TestPropertiesToQ(BaseTest):
def test_simple(self):
Event.objects.create(team=self.team, event='$pageview')
Event.objects.create(team=self.team, event='$pageview', properties={'$current_url': 'https://whatever.com'})
properties = {'$current_url': 'https://whatever.com'}
events = Event.objects.filter(properties_to_Q(properties))
self.assertEqual(events.count(), 1)
def test_contains(self):
Event.objects.create(team=self.team, event='$pageview')
event2 = Event.objects.create(team=self.team, event='$pageview', properties={'$current_url': 'https://whatever.com'})
properties = {'$current_url__icontains': 'whatever'}
events = Event.objects.filter(properties_to_Q(properties))
self.assertEqual(events.get(), event2)
def test_is_not(self):
event1 = Event.objects.create(team=self.team, event='$pageview')
event2 = Event.objects.create(team=self.team, event='$pageview', properties={'$current_url': 'https://something.com'})
Event.objects.create(team=self.team, event='$pageview', properties={'$current_url': 'https://whatever.com'})
properties = {'$current_url__is_not': 'https://whatever.com'}
events = Event.objects.filter(properties_to_Q(properties))
self.assertEqual(events[0], event1)
self.assertEqual(events[1], event2)
self.assertEqual(len(events), 2)
def test_does_not_contain(self):
event1 = Event.objects.create(team=self.team, event='$pageview')
event2 = Event.objects.create(team=self.team, event='$pageview', properties={'$current_url': 'https://something.com'})
Event.objects.create(team=self.team, event='$pageview', properties={'$current_url': 'https://whatever.com'})
properties = {'$current_url__not_icontains': 'whatever.com'}
events = Event.objects.filter(properties_to_Q(properties))
self.assertEqual(events[0], event1)
self.assertEqual(events[1], event2)
self.assertEqual(len(events), 2)
|
/*'use strict';
// import all listener files so they can attach to the DOM
import './listeners/inputting.js';
import './listeners/change-separator.js';
// does your project have code that executes when the document or window are ready?
// that code can go here
import { data } from './data.js';
document.getElementById('separator-input').value = data.separator;
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['KeyRingIAMPolicyArgs', 'KeyRingIAMPolicy']
@pulumi.input_type
class KeyRingIAMPolicyArgs:
def __init__(__self__, *,
key_ring_id: pulumi.Input[str],
policy_data: pulumi.Input[str]):
"""
The set of arguments for constructing a KeyRingIAMPolicy resource.
:param pulumi.Input[str] key_ring_id: The key ring ID, in the form
`{project_id}/{location_name}/{key_ring_name}` or
`{location_name}/{key_ring_name}`. In the second form, the provider's
project setting will be used as a fallback.
:param pulumi.Input[str] policy_data: The policy data generated by
a `organizations.get_iam_policy` data source.
"""
pulumi.set(__self__, "key_ring_id", key_ring_id)
pulumi.set(__self__, "policy_data", policy_data)
@property
@pulumi.getter(name="keyRingId")
def key_ring_id(self) -> pulumi.Input[str]:
"""
The key ring ID, in the form
`{project_id}/{location_name}/{key_ring_name}` or
`{location_name}/{key_ring_name}`. In the second form, the provider's
project setting will be used as a fallback.
"""
return pulumi.get(self, "key_ring_id")
@key_ring_id.setter
def key_ring_id(self, value: pulumi.Input[str]):
pulumi.set(self, "key_ring_id", value)
@property
@pulumi.getter(name="policyData")
def policy_data(self) -> pulumi.Input[str]:
"""
The policy data generated by
a `organizations.get_iam_policy` data source.
"""
return pulumi.get(self, "policy_data")
@policy_data.setter
def policy_data(self, value: pulumi.Input[str]):
pulumi.set(self, "policy_data", value)
@pulumi.input_type
class _KeyRingIAMPolicyState:
def __init__(__self__, *,
etag: Optional[pulumi.Input[str]] = None,
key_ring_id: Optional[pulumi.Input[str]] = None,
policy_data: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering KeyRingIAMPolicy resources.
:param pulumi.Input[str] etag: (Computed) The etag of the key ring's IAM policy.
:param pulumi.Input[str] key_ring_id: The key ring ID, in the form
`{project_id}/{location_name}/{key_ring_name}` or
`{location_name}/{key_ring_name}`. In the second form, the provider's
project setting will be used as a fallback.
:param pulumi.Input[str] policy_data: The policy data generated by
a `organizations.get_iam_policy` data source.
"""
if etag is not None:
pulumi.set(__self__, "etag", etag)
if key_ring_id is not None:
pulumi.set(__self__, "key_ring_id", key_ring_id)
if policy_data is not None:
pulumi.set(__self__, "policy_data", policy_data)
@property
@pulumi.getter
def etag(self) -> Optional[pulumi.Input[str]]:
"""
(Computed) The etag of the key ring's IAM policy.
"""
return pulumi.get(self, "etag")
@etag.setter
def etag(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "etag", value)
@property
@pulumi.getter(name="keyRingId")
def key_ring_id(self) -> Optional[pulumi.Input[str]]:
"""
The key ring ID, in the form
`{project_id}/{location_name}/{key_ring_name}` or
`{location_name}/{key_ring_name}`. In the second form, the provider's
project setting will be used as a fallback.
"""
return pulumi.get(self, "key_ring_id")
@key_ring_id.setter
def key_ring_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "key_ring_id", value)
@property
@pulumi.getter(name="policyData")
def policy_data(self) -> Optional[pulumi.Input[str]]:
"""
The policy data generated by
a `organizations.get_iam_policy` data source.
"""
return pulumi.get(self, "policy_data")
@policy_data.setter
def policy_data(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "policy_data", value)
class KeyRingIAMPolicy(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
key_ring_id: Optional[pulumi.Input[str]] = None,
policy_data: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
Three different resources help you manage your IAM policy for KMS key ring. Each of these resources serves a different use case:
* `kms.KeyRingIAMPolicy`: Authoritative. Sets the IAM policy for the key ring and replaces any existing policy already attached.
* `kms.KeyRingIAMBinding`: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other roles within the IAM policy for the key ring are preserved.
* `kms.KeyRingIAMMember`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the key ring are preserved.
> **Note:** `kms.KeyRingIAMPolicy` **cannot** be used in conjunction with `kms.KeyRingIAMBinding` and `kms.KeyRingIAMMember` or they will fight over what your policy should be.
> **Note:** `kms.KeyRingIAMBinding` resources **can be** used in conjunction with `kms.KeyRingIAMMember` resources **only if** they do not grant privilege to the same role.
## google\_kms\_key\_ring\_iam\_policy
```python
import pulumi
import pulumi_gcp as gcp
keyring = gcp.kms.KeyRing("keyring", location="global")
admin = gcp.organizations.get_iam_policy(bindings=[gcp.organizations.GetIAMPolicyBindingArgs(
role="roles/editor",
members=["user:jane@example.com"],
)])
key_ring = gcp.kms.KeyRingIAMPolicy("keyRing",
key_ring_id=keyring.id,
policy_data=admin.policy_data)
```
With IAM Conditions:
```python
import pulumi
import pulumi_gcp as gcp
keyring = gcp.kms.KeyRing("keyring", location="global")
admin = gcp.organizations.get_iam_policy(bindings=[gcp.organizations.GetIAMPolicyBindingArgs(
role="roles/editor",
members=["user:jane@example.com"],
condition=gcp.organizations.GetIAMPolicyBindingConditionArgs(
title="expires_after_2019_12_31",
description="Expiring at midnight of 2019-12-31",
expression="request.time < timestamp(\"2020-01-01T00:00:00Z\")",
),
)])
key_ring = gcp.kms.KeyRingIAMPolicy("keyRing",
key_ring_id=keyring.id,
policy_data=admin.policy_data)
```
## google\_kms\_key\_ring\_iam\_binding
```python
import pulumi
import pulumi_gcp as gcp
key_ring = gcp.kms.KeyRingIAMBinding("keyRing",
key_ring_id="your-key-ring-id",
members=["user:jane@example.com"],
role="roles/editor")
```
With IAM Conditions:
```python
import pulumi
import pulumi_gcp as gcp
key_ring = gcp.kms.KeyRingIAMBinding("keyRing",
condition=gcp.kms.KeyRingIAMBindingConditionArgs(
description="Expiring at midnight of 2019-12-31",
expression="request.time < timestamp(\"2020-01-01T00:00:00Z\")",
title="expires_after_2019_12_31",
),
key_ring_id="your-key-ring-id",
members=["user:jane@example.com"],
role="roles/editor")
```
## google\_kms\_key\_ring\_iam\_member
```python
import pulumi
import pulumi_gcp as gcp
key_ring = gcp.kms.KeyRingIAMMember("keyRing",
key_ring_id="your-key-ring-id",
member="user:jane@example.com",
role="roles/editor")
```
With IAM Conditions:
```python
import pulumi
import pulumi_gcp as gcp
key_ring = gcp.kms.KeyRingIAMMember("keyRing",
condition=gcp.kms.KeyRingIAMMemberConditionArgs(
description="Expiring at midnight of 2019-12-31",
expression="request.time < timestamp(\"2020-01-01T00:00:00Z\")",
title="expires_after_2019_12_31",
),
key_ring_id="your-key-ring-id",
member="user:jane@example.com",
role="roles/editor")
```
## Import
IAM member imports use space-delimited identifiers; the resource in question, the role, and the account.
This member resource can be imported using the `key_ring_id`, role, and account e.g.
```sh
$ pulumi import gcp:kms/keyRingIAMPolicy:KeyRingIAMPolicy key_ring_iam "your-project-id/location-name/key-ring-name roles/viewer user:foo@example.com"
```
IAM binding imports use space-delimited identifiers; the resource in question and the role.
This binding resource can be imported using the `key_ring_id` and role, e.g.
```sh
$ pulumi import gcp:kms/keyRingIAMPolicy:KeyRingIAMPolicy key_ring_iam "your-project-id/location-name/key-ring-name roles/viewer"
```
IAM policy imports use the identifier of the resource in question.
This policy resource can be imported using the `key_ring_id`, e.g.
```sh
$ pulumi import gcp:kms/keyRingIAMPolicy:KeyRingIAMPolicy key_ring_iam your-project-id/location-name/key-ring-name
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] key_ring_id: The key ring ID, in the form
`{project_id}/{location_name}/{key_ring_name}` or
`{location_name}/{key_ring_name}`. In the second form, the provider's
project setting will be used as a fallback.
:param pulumi.Input[str] policy_data: The policy data generated by
a `organizations.get_iam_policy` data source.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: KeyRingIAMPolicyArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Three different resources help you manage your IAM policy for KMS key ring. Each of these resources serves a different use case:
* `kms.KeyRingIAMPolicy`: Authoritative. Sets the IAM policy for the key ring and replaces any existing policy already attached.
* `kms.KeyRingIAMBinding`: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other roles within the IAM policy for the key ring are preserved.
* `kms.KeyRingIAMMember`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the key ring are preserved.
> **Note:** `kms.KeyRingIAMPolicy` **cannot** be used in conjunction with `kms.KeyRingIAMBinding` and `kms.KeyRingIAMMember` or they will fight over what your policy should be.
> **Note:** `kms.KeyRingIAMBinding` resources **can be** used in conjunction with `kms.KeyRingIAMMember` resources **only if** they do not grant privilege to the same role.
## google\_kms\_key\_ring\_iam\_policy
```python
import pulumi
import pulumi_gcp as gcp
keyring = gcp.kms.KeyRing("keyring", location="global")
admin = gcp.organizations.get_iam_policy(bindings=[gcp.organizations.GetIAMPolicyBindingArgs(
role="roles/editor",
members=["user:jane@example.com"],
)])
key_ring = gcp.kms.KeyRingIAMPolicy("keyRing",
key_ring_id=keyring.id,
policy_data=admin.policy_data)
```
With IAM Conditions:
```python
import pulumi
import pulumi_gcp as gcp
keyring = gcp.kms.KeyRing("keyring", location="global")
admin = gcp.organizations.get_iam_policy(bindings=[gcp.organizations.GetIAMPolicyBindingArgs(
role="roles/editor",
members=["user:jane@example.com"],
condition=gcp.organizations.GetIAMPolicyBindingConditionArgs(
title="expires_after_2019_12_31",
description="Expiring at midnight of 2019-12-31",
expression="request.time < timestamp(\"2020-01-01T00:00:00Z\")",
),
)])
key_ring = gcp.kms.KeyRingIAMPolicy("keyRing",
key_ring_id=keyring.id,
policy_data=admin.policy_data)
```
## google\_kms\_key\_ring\_iam\_binding
```python
import pulumi
import pulumi_gcp as gcp
key_ring = gcp.kms.KeyRingIAMBinding("keyRing",
key_ring_id="your-key-ring-id",
members=["user:jane@example.com"],
role="roles/editor")
```
With IAM Conditions:
```python
import pulumi
import pulumi_gcp as gcp
key_ring = gcp.kms.KeyRingIAMBinding("keyRing",
condition=gcp.kms.KeyRingIAMBindingConditionArgs(
description="Expiring at midnight of 2019-12-31",
expression="request.time < timestamp(\"2020-01-01T00:00:00Z\")",
title="expires_after_2019_12_31",
),
key_ring_id="your-key-ring-id",
members=["user:jane@example.com"],
role="roles/editor")
```
## google\_kms\_key\_ring\_iam\_member
```python
import pulumi
import pulumi_gcp as gcp
key_ring = gcp.kms.KeyRingIAMMember("keyRing",
key_ring_id="your-key-ring-id",
member="user:jane@example.com",
role="roles/editor")
```
With IAM Conditions:
```python
import pulumi
import pulumi_gcp as gcp
key_ring = gcp.kms.KeyRingIAMMember("keyRing",
condition=gcp.kms.KeyRingIAMMemberConditionArgs(
description="Expiring at midnight of 2019-12-31",
expression="request.time < timestamp(\"2020-01-01T00:00:00Z\")",
title="expires_after_2019_12_31",
),
key_ring_id="your-key-ring-id",
member="user:jane@example.com",
role="roles/editor")
```
## Import
IAM member imports use space-delimited identifiers; the resource in question, the role, and the account.
This member resource can be imported using the `key_ring_id`, role, and account e.g.
```sh
$ pulumi import gcp:kms/keyRingIAMPolicy:KeyRingIAMPolicy key_ring_iam "your-project-id/location-name/key-ring-name roles/viewer user:foo@example.com"
```
IAM binding imports use space-delimited identifiers; the resource in question and the role.
This binding resource can be imported using the `key_ring_id` and role, e.g.
```sh
$ pulumi import gcp:kms/keyRingIAMPolicy:KeyRingIAMPolicy key_ring_iam "your-project-id/location-name/key-ring-name roles/viewer"
```
IAM policy imports use the identifier of the resource in question.
This policy resource can be imported using the `key_ring_id`, e.g.
```sh
$ pulumi import gcp:kms/keyRingIAMPolicy:KeyRingIAMPolicy key_ring_iam your-project-id/location-name/key-ring-name
```
:param str resource_name: The name of the resource.
:param KeyRingIAMPolicyArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(KeyRingIAMPolicyArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
key_ring_id: Optional[pulumi.Input[str]] = None,
policy_data: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = KeyRingIAMPolicyArgs.__new__(KeyRingIAMPolicyArgs)
if key_ring_id is None and not opts.urn:
raise TypeError("Missing required property 'key_ring_id'")
__props__.__dict__["key_ring_id"] = key_ring_id
if policy_data is None and not opts.urn:
raise TypeError("Missing required property 'policy_data'")
__props__.__dict__["policy_data"] = policy_data
__props__.__dict__["etag"] = None
super(KeyRingIAMPolicy, __self__).__init__(
'gcp:kms/keyRingIAMPolicy:KeyRingIAMPolicy',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
etag: Optional[pulumi.Input[str]] = None,
key_ring_id: Optional[pulumi.Input[str]] = None,
policy_data: Optional[pulumi.Input[str]] = None) -> 'KeyRingIAMPolicy':
"""
Get an existing KeyRingIAMPolicy resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] etag: (Computed) The etag of the key ring's IAM policy.
:param pulumi.Input[str] key_ring_id: The key ring ID, in the form
`{project_id}/{location_name}/{key_ring_name}` or
`{location_name}/{key_ring_name}`. In the second form, the provider's
project setting will be used as a fallback.
:param pulumi.Input[str] policy_data: The policy data generated by
a `organizations.get_iam_policy` data source.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _KeyRingIAMPolicyState.__new__(_KeyRingIAMPolicyState)
__props__.__dict__["etag"] = etag
__props__.__dict__["key_ring_id"] = key_ring_id
__props__.__dict__["policy_data"] = policy_data
return KeyRingIAMPolicy(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def etag(self) -> pulumi.Output[str]:
"""
(Computed) The etag of the key ring's IAM policy.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter(name="keyRingId")
def key_ring_id(self) -> pulumi.Output[str]:
"""
The key ring ID, in the form
`{project_id}/{location_name}/{key_ring_name}` or
`{location_name}/{key_ring_name}`. In the second form, the provider's
project setting will be used as a fallback.
"""
return pulumi.get(self, "key_ring_id")
@property
@pulumi.getter(name="policyData")
def policy_data(self) -> pulumi.Output[str]:
"""
The policy data generated by
a `organizations.get_iam_policy` data source.
"""
return pulumi.get(self, "policy_data")
|
"""
A number is considered perfect if its digits sum up to exactly 10.
Given a positive integer n, return the n-th perfect number.
For example, given 1, you should return 19. Given 2, you should return 28.
"""
import random
import math
def get_sum_of_digs(x: int) -> int:
s: int = 0
while True:
while x:
s += x % 10
x = x // 10
if s <= 10:
return s
else:
x = s
s = 0
def perfect_number_brute_force(n: int) -> int:
"""
Start With 19 and add 9 to it. Verify the solution.
"""
if n < 1:
return 0
number: int = 19
if n == 1:
return number
while n > 1:
x = 0
while x != 10:
number += 9
x = get_sum_of_digs(number)
n -= 1
return number
def perfect_number_faster(n: int) -> int:
"""
The solution to the problem is an AP with a = 19 and d = 9.
There are some outliers such as 100, 1000, 10_000 ...
Therefore the final solution would be: 19 + (n-1+number_of_outliers)*9
Time Complexity: O(1)
Space Complexity: O(1)
"""
if n < 1:
return 0
nth_element = 19 + (n - 1) * 9
outliers = int(math.log10(nth_element)) - 1
return nth_element + outliers * 9
if __name__ == "__main__":
for _ in range(5):
n: int = random.randint(1, 1000)
print("N:", n)
print("brute force solution:", perfect_number_brute_force(n))
print("Faster solution:", perfect_number_faster(n))
|
from django.apps import AppConfig
class MaintenanceConfig(AppConfig):
name = "maintenance"
|
xs = {'foo', 'bar',<caret>
|
/**
* @fileoverview added by tsickle
* Generated from: src/material/icon/public-api.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { MatIconModule } from './icon-module';
export { MAT_ICON_LOCATION_FACTORY, MAT_ICON_LOCATION, MatIcon } from './icon';
export { getMatIconNameNotFoundError, getMatIconNoHttpProviderError, getMatIconFailedToSanitizeUrlError, getMatIconFailedToSanitizeLiteralError, ICON_REGISTRY_PROVIDER_FACTORY, MatIconRegistry, ICON_REGISTRY_PROVIDER } from './icon-registry';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljLWFwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3NyYy9tYXRlcmlhbC9pY29uL3B1YmxpYy1hcGkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7O0FBUUEsOEJBQWMsZUFBZSxDQUFDO0FBQzlCLHNFQUFjLFFBQVEsQ0FBQztBQUN2QixnT0FBYyxpQkFBaUIsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgTExDIEFsbCBSaWdodHMgUmVzZXJ2ZWQuXG4gKlxuICogVXNlIG9mIHRoaXMgc291cmNlIGNvZGUgaXMgZ292ZXJuZWQgYnkgYW4gTUlULXN0eWxlIGxpY2Vuc2UgdGhhdCBjYW4gYmVcbiAqIGZvdW5kIGluIHRoZSBMSUNFTlNFIGZpbGUgYXQgaHR0cHM6Ly9hbmd1bGFyLmlvL2xpY2Vuc2VcbiAqL1xuXG5leHBvcnQgKiBmcm9tICcuL2ljb24tbW9kdWxlJztcbmV4cG9ydCAqIGZyb20gJy4vaWNvbic7XG5leHBvcnQgKiBmcm9tICcuL2ljb24tcmVnaXN0cnknO1xuXG4iXX0=
|
/*! For license information please see 207e61d01b9a6e9d440f6c73e1b6c16da759b29a-53910a28a02fdba66c0a.js.LICENSE.txt */
(window.webpackJsonp=window.webpackJsonp||[]).push([[0],{"+ZrZ":function(t,e,r){"use strict";var n=r("8OQS"),i=r("TqRt");e.__esModule=!0,e.default=function(t){t.exit,t.entry,t.fade;var e=t.duration,r=n(t,["exit","entry","fade","duration"]),i=e||.8;return o.default.createElement(s.default,(0,a.default)({exit:{length:i,zIndex:1,trigger:function(t){var e=t.exit,r=t.node;return l({exit:e,node:r,direction:"out"})}},entry:{length:0,trigger:function(t){var e=t.exit,r=t.node;return l({exit:e,node:r,direction:"in"})}}},r,{__self:this,__source:{fileName:"/Users/tyler/Documents/GitHub/gatsby-plugins/transition-link/gatsby-plugin-transition-link/src/AniLink/Fade.js",lineNumber:36,columnNumber:3}}),r.children)};var a=i(r("pVnL")),o=i(r("q1tI")),s=i(r("plVc")),u=i(r("z/o8")),l=function(t){var e=t.exit.length,r=t.node,n=t.direction,i="out"===n?e+e/4:e,a="in"===n?1:0,o=document.scrollingElement&&document.scrollingElement.scrollTop||document.body.scrollTop||window.pageYOffset,s="out"===n?{overflowY:"hidden",height:"100vh",scrollTop:o}:{};return u.default.timeline().set(r,s).fromTo(r,{opacity:!a},{opacity:a,duration:i})}},"/d1K":function(t,e,r){"use strict";var n=r("q1tI"),i=r.n(n),a=r("Wbzz"),o=r("MUpH"),s=r("vOnD"),u=r("9eSz"),l=r.n(u),c=r("ibEc");function f(){var t=Object(o.a)(["\n height: 2.5rem;\n width: 2.5rem;\n "]);return f=function(){return t},t}var d=Object(s.c)(l.a).withConfig({displayName:"styled__AvatarWrapper",componentId:"sc-1y7bal3-0"})(["border-radius:50%;height:3.75rem;margin:auto;width:3.75rem;",""],c.a.lessThan("large")(f())),h=function(){var t=Object(a.useStaticQuery)("836162562").avatarImage;return i.a.createElement(d,{fluid:t.childImageSharp.fluid})},p=r("kOA+"),m=r.n(p);function g(){var t=Object(o.a)(["\n display: none;\n "]);return g=function(){return t},t}function v(){var t=Object(o.a)(["\n font-size: 0.8rem;\n margin-top: 0.2rem;\n "]);return v=function(){return t},t}function y(){var t=Object(o.a)(["\n font-size: 1.2rem;\n margin: 0 0 0 10px;\n "]);return y=function(){return t},t}function b(){var t=Object(o.a)(["\n display: flex;\n text-align: left;\n "]);return b=function(){return t},t}var _=s.c.section.withConfig({displayName:"styled__ProfileWrapper",componentId:"sc-14b63l5-0"})(["color:var(--texts);display:flex;flex-direction:column;"]),w=Object(s.c)(m.a).withConfig({displayName:"styled__ProfileLink",componentId:"sc-14b63l5-1"})(["color:var(--texts);text-decoration:none;transition:color 0.5s;"," &:hover{color:var(--higlight);}"],c.a.lessThan("large")(b())),x=s.c.h1.withConfig({displayName:"styled__ProfileAuthor",componentId:"sc-14b63l5-2"})(["font-size:1.5rem;margin:0.5rem auto 0.5rem;",""],c.a.lessThan("large")(y())),T=s.c.small.withConfig({displayName:"styled__ProfilePosition",componentId:"sc-14b63l5-3"})(["display:block;font-size:1.2rem;font-weight:300;",""],c.a.lessThan("large")(v())),k=s.c.p.withConfig({displayName:"styled__ProfileDescription",componentId:"sc-14b63l5-4"})(["font-size:1rem;font-weight:300;line-height:1.4;",""],c.a.lessThan("large")(g())),S=function(){return i.a.createElement(a.StaticQuery,{query:"2037742868",render:function(t){var e=t.site.siteMetadata,r=e.title,n=e.position,a=e.description;return i.a.createElement(_,null,i.a.createElement(w,{to:"/",cover:!0,direction:"left",bg:"var(--background)",duration:.6},i.a.createElement(h,null),i.a.createElement(x,null,r,i.a.createElement(T,null,n))),i.a.createElement(k,null,a))}})},O=r("pVnL"),C=r.n(O),E=r("Bop7"),A=n.forwardRef((function(t,e){return n.createElement(E.a,C()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{fillRule:"evenodd",d:"M12.026 2c-5.509 0-9.974 4.465-9.974 9.974 0 4.406 2.857 8.145 6.821 9.465.499.09.679-.217.679-.481 0-.237-.008-.865-.011-1.696-2.775.602-3.361-1.338-3.361-1.338-.452-1.152-1.107-1.459-1.107-1.459-.905-.619.069-.605.069-.605 1.002.07 1.527 1.028 1.527 1.028.89 1.524 2.336 1.084 2.902.829.091-.645.351-1.085.635-1.334-2.214-.251-4.542-1.107-4.542-4.93 0-1.087.389-1.979 1.024-2.675-.101-.253-.446-1.268.099-2.64 0 0 .837-.269 2.742 1.021a9.582 9.582 0 012.496-.336 9.554 9.554 0 012.496.336c1.906-1.291 2.742-1.021 2.742-1.021.545 1.372.203 2.387.099 2.64.64.696 1.024 1.587 1.024 2.675 0 3.833-2.33 4.675-4.552 4.922.355.308.675.916.675 1.846 0 1.334-.012 2.41-.012 2.737 0 .267.178.577.687.479C19.146 20.115 22 16.379 22 11.974 22 6.465 17.535 2 12.026 2z",clipRule:"evenodd"}))}));A.displayName="Github";var M=n.forwardRef((function(t,e){return n.createElement(E.a,C()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M19.633 7.997c.013.175.013.349.013.523 0 5.325-4.053 11.461-11.46 11.461-2.282 0-4.402-.661-6.186-1.809.324.037.636.05.973.05a8.07 8.07 0 005.001-1.721 4.036 4.036 0 01-3.767-2.793c.249.037.499.062.761.062.361 0 .724-.05 1.061-.137a4.027 4.027 0 01-3.23-3.953v-.05c.537.299 1.16.486 1.82.511a4.022 4.022 0 01-1.796-3.354c0-.748.199-1.434.548-2.032a11.457 11.457 0 008.306 4.215c-.062-.3-.1-.611-.1-.923a4.026 4.026 0 014.028-4.028c1.16 0 2.207.486 2.943 1.272a7.957 7.957 0 002.556-.973 4.02 4.02 0 01-1.771 2.22 8.073 8.073 0 002.319-.624 8.645 8.645 0 01-2.019 2.083z"}))}));M.displayName="Twitter";var P=n.forwardRef((function(t,e){return n.createElement(E.a,C()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M21.593 7.203a2.506 2.506 0 00-1.762-1.766C18.265 5.007 12 5 12 5s-6.264-.007-7.831.404a2.56 2.56 0 00-1.766 1.778c-.413 1.566-.417 4.814-.417 4.814s-.004 3.264.406 4.814c.23.857.905 1.534 1.763 1.765 1.582.43 7.83.437 7.83.437s6.265.007 7.831-.403a2.515 2.515 0 001.767-1.763c.414-1.565.417-4.812.417-4.812s.02-3.265-.407-4.831zM9.996 15.005l.005-6 5.207 3.005-5.212 2.995z"}))}));P.displayName="Youtube";var I=n.forwardRef((function(t,e){return n.createElement(E.a,C()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M8.625 8.063V3h6.75v5.063h-6.75zm6.75 2.812H21V21H3V10.875h5.625v5.063h6.75v-5.063z"}))}));I.displayName="Unsplash";var j=n.forwardRef((function(t,e){return n.createElement(E.a,C()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M11.999 7.377a4.623 4.623 0 100 9.248 4.623 4.623 0 000-9.248zm0 7.627a3.004 3.004 0 110-6.008 3.004 3.004 0 010 6.008z"}),n.createElement("circle",{cx:16.806,cy:7.207,r:1.078}),n.createElement("path",{d:"M20.533 6.111A4.605 4.605 0 0017.9 3.479a6.606 6.606 0 00-2.186-.42c-.963-.042-1.268-.054-3.71-.054s-2.755 0-3.71.054a6.554 6.554 0 00-2.184.42 4.6 4.6 0 00-2.633 2.632 6.585 6.585 0 00-.419 2.186c-.043.962-.056 1.267-.056 3.71 0 2.442 0 2.753.056 3.71.015.748.156 1.486.419 2.187a4.61 4.61 0 002.634 2.632 6.584 6.584 0 002.185.45c.963.042 1.268.055 3.71.055s2.755 0 3.71-.055a6.615 6.615 0 002.186-.419 4.613 4.613 0 002.633-2.633c.263-.7.404-1.438.419-2.186.043-.962.056-1.267.056-3.71s0-2.753-.056-3.71a6.581 6.581 0 00-.421-2.217zm-1.218 9.532a5.043 5.043 0 01-.311 1.688 2.987 2.987 0 01-1.712 1.711 4.985 4.985 0 01-1.67.311c-.95.044-1.218.055-3.654.055-2.438 0-2.687 0-3.655-.055a4.96 4.96 0 01-1.669-.311 2.985 2.985 0 01-1.719-1.711 5.08 5.08 0 01-.311-1.669c-.043-.95-.053-1.218-.053-3.654 0-2.437 0-2.686.053-3.655a5.038 5.038 0 01.311-1.687c.305-.789.93-1.41 1.719-1.712a5.01 5.01 0 011.669-.311c.951-.043 1.218-.055 3.655-.055s2.687 0 3.654.055a4.96 4.96 0 011.67.311 2.991 2.991 0 011.712 1.712 5.08 5.08 0 01.311 1.669c.043.951.054 1.218.054 3.655 0 2.436 0 2.698-.043 3.654h-.011z"}))}));j.displayName="Instagram";var R={Github:A,Twitter:M,Youtube:P,Unsplash:I,Instagram:j},N=[{label:"Github",url:"https://github.com/"},{label:"Twitter",url:"https://twitter.com/"},{label:"Youtube",url:"https://www.youtube.com/"},{label:"Instagram",url:"https://www.instagram.com/"},{label:"Unsplash",url:"https://unsplash.com/"}];function z(){var t=Object(o.a)(["\n display: none;\n "]);return z=function(){return t},t}var L=s.c.nav.withConfig({displayName:"styled__SocialLinksWrapper",componentId:"p41hl8-0"})(["margin:2rem auto;width:100%;",""],c.a.lessThan("large")(z())),D=s.c.ul.withConfig({displayName:"styled__SocialLinksList",componentId:"p41hl8-1"})(["align-items:center;display:flex;justify-content:space-around;list-style:none;"]),F=s.c.li.withConfig({displayName:"styled__SocialLinksItem",componentId:"p41hl8-2"})([""]),V=s.c.a.withConfig({displayName:"styled__SocialLinksLink",componentId:"p41hl8-3"})(["color:var(--texts);text-decoration:none;transition:color 0.5s;&:hover{color:var(--higlight);}"]),q=s.c.div.withConfig({displayName:"styled__IconWrapper",componentId:"p41hl8-4"})(["fill:#bbb;width:30px;height:30px;"]),B=function(){return i.a.createElement(L,null,i.a.createElement(D,null,N.map((function(t,e){var r=R[t.label];return i.a.createElement(F,{key:e},i.a.createElement(V,{href:t.url,title:t.label,target:"_blank",rel:"noopener noreferrer"},i.a.createElement(q,null,i.a.createElement(r,null))))}))))},H=[{label:"Home",url:"/"},{label:"Sobre",url:"/about"}];function U(){var t=Object(o.a)(["\n display: none;\n "]);return U=function(){return t},t}var Y=s.c.nav.withConfig({displayName:"styled__MenuLinksWrapper",componentId:"sc-1dapy1v-0"})(["",""],c.a.lessThan("large")(U())),G=s.c.ul.withConfig({displayName:"styled__MenuLinksList",componentId:"sc-1dapy1v-1"})(["font-size:1.2rem;font-weight:300;"]),$=s.c.li.withConfig({displayName:"styled__MenuLinksItem",componentId:"sc-1dapy1v-2"})(["padding:0.5rem 0;.active{color:var(--higlight);}"]),W=Object(s.c)(m.a).withConfig({displayName:"styled__MenuLinksLink",componentId:"sc-1dapy1v-3"})(["color:var(--texts);text-decoration:none;transition:color 0.5s;&:hover{color:var(--higlight);}"]),X=function(){return i.a.createElement(Y,null,i.a.createElement(G,null,H.map((function(t,e){return i.a.createElement($,{key:e},i.a.createElement(W,{cover:!0,direction:"left",bg:"var(--background)",duration:.6,to:t.url},t.label))}))))};function Q(){var t=Object(o.a)(["\n align-itens: flex-start;\n height: auto;\n padding: 1rem 2rem;\n width: 100%;\n "]);return Q=function(){return t},t}var Z=s.c.aside.withConfig({displayName:"styled__SidebarWrapper",componentId:"yydtae-0"})(["align-items:center;border-right:1px solidvar(--borders);background:var(--mediumBackground);display:flex;flex-direction:column;height:100vh;position:fixed;padding:2rem;text-align:center;width:16rem;",""],c.a.lessThan("large")(Q()));e.a=function(){return i.a.createElement(Z,null,i.a.createElement(S,null),i.a.createElement(B,null),i.a.createElement(X,null))}},"/hDo":function(t,e,r){"use strict";var n=r("q1tI"),i=r.n(n),a=r("pVnL"),o=r.n(a),s=r("Bop7"),u=n.forwardRef((function(t,e){return n.createElement(s.a,o()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M21.743 12.331l-9-10c-.379-.422-1.107-.422-1.486 0l-9 10a.998.998 0 00-.17 1.076c.16.361.518.593.913.593h2v7a1 1 0 001 1h3a1 1 0 001-1v-4h4v4a1 1 0 001 1h3a1 1 0 001-1v-7h2a.998.998 0 00.743-1.669z"}))}));u.displayName="Home";var l=n.forwardRef((function(t,e){return n.createElement(s.a,o()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M19.023 16.977a35.13 35.13 0 01-1.367-1.384c-.372-.378-.596-.653-.596-.653l-2.8-1.337A6.962 6.962 0 0016 9c0-3.859-3.14-7-7-7S2 5.141 2 9s3.14 7 7 7c1.763 0 3.37-.66 4.603-1.739l1.337 2.8s.275.224.653.596c.387.363.896.854 1.384 1.367l1.358 1.392.604.646 2.121-2.121-.646-.604c-.379-.372-.885-.866-1.391-1.36zM9 14c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"}))}));l.displayName="SearchAlt2";var c=n.forwardRef((function(t,e){return n.createElement(s.a,o()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M11 8.414V18h2V8.414l4.293 4.293 1.414-1.414L12 4.586l-6.707 6.707 1.414 1.414z"}))}));c.displayName="UpArrowAlt";var f=n.forwardRef((function(t,e){return n.createElement(s.a,o()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M9 20h6v2H9zm7.906-6.288C17.936 12.506 19 11.259 19 9c0-3.859-3.141-7-7-7S5 5.141 5 9c0 2.285 1.067 3.528 2.101 4.73.358.418.729.851 1.084 1.349.144.206.38.996.591 1.921H8v2h8v-2h-.774c.213-.927.45-1.719.593-1.925.352-.503.726-.94 1.087-1.363zm-2.724.213c-.434.617-.796 2.075-1.006 3.075h-2.351c-.209-1.002-.572-2.463-1.011-3.08a20.502 20.502 0 00-1.196-1.492C7.644 11.294 7 10.544 7 9c0-2.757 2.243-5 5-5s5 2.243 5 5c0 1.521-.643 2.274-1.615 3.413-.373.438-.796.933-1.203 1.512z"}))}));f.displayName="Bulb";var d=n.forwardRef((function(t,e){return n.createElement(s.a,o()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M4 4h4v4H4zm6 0h4v4h-4zm6 0h4v4h-4zM4 10h4v4H4zm6 0h4v4h-4zm6 0h4v4h-4zM4 16h4v4H4zm6 0h4v4h-4zm6 0h4v4h-4z"}))}));d.displayName="Grid";var h=n.forwardRef((function(t,e){return n.createElement(s.a,o()({iconAttrs:{fill:"currentColor",xmlns:"http://www.w3.org/2000/svg"},iconVerticalAlign:"middle",iconViewBox:"0 0 24 24"},t,{ref:e}),n.createElement("path",{d:"M4 6h2v2H4zm0 5h2v2H4zm0 5h2v2H4zm16-8V6H8.023v2H18.8zM8 11h12v2H8zm0 5h12v2H8z"}))}));h.displayName="ListUl";var p=r("MUpH"),m=r("vOnD"),g=r("ibEc"),v=r("Wbzz");function y(){var t=Object(p.a)(["\n height: 3.2rem;\n padding: .9rem;\n position: relative;\n width: 3.2rem;\n "]);return y=function(){return t},t}function b(){var t=Object(p.a)(["\n &:hover {\n color: var(--highlight);\n }\n "]);return b=function(){return t},t}function _(){var t=Object(p.a)(["\n display: none;\n "]);return _=function(){return t},t}function w(){var t=Object(p.a)(["\n flex-direction: row;\n "]);return w=function(){return t},t}function x(){var t=Object(p.a)(["\n border-top: 1px solid var(--borders);\n bottom: 0;\n flex-direction: row;\n height: auto;\n padding: 0;\n position: fixed;\n width: 100%;\n "]);return x=function(){return t},t}var T=m.c.aside.withConfig({displayName:"styled__MenuBarWrapper",componentId:"sc-15auwkv-0"})(["align-items:center;background:var(--mediumBackground);border-left:1px solidvar(--borders);display:flex;flex-direction:column;height:100vh;justify-content:space-between;padding:0.8rem 0;position:fixed;right:0;width:3.75rem;transition:background 0.5s;",""],g.a.lessThan("large")(x())),k=m.c.div.withConfig({displayName:"styled__MenuBarGroup",componentId:"sc-15auwkv-1"})(["display:flex;flex-direction:column;",""],g.a.lessThan("large")(w())),S=Object(m.c)(v.Link).withConfig({displayName:"styled__MenuBarLink",componentId:"sc-15auwkv-2"})(["display:block;&.active{span{color:var(--highlight);}}"]),O=m.c.span.withConfig({displayName:"styled__MenuBarItem",componentId:"sc-15auwkv-3"})(["color:var(--texts);cursor:pointer;display:block;height:1.75rem;padding:1.1rem;position:relative;width:1.75rem;&.light{color:#d4d400;&:hover{color:#e2e240;}}&:hover{color:var(--higlight);}&.display{","}"," ",""],g.a.lessThan("large")(_()),g.a.greaterThan("large")(b()),g.a.lessThan("large")(y()));e.a=function(){var t=Object(n.useState)(null),e=t[0],r=t[1],a=Object(n.useState)(null),o=a[0],s=a[1],p="dark"===e,m="list"===o;return Object(n.useEffect)((function(){r(window.__theme),s(window.__display),window.__onThemeChange=function(){return r(window.__theme)},window.__onDisplayChange=function(){return s(window.display)}}),[]),i.a.createElement(T,null,i.a.createElement(k,null,i.a.createElement(S,{to:"/",title:"Home"},i.a.createElement(O,null,i.a.createElement(u,null))),i.a.createElement(S,{to:"/search",title:"Pesquisar"},i.a.createElement(O,null,i.a.createElement(l,null)))),i.a.createElement(k,null,i.a.createElement(O,{title:"Mudar tema",onClick:function(){window.__setPreferredTheme(p?"light":"dark")},className:e},i.a.createElement(f,null)),i.a.createElement(O,{title:"Mudar visualização",onClick:function(){window.__setPreferredDisplay(m?"grid":"list")},className:"display"},m?i.a.createElement(d,null):i.a.createElement(h,null)),i.a.createElement(O,{title:"Voltar para o Topo"},i.a.createElement(c,null))))}},"0x0X":function(t,e,r){"use strict";e.a=function(t){function e(t,e,n){var i=e.trim().split(p);e=i;var a=i.length,o=t.length;switch(o){case 0:case 1:var s=0;for(t=0===o?"":t[0]+" ";s<a;++s)e[s]=r(t,e[s],n).trim();break;default:var u=s=0;for(e=[];s<a;++s)for(var l=0;l<o;++l)e[u++]=r(t[l]+" ",i[s],n).trim()}return e}function r(t,e,r){var n=e.charCodeAt(0);switch(33>n&&(n=(e=e.trim()).charCodeAt(0)),n){case 38:return e.replace(m,"$1"+t.trim());case 58:return t.trim()+e.replace(m,"$1"+t.trim());default:if(0<1*r&&0<e.indexOf("\f"))return e.replace(m,(58===t.charCodeAt(0)?"":"$1")+t.trim())}return t+e}function n(t,e,r,a){var o=t+";",s=2*e+3*r+4*a;if(944===s){t=o.indexOf(":",9)+1;var u=o.substring(t,o.length-1).trim();return u=o.substring(0,t).trim()+u+";",1===A||2===A&&i(u,1)?"-webkit-"+u+u:u}if(0===A||2===A&&!i(o,1))return o;switch(s){case 1015:return 97===o.charCodeAt(10)?"-webkit-"+o+o:o;case 951:return 116===o.charCodeAt(3)?"-webkit-"+o+o:o;case 963:return 110===o.charCodeAt(5)?"-webkit-"+o+o:o;case 1009:if(100!==o.charCodeAt(4))break;case 969:case 942:return"-webkit-"+o+o;case 978:return"-webkit-"+o+"-moz-"+o+o;case 1019:case 983:return"-webkit-"+o+"-moz-"+o+"-ms-"+o+o;case 883:if(45===o.charCodeAt(8))return"-webkit-"+o+o;if(0<o.indexOf("image-set(",11))return o.replace(S,"$1-webkit-$2")+o;break;case 932:if(45===o.charCodeAt(4))switch(o.charCodeAt(5)){case 103:return"-webkit-box-"+o.replace("-grow","")+"-webkit-"+o+"-ms-"+o.replace("grow","positive")+o;case 115:return"-webkit-"+o+"-ms-"+o.replace("shrink","negative")+o;case 98:return"-webkit-"+o+"-ms-"+o.replace("basis","preferred-size")+o}return"-webkit-"+o+"-ms-"+o+o;case 964:return"-webkit-"+o+"-ms-flex-"+o+o;case 1023:if(99!==o.charCodeAt(8))break;return"-webkit-box-pack"+(u=o.substring(o.indexOf(":",15)).replace("flex-","").replace("space-between","justify"))+"-webkit-"+o+"-ms-flex-pack"+u+o;case 1005:return d.test(o)?o.replace(f,":-webkit-")+o.replace(f,":-moz-")+o:o;case 1e3:switch(e=(u=o.substring(13).trim()).indexOf("-")+1,u.charCodeAt(0)+u.charCodeAt(e)){case 226:u=o.replace(b,"tb");break;case 232:u=o.replace(b,"tb-rl");break;case 220:u=o.replace(b,"lr");break;default:return o}return"-webkit-"+o+"-ms-"+u+o;case 1017:if(-1===o.indexOf("sticky",9))break;case 975:switch(e=(o=t).length-10,s=(u=(33===o.charCodeAt(e)?o.substring(0,e):o).substring(t.indexOf(":",7)+1).trim()).charCodeAt(0)+(0|u.charCodeAt(7))){case 203:if(111>u.charCodeAt(8))break;case 115:o=o.replace(u,"-webkit-"+u)+";"+o;break;case 207:case 102:o=o.replace(u,"-webkit-"+(102<s?"inline-":"")+"box")+";"+o.replace(u,"-webkit-"+u)+";"+o.replace(u,"-ms-"+u+"box")+";"+o}return o+";";case 938:if(45===o.charCodeAt(5))switch(o.charCodeAt(6)){case 105:return u=o.replace("-items",""),"-webkit-"+o+"-webkit-box-"+u+"-ms-flex-"+u+o;case 115:return"-webkit-"+o+"-ms-flex-item-"+o.replace(x,"")+o;default:return"-webkit-"+o+"-ms-flex-line-pack"+o.replace("align-content","").replace(x,"")+o}break;case 973:case 989:if(45!==o.charCodeAt(3)||122===o.charCodeAt(4))break;case 931:case 953:if(!0===k.test(t))return 115===(u=t.substring(t.indexOf(":")+1)).charCodeAt(0)?n(t.replace("stretch","fill-available"),e,r,a).replace(":fill-available",":stretch"):o.replace(u,"-webkit-"+u)+o.replace(u,"-moz-"+u.replace("fill-",""))+o;break;case 962:if(o="-webkit-"+o+(102===o.charCodeAt(5)?"-ms-"+o:"")+o,211===r+a&&105===o.charCodeAt(13)&&0<o.indexOf("transform",10))return o.substring(0,o.indexOf(";",27)+1).replace(h,"$1-webkit-$2")+o}return o}function i(t,e){var r=t.indexOf(1===e?":":"{"),n=t.substring(0,3!==e?r:10);return r=t.substring(r+1,t.length-1),j(2!==e?n:n.replace(T,"$1"),r,e)}function a(t,e){var r=n(e,e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2));return r!==e+";"?r.replace(w," or ($1)").substring(4):"("+e+")"}function o(t,e,r,n,i,a,o,s,l,c){for(var f,d=0,h=e;d<I;++d)switch(f=P[d].call(u,t,h,r,n,i,a,o,s,l,c)){case void 0:case!1:case!0:case null:break;default:h=f}if(h!==e)return h}function s(t){return void 0!==(t=t.prefix)&&(j=null,t?"function"!=typeof t?A=1:(A=2,j=t):A=0),s}function u(t,r){var s=t;if(33>s.charCodeAt(0)&&(s=s.trim()),s=[s],0<I){var u=o(-1,r,s,s,C,O,0,0,0,0);void 0!==u&&"string"==typeof u&&(r=u)}var f=function t(r,s,u,f,d){for(var h,p,m,b,w,x=0,T=0,k=0,S=0,P=0,j=0,N=m=h=0,z=0,L=0,D=0,F=0,V=u.length,q=V-1,B="",H="",U="",Y="";z<V;){if(p=u.charCodeAt(z),z===q&&0!==T+S+k+x&&(0!==T&&(p=47===T?10:47),S=k=x=0,V++,q++),0===T+S+k+x){if(z===q&&(0<L&&(B=B.replace(c,"")),0<B.trim().length)){switch(p){case 32:case 9:case 59:case 13:case 10:break;default:B+=u.charAt(z)}p=59}switch(p){case 123:for(h=(B=B.trim()).charCodeAt(0),m=1,F=++z;z<V;){switch(p=u.charCodeAt(z)){case 123:m++;break;case 125:m--;break;case 47:switch(p=u.charCodeAt(z+1)){case 42:case 47:t:{for(N=z+1;N<q;++N)switch(u.charCodeAt(N)){case 47:if(42===p&&42===u.charCodeAt(N-1)&&z+2!==N){z=N+1;break t}break;case 10:if(47===p){z=N+1;break t}}z=N}}break;case 91:p++;case 40:p++;case 34:case 39:for(;z++<q&&u.charCodeAt(z)!==p;);}if(0===m)break;z++}switch(m=u.substring(F,z),0===h&&(h=(B=B.replace(l,"").trim()).charCodeAt(0)),h){case 64:switch(0<L&&(B=B.replace(c,"")),p=B.charCodeAt(1)){case 100:case 109:case 115:case 45:L=s;break;default:L=M}if(F=(m=t(s,L,m,p,d+1)).length,0<I&&(w=o(3,m,L=e(M,B,D),s,C,O,F,p,d,f),B=L.join(""),void 0!==w&&0===(F=(m=w.trim()).length)&&(p=0,m="")),0<F)switch(p){case 115:B=B.replace(_,a);case 100:case 109:case 45:m=B+"{"+m+"}";break;case 107:m=(B=B.replace(g,"$1 $2"))+"{"+m+"}",m=1===A||2===A&&i("@"+m,3)?"@-webkit-"+m+"@"+m:"@"+m;break;default:m=B+m,112===f&&(H+=m,m="")}else m="";break;default:m=t(s,e(s,B,D),m,f,d+1)}U+=m,m=D=L=N=h=0,B="",p=u.charCodeAt(++z);break;case 125:case 59:if(1<(F=(B=(0<L?B.replace(c,""):B).trim()).length))switch(0===N&&(h=B.charCodeAt(0),45===h||96<h&&123>h)&&(F=(B=B.replace(" ",":")).length),0<I&&void 0!==(w=o(1,B,s,r,C,O,H.length,f,d,f))&&0===(F=(B=w.trim()).length)&&(B="\0\0"),h=B.charCodeAt(0),p=B.charCodeAt(1),h){case 0:break;case 64:if(105===p||99===p){Y+=B+u.charAt(z);break}default:58!==B.charCodeAt(F-1)&&(H+=n(B,h,p,B.charCodeAt(2)))}D=L=N=h=0,B="",p=u.charCodeAt(++z)}}switch(p){case 13:case 10:47===T?T=0:0===1+h&&107!==f&&0<B.length&&(L=1,B+="\0"),0<I*R&&o(0,B,s,r,C,O,H.length,f,d,f),O=1,C++;break;case 59:case 125:if(0===T+S+k+x){O++;break}default:switch(O++,b=u.charAt(z),p){case 9:case 32:if(0===S+x+T)switch(P){case 44:case 58:case 9:case 32:b="";break;default:32!==p&&(b=" ")}break;case 0:b="\\0";break;case 12:b="\\f";break;case 11:b="\\v";break;case 38:0===S+T+x&&(L=D=1,b="\f"+b);break;case 108:if(0===S+T+x+E&&0<N)switch(z-N){case 2:112===P&&58===u.charCodeAt(z-3)&&(E=P);case 8:111===j&&(E=j)}break;case 58:0===S+T+x&&(N=z);break;case 44:0===T+k+S+x&&(L=1,b+="\r");break;case 34:case 39:0===T&&(S=S===p?0:0===S?p:S);break;case 91:0===S+T+k&&x++;break;case 93:0===S+T+k&&x--;break;case 41:0===S+T+x&&k--;break;case 40:if(0===S+T+x){if(0===h)switch(2*P+3*j){case 533:break;default:h=1}k++}break;case 64:0===T+k+S+x+N+m&&(m=1);break;case 42:case 47:if(!(0<S+x+k))switch(T){case 0:switch(2*p+3*u.charCodeAt(z+1)){case 235:T=47;break;case 220:F=z,T=42}break;case 42:47===p&&42===P&&F+2!==z&&(33===u.charCodeAt(F+2)&&(H+=u.substring(F,z+1)),b="",T=0)}}0===T&&(B+=b)}j=P,P=p,z++}if(0<(F=H.length)){if(L=s,0<I&&(void 0!==(w=o(2,H,L,r,C,O,F,f,d,f))&&0===(H=w).length))return Y+H+U;if(H=L.join(",")+"{"+H+"}",0!=A*E){switch(2!==A||i(H,2)||(E=0),E){case 111:H=H.replace(y,":-moz-$1")+H;break;case 112:H=H.replace(v,"::-webkit-input-$1")+H.replace(v,"::-moz-$1")+H.replace(v,":-ms-input-$1")+H}E=0}}return Y+H+U}(M,s,r,0,0);return 0<I&&(void 0!==(u=o(-2,f,s,s,C,O,f.length,0,0,0))&&(f=u)),"",E=0,O=C=1,f}var l=/^\0+/g,c=/[\0\r\f]/g,f=/: */g,d=/zoo|gra/,h=/([,: ])(transform)/g,p=/,\r+?/g,m=/([\t\r\n ])*\f?&/g,g=/@(k\w+)\s*(\S*)\s*/,v=/::(place)/g,y=/:(read-only)/g,b=/[svh]\w+-[tblr]{2}/,_=/\(\s*(.*)\s*\)/g,w=/([\s\S]*?);/g,x=/-self|flex-/g,T=/[^]*?(:[rp][el]a[\w-]+)[^]*/,k=/stretch|:\s*\w+\-(?:conte|avail)/,S=/([^-])(image-set\()/,O=1,C=1,E=0,A=1,M=[],P=[],I=0,j=null,R=0;return u.use=function t(e){switch(e){case void 0:case null:I=P.length=0;break;default:if("function"==typeof e)P[I++]=e;else if("object"==typeof e)for(var r=0,n=e.length;r<n;++r)t(e[r]);else R=0|!!e}return t},u.set=s,void 0!==t&&s(t),u}},"2mql":function(t,e,r){"use strict";var n=r("TOwV"),i={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},a={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},o={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},s={};function u(t){return n.isMemo(t)?o:s[t.$$typeof]||i}s[n.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},s[n.Memo]=o;var l=Object.defineProperty,c=Object.getOwnPropertyNames,f=Object.getOwnPropertySymbols,d=Object.getOwnPropertyDescriptor,h=Object.getPrototypeOf,p=Object.prototype;t.exports=function t(e,r,n){if("string"!=typeof r){if(p){var i=h(r);i&&i!==p&&t(e,i,n)}var o=c(r);f&&(o=o.concat(f(r)));for(var s=u(e),m=u(r),g=0;g<o.length;++g){var v=o[g];if(!(a[v]||n&&n[v]||m&&m[v]||s&&s[v])){var y=d(r,v);try{l(e,v,y)}catch(b){}}}}return e}},"8+s/":function(t,e,r){"use strict";var n,i=r("q1tI"),a=(n=i)&&"object"==typeof n&&"default"in n?n.default:n;function o(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}var s=!("undefined"==typeof window||!window.document||!window.document.createElement);t.exports=function(t,e,r){if("function"!=typeof t)throw new Error("Expected reducePropsToState to be a function.");if("function"!=typeof e)throw new Error("Expected handleStateChangeOnClient to be a function.");if(void 0!==r&&"function"!=typeof r)throw new Error("Expected mapStateOnServer to either be undefined or a function.");return function(n){if("function"!=typeof n)throw new Error("Expected WrappedComponent to be a React component.");var u,l=[];function c(){u=t(l.map((function(t){return t.props}))),f.canUseDOM?e(u):r&&(u=r(u))}var f=function(t){var e,r;function i(){return t.apply(this,arguments)||this}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,e.__proto__=r,i.peek=function(){return u},i.rewind=function(){if(i.canUseDOM)throw new Error("You may only call rewind() on the server. Call peek() to read the current state.");var t=u;return u=void 0,l=[],t};var o=i.prototype;return o.UNSAFE_componentWillMount=function(){l.push(this),c()},o.componentDidUpdate=function(){c()},o.componentWillUnmount=function(){var t=l.indexOf(this);l.splice(t,1),c()},o.render=function(){return a.createElement(n,this.props)},i}(i.PureComponent);return o(f,"displayName","SideEffect("+function(t){return t.displayName||t.name||"Component"}(n)+")"),o(f,"canUseDOM",s),f}}},"9eSz":function(t,e,r){"use strict";var n=r("TqRt");e.__esModule=!0,e.default=void 0;var i,a=n(r("PJYZ")),o=n(r("VbXa")),s=n(r("8OQS")),u=n(r("pVnL")),l=n(r("q1tI")),c=n(r("17x9")),f=function(t){var e=(0,u.default)({},t),r=e.resolutions,n=e.sizes,i=e.critical;return r&&(e.fixed=r,delete e.resolutions),n&&(e.fluid=n,delete e.sizes),i&&(e.loading="eager"),e.fluid&&(e.fluid=x([].concat(e.fluid))),e.fixed&&(e.fixed=x([].concat(e.fixed))),e},d=function(t){var e=t.media;return!!e&&(y&&!!window.matchMedia(e).matches)},h=function(t){var e=t.fluid,r=t.fixed,n=p(e||r||[]);return n&&n.src},p=function(t){if(y&&function(t){return!!t&&Array.isArray(t)&&t.some((function(t){return void 0!==t.media}))}(t)){var e=t.findIndex(d);if(-1!==e)return t[e];var r=t.findIndex((function(t){return void 0===t.media}));if(-1!==r)return t[r]}return t[0]},m=Object.create({}),g=function(t){var e=f(t),r=h(e);return m[r]||!1},v="undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype,y="undefined"!=typeof window,b=y&&window.IntersectionObserver,_=new WeakMap;function w(t){return t.map((function(t){var e=t.src,r=t.srcSet,n=t.srcSetWebp,i=t.media,a=t.sizes;return l.default.createElement(l.default.Fragment,{key:e},n&&l.default.createElement("source",{type:"image/webp",media:i,srcSet:n,sizes:a}),r&&l.default.createElement("source",{media:i,srcSet:r,sizes:a}))}))}function x(t){var e=[],r=[];return t.forEach((function(t){return(t.media?e:r).push(t)})),[].concat(e,r)}function T(t){return t.map((function(t){var e=t.src,r=t.media,n=t.tracedSVG;return l.default.createElement("source",{key:e,media:r,srcSet:n})}))}function k(t){return t.map((function(t){var e=t.src,r=t.media,n=t.base64;return l.default.createElement("source",{key:e,media:r,srcSet:n})}))}function S(t,e){var r=t.srcSet,n=t.srcSetWebp,i=t.media,a=t.sizes;return"<source "+(e?"type='image/webp' ":"")+(i?'media="'+i+'" ':"")+'srcset="'+(e?n:r)+'" '+(a?'sizes="'+a+'" ':"")+"/>"}var O=function(t,e){var r=(void 0===i&&"undefined"!=typeof window&&window.IntersectionObserver&&(i=new window.IntersectionObserver((function(t){t.forEach((function(t){if(_.has(t.target)){var e=_.get(t.target);(t.isIntersecting||t.intersectionRatio>0)&&(i.unobserve(t.target),_.delete(t.target),e())}}))}),{rootMargin:"200px"})),i);return r&&(r.observe(t),_.set(t,e)),function(){r.unobserve(t),_.delete(t)}},C=function(t){var e=t.src?'src="'+t.src+'" ':'src="" ',r=t.sizes?'sizes="'+t.sizes+'" ':"",n=t.srcSet?'srcset="'+t.srcSet+'" ':"",i=t.title?'title="'+t.title+'" ':"",a=t.alt?'alt="'+t.alt+'" ':'alt="" ',o=t.width?'width="'+t.width+'" ':"",s=t.height?'height="'+t.height+'" ':"",u=t.crossOrigin?'crossorigin="'+t.crossOrigin+'" ':"",l=t.loading?'loading="'+t.loading+'" ':"",c=t.draggable?'draggable="'+t.draggable+'" ':"";return"<picture>"+t.imageVariants.map((function(t){return(t.srcSetWebp?S(t,!0):"")+S(t)})).join("")+"<img "+l+o+s+r+n+e+a+i+u+c+'style="position:absolute;top:0;left:0;opacity:1;width:100%;height:100%;object-fit:cover;object-position:center"/></picture>'},E=l.default.forwardRef((function(t,e){var r=t.src,n=t.imageVariants,i=t.generateSources,a=t.spreadProps,o=t.ariaHidden,s=l.default.createElement(A,(0,u.default)({ref:e,src:r},a,{ariaHidden:o}));return n.length>1?l.default.createElement("picture",null,i(n),s):s})),A=l.default.forwardRef((function(t,e){var r=t.sizes,n=t.srcSet,i=t.src,a=t.style,o=t.onLoad,c=t.onError,f=t.loading,d=t.draggable,h=t.ariaHidden,p=(0,s.default)(t,["sizes","srcSet","src","style","onLoad","onError","loading","draggable","ariaHidden"]);return l.default.createElement("img",(0,u.default)({"aria-hidden":h,sizes:r,srcSet:n,src:i},p,{onLoad:o,onError:c,ref:e,loading:f,draggable:d,style:(0,u.default)({position:"absolute",top:0,left:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"center"},a)}))}));A.propTypes={style:c.default.object,onError:c.default.func,onLoad:c.default.func};var M=function(t){function e(e){var r;(r=t.call(this,e)||this).seenBefore=y&&g(e),r.isCritical="eager"===e.loading||e.critical,r.addNoScript=!(r.isCritical&&!e.fadeIn),r.useIOSupport=!v&&b&&!r.isCritical&&!r.seenBefore;var n=r.isCritical||y&&(v||!r.useIOSupport);return r.state={isVisible:n,imgLoaded:!1,imgCached:!1,fadeIn:!r.seenBefore&&e.fadeIn,isHydrated:!1},r.imageRef=l.default.createRef(),r.placeholderRef=e.placeholderRef||l.default.createRef(),r.handleImageLoaded=r.handleImageLoaded.bind((0,a.default)(r)),r.handleRef=r.handleRef.bind((0,a.default)(r)),r}(0,o.default)(e,t);var r=e.prototype;return r.componentDidMount=function(){if(this.setState({isHydrated:y}),this.state.isVisible&&"function"==typeof this.props.onStartLoad&&this.props.onStartLoad({wasCached:g(this.props)}),this.isCritical){var t=this.imageRef.current;t&&t.complete&&this.handleImageLoaded()}},r.componentWillUnmount=function(){this.cleanUpListeners&&this.cleanUpListeners()},r.handleRef=function(t){var e=this;this.useIOSupport&&t&&(this.cleanUpListeners=O(t,(function(){var t=g(e.props);e.state.isVisible||"function"!=typeof e.props.onStartLoad||e.props.onStartLoad({wasCached:t}),e.setState({isVisible:!0},(function(){e.setState({imgLoaded:t,imgCached:!(!e.imageRef.current||!e.imageRef.current.currentSrc)})}))})))},r.handleImageLoaded=function(){var t,e,r;t=this.props,e=f(t),(r=h(e))&&(m[r]=!0),this.setState({imgLoaded:!0}),this.props.onLoad&&this.props.onLoad()},r.render=function(){var t=f(this.props),e=t.title,r=t.alt,n=t.className,i=t.style,a=void 0===i?{}:i,o=t.imgStyle,s=void 0===o?{}:o,c=t.placeholderStyle,d=void 0===c?{}:c,h=t.placeholderClassName,m=t.fluid,g=t.fixed,v=t.backgroundColor,y=t.durationFadeIn,b=t.Tag,_=t.itemProp,x=t.loading,S=t.draggable,O=m||g;if(!O)return null;var M=!1===this.state.fadeIn||this.state.imgLoaded,P=!0===this.state.fadeIn&&!this.state.imgCached,I=(0,u.default)({opacity:M?1:0,transition:P?"opacity "+y+"ms":"none"},s),j="boolean"==typeof v?"lightgray":v,R={transitionDelay:y+"ms"},N=(0,u.default)({opacity:this.state.imgLoaded?0:1},P&&R,s,d),z={title:e,alt:this.state.isVisible?"":r,style:N,className:h,itemProp:_},L=this.state.isHydrated?p(O):O[0];if(m)return l.default.createElement(b,{className:(n||"")+" gatsby-image-wrapper",style:(0,u.default)({position:"relative",overflow:"hidden",maxWidth:L.maxWidth?L.maxWidth+"px":null,maxHeight:L.maxHeight?L.maxHeight+"px":null},a),ref:this.handleRef,key:"fluid-"+JSON.stringify(L.srcSet)},l.default.createElement(b,{"aria-hidden":!0,style:{width:"100%",paddingBottom:100/L.aspectRatio+"%"}}),j&&l.default.createElement(b,{"aria-hidden":!0,title:e,style:(0,u.default)({backgroundColor:j,position:"absolute",top:0,bottom:0,opacity:this.state.imgLoaded?0:1,right:0,left:0},P&&R)}),L.base64&&l.default.createElement(E,{ariaHidden:!0,ref:this.placeholderRef,src:L.base64,spreadProps:z,imageVariants:O,generateSources:k}),L.tracedSVG&&l.default.createElement(E,{ariaHidden:!0,ref:this.placeholderRef,src:L.tracedSVG,spreadProps:z,imageVariants:O,generateSources:T}),this.state.isVisible&&l.default.createElement("picture",null,w(O),l.default.createElement(A,{alt:r,title:e,sizes:L.sizes,src:L.src,crossOrigin:this.props.crossOrigin,srcSet:L.srcSet,style:I,ref:this.imageRef,onLoad:this.handleImageLoaded,onError:this.props.onError,itemProp:_,loading:x,draggable:S})),this.addNoScript&&l.default.createElement("noscript",{dangerouslySetInnerHTML:{__html:C((0,u.default)({alt:r,title:e,loading:x},L,{imageVariants:O}))}}));if(g){var D=(0,u.default)({position:"relative",overflow:"hidden",display:"inline-block",width:L.width,height:L.height},a);return"inherit"===a.display&&delete D.display,l.default.createElement(b,{className:(n||"")+" gatsby-image-wrapper",style:D,ref:this.handleRef,key:"fixed-"+JSON.stringify(L.srcSet)},j&&l.default.createElement(b,{"aria-hidden":!0,title:e,style:(0,u.default)({backgroundColor:j,width:L.width,opacity:this.state.imgLoaded?0:1,height:L.height},P&&R)}),L.base64&&l.default.createElement(E,{ariaHidden:!0,ref:this.placeholderRef,src:L.base64,spreadProps:z,imageVariants:O,generateSources:k}),L.tracedSVG&&l.default.createElement(E,{ariaHidden:!0,ref:this.placeholderRef,src:L.tracedSVG,spreadProps:z,imageVariants:O,generateSources:T}),this.state.isVisible&&l.default.createElement("picture",null,w(O),l.default.createElement(A,{alt:r,title:e,width:L.width,height:L.height,sizes:L.sizes,src:L.src,crossOrigin:this.props.crossOrigin,srcSet:L.srcSet,style:I,ref:this.imageRef,onLoad:this.handleImageLoaded,onError:this.props.onError,itemProp:_,loading:x,draggable:S})),this.addNoScript&&l.default.createElement("noscript",{dangerouslySetInnerHTML:{__html:C((0,u.default)({alt:r,title:e,loading:x},L,{imageVariants:O}))}}))}return null},e}(l.default.Component);M.defaultProps={fadeIn:!0,durationFadeIn:500,alt:"",Tag:"div",loading:"lazy"};var P=c.default.shape({width:c.default.number.isRequired,height:c.default.number.isRequired,src:c.default.string.isRequired,srcSet:c.default.string.isRequired,base64:c.default.string,tracedSVG:c.default.string,srcWebp:c.default.string,srcSetWebp:c.default.string,media:c.default.string}),I=c.default.shape({aspectRatio:c.default.number.isRequired,src:c.default.string.isRequired,srcSet:c.default.string.isRequired,sizes:c.default.string.isRequired,base64:c.default.string,tracedSVG:c.default.string,srcWebp:c.default.string,srcSetWebp:c.default.string,media:c.default.string,maxWidth:c.default.number,maxHeight:c.default.number});function j(t){return function(e,r,n){var i;if(!e.fixed&&!e.fluid)throw new Error("The prop `fluid` or `fixed` is marked as required in `"+n+"`, but their values are both `undefined`.");c.default.checkPropTypes(((i={})[r]=t,i),e,"prop",n)}}M.propTypes={resolutions:P,sizes:I,fixed:j(c.default.oneOfType([P,c.default.arrayOf(P)])),fluid:j(c.default.oneOfType([I,c.default.arrayOf(I)])),fadeIn:c.default.bool,durationFadeIn:c.default.number,title:c.default.string,alt:c.default.string,className:c.default.oneOfType([c.default.string,c.default.object]),critical:c.default.bool,crossOrigin:c.default.oneOfType([c.default.string,c.default.bool]),style:c.default.object,imgStyle:c.default.object,placeholderStyle:c.default.object,placeholderClassName:c.default.string,backgroundColor:c.default.oneOfType([c.default.string,c.default.bool]),onLoad:c.default.func,onError:c.default.func,onStartLoad:c.default.func,Tag:c.default.string,itemProp:c.default.string,loading:c.default.oneOf(["auto","lazy","eager"]),draggable:c.default.bool};var R=M;e.default=R},"9uj6":function(t,e,r){"use strict";var n=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,i=function(t){var e={};return function(r){return void 0===e[r]&&(e[r]=t(r)),e[r]}}((function(t){return n.test(t)||111===t.charCodeAt(0)&&110===t.charCodeAt(1)&&t.charCodeAt(2)<91}));e.a=i},AbOF:function(t,e,r){"use strict";var n=r("8OQS"),i=r("PJYZ"),a=r("VbXa"),o=r("TqRt"),s=r("284h");e.__esModule=!0,e.default=void 0;var u=o(r("pVnL")),l=s(r("q1tI")),c=o(r("plVc")),f=o(r("z/o8")),d=o(r("uxXc")),h=function(t){function e(e){var r;return(r=t.call(this,e)||this).createRipple=function(t,e,r,n,i){var a=t.length,o=document.body,s=document.createElement("canvas"),u=s.getContext("2d"),l=2*Math.PI,c=r?d.default.hex.rgb(r).join(","):"0,0,255";c=n?d.default.keyword.rgb(n):c,s.style.zIndex=1e4,s.style.top=0,s.style.position="fixed";var h=s.width=window.innerWidth,p=s.height=window.innerHeight;o.appendChild(s);var m=e.clientX,g=e.clientY,v=m<h/2?h-m:m,y=g<p/2?p-g:g,b=Math.sqrt(v*v+y*y),_={alpha:0,radius:0,x:m,y:g},w=a;f.default.timeline({onUpdate:function(){u.clearRect(0,0,h,p),u.beginPath(),u.arc(_.x,_.y,_.radius,0,l,!1);var t="rgba("+c+","+_.alpha+")";u.fillStyle=t,u.fill()},onComplete:function(){return function(t){void 0===t&&(t=0);setTimeout((function(){o.removeChild(s)}),t)}(w/3)}}).to(_,{alpha:1,duration:w/4}).to(_,{radius:b,ease:"power1.easeIn",duration:w-w/3},0).set(i,{visibility:"hidden"}).to(s,{x:"100%",ease:"power1.easeIn",duration:w/3},"+="+.4*w),window.addEventListener("resize",(function(){h=s.width=window.innerWidth,p=s.height=window.innerHeight}))},r.getDirection=function(t){switch(t){case"left":return{xPercent:-5};case"right":return{xPercent:5};case"top":return{yPercent:-5};case"bottom":return{yPercent:5};default:return{}}},r.slideIn=function(t,e,n){var i=t.length;f.default.from(e,i,Object.assign({},r.getDirection(n),{ease:"power1.easeOut"}))},r.onResize=function(){r.vw=r.canvas.width=window.innerWidth,r.vh=r.canvas.height=window.innerHeight},r.createRipple=r.createRipple.bind(i(r)),r}a(e,t);var r=e.prototype;return r.componentWillUnmount=function(){window.removeEventListener("resize",this.onResize)},r.render=function(){var t=this,e=this.props,r=(e.exit,e.entry,e.paintDrip,e.duration),i=e.direction,a=void 0===i?"left":i,o=n(e,["exit","entry","paintDrip","duration","direction"]),s=r||1,f=s/1.75;return l.default.createElement(l.default.Fragment,null,l.default.createElement(c.default,(0,u.default)({exit:{length:s,trigger:function(e){var r=e.exit,n=e.e,i=e.node;return t.createRipple(r,n,o.hex,o.color,i)}},entry:{delay:f,length:s,trigger:function(e){var r=e.entry,n=e.node;return t.slideIn(r,n,a)}}},o,{__self:this,__source:{fileName:"/Users/tyler/Documents/GitHub/gatsby-plugins/transition-link/gatsby-plugin-transition-link/src/AniLink/PaintDrip.js",lineNumber:145,columnNumber:5}}),o.children))},e}(l.Component);e.default=h},Alic:function(t,e,r){"use strict";e.__esModule=!0,e.useTransitionState=void 0;var n=r("q1tI"),i=r("Ds8n");e.useTransitionState=function(){return(0,n.useContext)(i.publicContext)}},Bop7:function(t,e,r){"use strict";r.d(e,"a",(function(){return m}));r("E9XD");var n=r("pVnL"),i=r.n(n),a=r("lSNA"),o=r.n(a),s=r("QILm"),u=r.n(s),l=r("q1tI"),c=r("vOnD"),f=r("9uj6");function d(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function h(t){return Object.keys(t).reduce((function(e,r){var n;return n=r,Object(f.a)(n)&&(e[r]=t[r]),e}),{})}var p=l.forwardRef((function(t,e){var r=t.children,n=t.iconAttrs,a=(t.iconVerticalAlign,t.iconViewBox),s=t.size,c=t.title,f=u()(t,["children","iconAttrs","iconVerticalAlign","iconViewBox","size","title"]),p=function(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?d(Object(r),!0).forEach((function(e){o()(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}({viewBox:a,height:void 0!==t.height?t.height:s,width:void 0!==t.width?t.width:s,"aria-hidden":null==c?"true":void 0,focusable:"false",role:null!=c?"img":void 0},n),m=h(f);return l.createElement("svg",i()({},p,m,{ref:e}),c&&l.createElement("title",{key:"icon-title"},c),r)})),m=Object(c.c)(p).withConfig({displayName:"StyledIconBase",componentId:"ea9ulj-0"})(["display:inline-block;vertical-align:",";overflow:hidden;"],(function(t){return t.iconVerticalAlign}))},Fstm:function(t,e,r){"use strict";var n=r("TqRt");e.__esModule=!0,e.triggerTransition=void 0;var i=r("Wbzz"),a=r("NAVQ"),o=r("c3/e"),s=n(r("I3R8"));e.triggerTransition=function(t){var e,r=t.to,n=t.event,u=void 0===n?null:n,l=t.exit,c=void 0===l?{}:l,f=t.entry,d=void 0===f?{}:f,h=t.inTransition,p=t.pages,m=t.trigger,g=t.updateContext,v=t.linkState,y=t.replace,b=t.preventScrollJump;if(u&&(u.persist(),u.preventDefault()),h)return!1;if(r.includes("#")){var _=r.split("#");r=_[0],e=_[1]}window.__tl_inTransition=!0,window.__tl_desiredPathname=(0,i.withPrefix)(r),g({inTransition:!0,exitDelay:0,exitLength:0,appearAfter:0,exitState:{}}),m&&"function"==typeof m&&m(p);var w=c.length,x=void 0===w?0:w,T=c.delay,k=void 0===T?0:T,S=c.state,O=void 0===S?{}:S,C=c.trigger,E=void 0===C?function(){}:C,A=d.length,M=void 0===A?1:A,P=d.delay,I=void 0===P?0:P,j=d.state,R=void 0===j?{}:j,N=d.trigger,z=void 0===N?function(){}:N,L=d.appearAfter;g({entryLength:M,entryDelay:I,exitLength:x,exitDelay:k,entryProps:d,exitProps:c,appearAfter:void 0===L?0:L,preventScrollJump:b,exitTrigger:function(t,e,r){return E(t,e,r)},entryTrigger:function(t,e,r){return z(t,e,r)},e:u}),(0,a.setTimeout)((function(){(0,i.navigate)(r,{state:Object.assign({},v),replace:y}),g({exitState:O,hash:e})}),(0,o.getMs)(k)),(0,a.setTimeout)((function(){g({entryState:R})}),(0,o.getMs)(k+I)),(0,a.setTimeout)((function(){return g({entryDelay:0,appearAfter:0,entryLength:0})}),(0,o.getMs)(k+I+M));var D=k+Math.max(x,I+M);(0,a.setTimeout)((function(){window.__tl_inTransition=!1,window.__tl_desiredPathname=!1,window.__tl_back_button_pressed=!1,g(Object.assign({exitDelay:0,exitLength:0,inTransition:!1},(0,s.default)()))}),(0,o.getMs)(D)+1)}},GVzS:function(t,e,r){"use strict";e.__esModule=!0,e.default=void 0;var n=r("q1tI"),i=r("Ds8n");var a=function(t){var e=(0,n.useRef)(null),r=(0,n.useContext)(i.publicContext),a=(0,n.useState)(null),o=a[0],s=a[1],u=(0,n.useState)(!1),l=u[0],c=u[1],f="IntersectionObserver"in window&&"IntersectionObserverEntry"in window&&"intersectionRatio"in window.IntersectionObserverEntry.prototype;return(0,n.useEffect)((function(){if(e&&e.current){var t;return(t=new IntersectionObserver((function(t){var e=t[0];c(!!e.intersectionRatio)}),{threshold:1})).observe(e.current),function(){return t.unobserve(e.current)}}}),[e]),(0,n.useEffect)((function(){(!f||t.forceRender||l)&&s(r)}),[r.transitionStatus,e,l]),t.children(o,e)};e.default=a},Gytx:function(t,e){t.exports=function(t,e,r,n){var i=r?r.call(n,t,e):void 0;if(void 0!==i)return!!i;if(t===e)return!0;if("object"!=typeof t||!t||"object"!=typeof e||!e)return!1;var a=Object.keys(t),o=Object.keys(e);if(a.length!==o.length)return!1;for(var s=Object.prototype.hasOwnProperty.bind(e),u=0;u<a.length;u++){var l=a[u];if(!s(l))return!1;var c=t[l],f=e[l];if(!1===(i=r?r.call(n,c,f,l):void 0)||void 0===i&&c!==f)return!1}return!0}},ME5O:function(t,e,r){"use strict";e.a={animationIterationCount:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1}},MUpH:function(t,e,r){"use strict";function n(t,e){return e||(e=t.slice(0)),t.raw=e,t}r.d(e,"a",(function(){return n}))},"N+e4":function(t,e,r){"use strict";var n=r("VbXa"),i=r("284h"),a=r("TqRt");e.__esModule=!0,e.default=void 0;var o=i(r("q1tI")),s=a(r("i8i4")),u="/Users/tyler/Documents/GitHub/gatsby-plugins/transition-link/gatsby-plugin-transition-link/src/components/TransitionPortal.js",l="undefined"!=typeof document&&document.body,c=function(t){var e=function(t){switch(t){case"bottom":return 1e3;case"top":return 1200;default:return 1100}}(t.level);return o.default.createElement("div",{className:"gatsby-plugin-transition-link-portal",style:{position:"fixed",top:0,left:0,zIndex:e},__self:void 0,__source:{fileName:u,lineNumber:19,columnNumber:3}},t.children)},f=function(t){function e(){var e;return(e=t.call(this)||this).componentDidMount=function(){l&&l.appendChild(e.el)},e.componentWillUnmount=function(){l&&l.removeChild(e.el)},e.el="undefined"!=typeof document&&document.createElement("section"),e}return n(e,t),e.prototype.render=function(){return this.el&&l?s.default.createPortal(o.default.createElement(o.default.Fragment,null,l&&o.default.createElement(c,{styles:this.props.css,level:this.props.level,__self:this,__source:{fileName:u,lineNumber:54,columnNumber:8}},this.props.children)),this.el):null},e}(o.Component);e.default=f},QILm:function(t,e,r){var n=r("8OQS");t.exports=function(t,e){if(null==t)return{};var r,i,a=n(t,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(i=0;i<o.length;i++)r=o[i],e.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(a[r]=t[r])}return a}},T016:function(t,e,r){"use strict";t.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}},TOwV:function(t,e,r){"use strict";t.exports=r("qT12")},V17b:function(t,e,r){"use strict";var n=r("8OQS"),i=r("TqRt"),a=r("284h");e.__esModule=!0,e.TransitionLink=void 0;var o=i(r("pVnL")),s=a(r("q1tI")),u=i(r("17x9")),l=r("Wbzz"),c=r("X6jR"),f=r("Fstm"),d=r("Ds8n"),h="/Users/tyler/Documents/GitHub/gatsby-plugins/transition-link/gatsby-plugin-transition-link/src/components/TransitionLink.js";void 0===s.forwardRef&&(s.forwardRef=function(){throw new Error('"forwardRef" is read-only.')}());var p=(0,s.forwardRef)((function(t,e){var r=t.to,i=t.children,a=t.exit,u=t.entry,p=t.activeStyle,m=t.partiallyActive,g=t.style,v=t.className,y=t.activeClassName,b=t.state,_=t.onClick,w=t.trigger,x=t.replace,T=t.innerRef,k=t.preventScrollJump,S=n(t,["to","children","exit","entry","activeStyle","partiallyActive","style","className","activeClassName","state","onClick","trigger","replace","innerRef","preventScrollJump"]);return s.default.createElement(d.Consumer,{__self:void 0,__source:{fileName:h,lineNumber:36,columnNumber:4}},(function(t){var d=t.disableAnimation,O=n(t,["disableAnimation"]);return s.default.createElement(l.Link,(0,o.default)({style:g,activeStyle:p,className:v,activeClassName:y,partiallyActive:m,onClick:function(t){if(!d){var e=(0,c.shouldNavigate)(t);e&&(0,f.triggerTransition)(Object.assign({event:t,to:r,exit:a,entry:u,trigger:w,replace:x,preventScrollJump:k,linkState:b},O)),"function"==typeof _&&_(t,e)}},to:r,ref:e||T},S,{__self:void 0,__source:{fileName:h,lineNumber:38,columnNumber:6}}),i)}))}));e.TransitionLink=p,p.propTypes={to:u.default.string.isRequired,exitLength:u.default.number,entryDelay:u.default.number,exitFn:u.default.func,entryState:u.default.object}},V2YU:function(t,e,r){"use strict";e.__esModule=!0,e.useTriggerTransition=void 0;var n=r("q1tI"),i=r("Wbzz"),a=r("Ds8n"),o=r("Fstm");e.useTriggerTransition=function(t){var e=(0,n.useContext)(a.Context);return function(r){(r instanceof Event||r.nativeEvent&&r.nativeEvent instanceof Event)&&(r={event:r});var n=Object.assign({},t,r);e.disableAnimation?(n.event&&(n.event.persist(),n.event.preventDefault()),(0,i.navigate)(n.to)):(0,o.triggerTransition)(Object.assign({},e,n))}}},X6jR:function(t,e,r){"use strict";e.__esModule=!0,e.shouldNavigate=void 0;e.shouldNavigate=function(t){return!t.defaultPrevented&&0===t.button&&!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}},ZhWT:function(t,e){var r="undefined"!=typeof Element,n="function"==typeof Map,i="function"==typeof Set,a="function"==typeof ArrayBuffer&&!!ArrayBuffer.isView;t.exports=function(t,e){try{return function t(e,o){if(e===o)return!0;if(e&&o&&"object"==typeof e&&"object"==typeof o){if(e.constructor!==o.constructor)return!1;var s,u,l,c;if(Array.isArray(e)){if((s=e.length)!=o.length)return!1;for(u=s;0!=u--;)if(!t(e[u],o[u]))return!1;return!0}if(n&&e instanceof Map&&o instanceof Map){if(e.size!==o.size)return!1;for(c=e.entries();!(u=c.next()).done;)if(!o.has(u.value[0]))return!1;for(c=e.entries();!(u=c.next()).done;)if(!t(u.value[1],o.get(u.value[0])))return!1;return!0}if(i&&e instanceof Set&&o instanceof Set){if(e.size!==o.size)return!1;for(c=e.entries();!(u=c.next()).done;)if(!o.has(u.value[0]))return!1;return!0}if(a&&ArrayBuffer.isView(e)&&ArrayBuffer.isView(o)){if((s=e.length)!=o.length)return!1;for(u=s;0!=u--;)if(e[u]!==o[u])return!1;return!0}if(e.constructor===RegExp)return e.source===o.source&&e.flags===o.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===o.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===o.toString();if((s=(l=Object.keys(e)).length)!==Object.keys(o).length)return!1;for(u=s;0!=u--;)if(!Object.prototype.hasOwnProperty.call(o,l[u]))return!1;if(r&&e instanceof Element)return!1;for(u=s;0!=u--;)if(("_owner"!==l[u]&&"__v"!==l[u]&&"__o"!==l[u]||!e.$$typeof)&&!t(e[l[u]],o[l[u]]))return!1;return!0}return e!=e&&o!=o}(t,e)}catch(o){if((o.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw o}}},ibEc:function(t,e,r){"use strict";r("E9XD");var n=r("vOnD");function i(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}function a(){var t=i(["\n @media (min-width: ",") {\n ","\n }\n "]);return a=function(){return t},t}function o(){var t=i(["\n @media (max-width: ",") {\n ","\n }\n "]);return o=function(){return t},t}function s(){var t=i(["\n @media (min-width: ",") and\n (max-width: ",") {\n ","\n }\n "]);return s=function(){return t},t}function u(){var t=i(["\n @media (min-width: ",") {\n ","\n }\n "]);return u=function(){return t},t}function l(){var t=i(["\n @media (max-width: ",") {\n ","\n }\n "]);return l=function(){return t},t}var c={huge:"1440px",large:"1170px",medium:"768px",small:"450px"};function f(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[t]?e[t]:parseInt(t)?t:(console.error("styled-media-query: No valid breakpoint or size specified for media."),"0")}var d=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:c,e=function(e){return function(){return Object(n.b)(l(),f(e,t),n.b.apply(void 0,arguments))}},r=function(e){return function(){return Object(n.b)(u(),f(e,t),n.b.apply(void 0,arguments))}},i=function(e,r){return function(){return Object(n.b)(s(),f(e,t),f(r,t),n.b.apply(void 0,arguments))}},d=Object.keys(t).reduce((function(e,r){var i=t[r];return e.to[r]=function(){return console.warn("styled-media-query: Use media.lessThan('".concat(r,"') instead of old media.to.").concat(r," (Probably we'll deprecate it)")),Object(n.b)(o(),i,n.b.apply(void 0,arguments))},e.from[r]=function(){return console.warn("styled-media-query: Use media.greaterThan('".concat(r,"') instead of old media.from.").concat(r," (Probably we'll deprecate it)")),Object(n.b)(a(),i,n.b.apply(void 0,arguments))},e}),{to:{},from:{}});return Object.assign({lessThan:e,greaterThan:r,between:i},d)}();e.a=d},"kOA+":function(t,e,r){"use strict";var n=r("8OQS"),i=r("TqRt");e.__esModule=!0,e.default=function(t){var e=t.children,r=n(t,["children"]);return o.default.createElement(o.default.Fragment,null,r.cover&&o.default.createElement(s.default,(0,a.default)({},r,{__self:this,__source:{fileName:h,lineNumber:13,columnNumber:20}}),e),r.fade&&o.default.createElement(u.default,(0,a.default)({},r,{__self:this,__source:{fileName:h,lineNumber:14,columnNumber:19}}),e),r.paintDrip&&o.default.createElement(l.default,(0,a.default)({},r,{__self:this,__source:{fileName:h,lineNumber:15,columnNumber:24}}),e),r.swipe&&o.default.createElement(c.default,(0,a.default)({},r,{__self:this,__source:{fileName:h,lineNumber:16,columnNumber:20}}),e),!!r.morph&&o.default.createElement(d.default,(0,a.default)({},r,{__self:this,__source:{fileName:h,lineNumber:17,columnNumber:22}}),e),!r.cover&&!r.fade&&!r.paintDrip&&!r.swipe&&!r.morph&&o.default.createElement(f.default,(0,a.default)({},r,{__self:this,__source:{fileName:h,lineNumber:24,columnNumber:6}}),e))};var a=i(r("pVnL")),o=i(r("q1tI")),s=i(r("tiwY")),u=i(r("+ZrZ")),l=i(r("AbOF")),c=i(r("mc3b")),f=i(r("plVc")),d=i(r("noOv")),h="/Users/tyler/Documents/GitHub/gatsby-plugins/transition-link/gatsby-plugin-transition-link/src/AniLink/index.js"},lEpx:function(t,e,r){"use strict";var n=r("MUpH"),i=r("vOnD");function a(){var t=Object(n.a)(["\n /* http://meyerweb.com/eric/tools/css/reset/ \n v2.0 | 20110126\n License: none (public domain)\n*/\n\nhtml, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, big, cite, code,\ndel, dfn, em, img, ins, kbd, q, s, samp,\nsmall, strike, strong, sub, sup, tt, var,\nb, u, i, center,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, canvas, details, embed, \nfigure, figcaption, footer, header, hgroup, \nmenu, nav, output, ruby, section, summary,\ntime, mark, audio, video {\n\tmargin: 0;\n\tpadding: 0;\n\tborder: 0;\n\tfont-size: 100%;\n\tfont: inherit;\n\tvertical-align: baseline;\n}\n/* HTML5 display-role reset for older browsers */\narticle, aside, details, figcaption, figure, \nfooter, header, hgroup, menu, nav, section {\n\tdisplay: block;\n}\nbody {\n\tline-height: 1;\n}\nol, ul {\n\tlist-style: none;\n}\nblockquote, q {\n\tquotes: none;\n}\nblockquote:before, blockquote:after,\nq:before, q:after {\n\tcontent: '';\n\tcontent: none;\n}\ntable {\n\tborder-collapse: collapse;\n\tborder-spacing: 0;\n}\nbody {\n background: #102027;\n line-height: 1;\n font-size: 100%;\n font-family: --apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;\n}\nimg {\n display: block;\n width: 100%;\n height: auto;\n}\n\nbody.dark {\n\t--borders: #384446;\n\t--texts: #8899a6;\n\t--postColor: #fff;\n\t--higlight: #1fa1f2;\n\t--mediumBackground: #192734;\n\t--background: #102027;\n\t--white: #fff;\n\t--black: #222;\n}\n\nbody.light {\n\t--borders: #dedede;\n\t--texts: #555555;\n\t--postColor: #111;\n\t--higlight: #1fa1f2;\n\t--mediumBackground: #eceff1;\n\t--background: #fff;\n\t--white: #fff;\n\t--black: #222;\n}\n"]);return a=function(){return t},t}var o=Object(i.a)(a());e.a=o},lSNA:function(t,e){t.exports=function(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}},ls82:function(t,e,r){var n=function(t){"use strict";var e=Object.prototype,r=e.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",a=n.asyncIterator||"@@asyncIterator",o=n.toStringTag||"@@toStringTag";function s(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{s({},"")}catch(O){s=function(t,e,r){return t[e]=r}}function u(t,e,r,n){var i=e&&e.prototype instanceof f?e:f,a=Object.create(i.prototype),o=new T(n||[]);return a._invoke=function(t,e,r){var n="suspendedStart";return function(i,a){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===i)throw a;return S()}for(r.method=i,r.arg=a;;){var o=r.delegate;if(o){var s=_(o,r);if(s){if(s===c)continue;return s}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=l(t,e,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===c)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}(t,r,o),a}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(O){return{type:"throw",arg:O}}}t.wrap=u;var c={};function f(){}function d(){}function h(){}var p={};p[i]=function(){return this};var m=Object.getPrototypeOf,g=m&&m(m(k([])));g&&g!==e&&r.call(g,i)&&(p=g);var v=h.prototype=f.prototype=Object.create(p);function y(t){["next","throw","return"].forEach((function(e){s(t,e,(function(t){return this._invoke(e,t)}))}))}function b(t,e){var n;this._invoke=function(i,a){function o(){return new e((function(n,o){!function n(i,a,o,s){var u=l(t[i],t,a);if("throw"!==u.type){var c=u.arg,f=c.value;return f&&"object"==typeof f&&r.call(f,"__await")?e.resolve(f.__await).then((function(t){n("next",t,o,s)}),(function(t){n("throw",t,o,s)})):e.resolve(f).then((function(t){c.value=t,o(c)}),(function(t){return n("throw",t,o,s)}))}s(u.arg)}(i,a,n,o)}))}return n=n?n.then(o,o):o()}}function _(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,_(t,e),"throw"===e.method))return c;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var n=l(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,c;var i=n.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,c):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,c)}function w(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function x(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(w,this),this.reset(!0)}function k(t){if(t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,a=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return a.next=a}}return{next:S}}function S(){return{value:void 0,done:!0}}return d.prototype=v.constructor=h,h.constructor=d,d.displayName=s(h,o,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===d||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,h):(t.__proto__=h,s(t,o,"GeneratorFunction")),t.prototype=Object.create(v),t},t.awrap=function(t){return{__await:t}},y(b.prototype),b.prototype[a]=function(){return this},t.AsyncIterator=b,t.async=function(e,r,n,i,a){void 0===a&&(a=Promise);var o=new b(u(e,r,n,i),a);return t.isGeneratorFunction(r)?o:o.next().then((function(t){return t.done?t.value:o.next()}))},y(v),s(v,o,"Generator"),v[i]=function(){return this},v.toString=function(){return"[object Generator]"},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=k,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(x),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return o.type="throw",o.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],o=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var s=r.call(a,"catchLoc"),u=r.call(a,"finallyLoc");if(s&&u){if(this.prev<a.catchLoc)return n(a.catchLoc,!0);if(this.prev<a.finallyLoc)return n(a.finallyLoc)}else if(s){if(this.prev<a.catchLoc)return n(a.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return n(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var a=i;break}}a&&("break"===t||"continue"===t)&&a.tryLoc<=e&&e<=a.finallyLoc&&(a=null);var o=a?a.completion:{};return o.type=t,o.arg=e,a?(this.method="next",this.next=a.finallyLoc,c):this.complete(o)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),c},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),x(r),c}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;x(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:k(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),c}},t}(t.exports);try{regeneratorRuntime=n}catch(i){Function("r","regeneratorRuntime = r")(n)}},mc3b:function(t,e,r){"use strict";var n=r("8OQS"),i=r("TqRt");e.__esModule=!0,e.default=function(t){t.exit,t.entry,t.swipe;var e=t.entryOffset,r=void 0===e?40:e,i=n(t,["exit","entry","swipe","entryOffset"]),u=i.top||"exit",l=i.duration||.7,c=l/3.5,f="entry"===u?1:0,h="exit"===u?1:0;return o.default.createElement(s.default,(0,a.default)({exit:{length:l,trigger:function(t){var e=t.node,n=t.exit;return d({node:e,exit:n,direction:i.direction,top:u,entryOffset:r,triggerName:"exit"})},zIndex:h},entry:{length:c,trigger:function(t){var e=t.node,n=t.exit;return d({node:e,exit:n,direction:i.direction,top:u,entryOffset:r,triggerName:"entry"})},zIndex:f}},i,{__self:this,__source:{fileName:"/Users/tyler/Documents/GitHub/gatsby-plugins/transition-link/gatsby-plugin-transition-link/src/AniLink/Swipe.js",lineNumber:106,columnNumber:3}}),i.children)};var a=i(r("pVnL")),o=i(r("q1tI")),s=i(r("plVc")),u=i(r("z/o8")),l="0 0 100px 10px rgba(0, 0, 0, 0.12941176470588237)",c=function(t,e){var r=e?"-":"+",n=e?"+":"-";switch(t){case"down":return{y:r+"=100vh",ease:"power1.easeIn"};case"up":return{y:n+"=100vh",ease:"power1.easeIn"};case"left":return{x:n+"=100%",ease:"power1.easeIn"};default:return{x:r+"=100%",ease:"power1.easeIn"}}},f=function(t,e,r){void 0===e&&(e=!1),void 0===r&&(r=40);var n=e?"-":"",i=e?"":"-";switch(t){case"down":return{y:""+i+r+"vh",ease:"power1.easeIn"};case"up":return{y:""+n+r+"vh",ease:"power1.easeIn"};case"left":return{x:""+n+r+"%",ease:"power1.easeIn"};default:return{x:""+i+r+"%",ease:"power1.easeIn"}}},d=function(t){var e=t.node,r=t.exit,n=t.direction,i=t.top,a=t.triggerName,o=t.entryOffset,s=document.scrollingElement&&document.scrollingElement.scrollTop||document.body.scrollTop||window.pageYOffset;return"entry"===a&&"entry"===i?u.default.timeline().set(e,{boxShadow:l,overflowY:"hidden",height:"100vh",scrollTop:s}).from(e,Object.assign({},c(n,!0),{duration:r.length})).set(e,{overflowY:"initial"}):"entry"===a?u.default.timeline().from(e,Object.assign({},f(n,!1,o),{duration:r.length})):"exit"===a&&"exit"===i?u.default.timeline().set(e,{boxShadow:l,overflowY:"hidden",height:"100vh",scrollTop:s}).to(e,Object.assign({},c(n),{duration:r.length})).set(e,{overflowY:"initial"}):u.default.timeline().set(e,{boxShadow:l,overflowY:"hidden",height:"100vh",scrollTop:s}).to(e,Object.assign({},f(n,!0,o),{duration:r.length})).set(e,{overflowY:"initial"})}},noOv:function(t,e,r){"use strict";var n=r("o0o1");r("ls82");var i=r("yXPU"),a=r("TqRt");e.__esModule=!0,e.default=void 0;var o=a(r("q1tI")),s=a(r("plVc")),u=a(r("z/o8")),l=function(t){var e,r=t.children,a=t.to,l=t.duration,c=t.morph;return o.default.createElement(s.default,{to:a,exit:{length:l},entry:{appearAfter:l},trigger:(e=i(n.mark((function t(e){var r,i,a,o,s;return n.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.exit;case 2:return r=t.sent,t.next=5,e.entry;case 5:i=t.sent,a=r.node.querySelector(c.from),o=i.node.querySelector(c.to),s={height:o.offsetHeight,width:o.offsetWidth},u.default.to(a,{width:s.width,height:s.height,duration:l});case 10:case"end":return t.stop()}}),t)}))),function(t){return e.apply(this,arguments)}),__self:void 0,__source:{fileName:"/Users/tyler/Documents/GitHub/gatsby-plugins/transition-link/gatsby-plugin-transition-link/src/AniLink/MorphTo.js",lineNumber:6,columnNumber:2}},r)};e.default=l},o0o1:function(t,e,r){t.exports=r("ls82")},onlc:function(t,e,r){var n=r("t1N5");function i(t){var e=function(){for(var t={},e=Object.keys(n),r=e.length,i=0;i<r;i++)t[e[i]]={distance:-1,parent:null};return t}(),r=[t];for(e[t].distance=0;r.length;)for(var i=r.pop(),a=Object.keys(n[i]),o=a.length,s=0;s<o;s++){var u=a[s],l=e[u];-1===l.distance&&(l.distance=e[i].distance+1,l.parent=i,r.unshift(u))}return e}function a(t,e){return function(r){return e(t(r))}}function o(t,e){for(var r=[e[t].parent,t],i=n[e[t].parent][t],o=e[t].parent;e[o].parent;)r.unshift(e[o].parent),i=a(n[e[o].parent][o],i),o=e[o].parent;return i.conversion=r,i}t.exports=function(t){for(var e=i(t),r={},n=Object.keys(e),a=n.length,s=0;s<a;s++){var u=n[s];null!==e[u].parent&&(r[u]=o(u,e))}return r}},plVc:function(t,e,r){"use strict";var n=r("TqRt");e.__esModule=!0,e.default=void 0;var i=r("V17b"),a=n(r("7Y3J"));e.TransitionHandler=a.default;var o=r("Ds8n");e.TransitionState=o.PublicConsumer;var s=n(r("N+e4"));e.TransitionPortal=s.default;var u=n(r("GVzS"));e.TransitionObserver=u.default;var l=r("qF42");e.useTriggerTransition=l.useTriggerTransition;var c=i.TransitionLink;e.default=c},qF42:function(t,e,r){"use strict";e.__esModule=!0,e.useTriggerTransition=e.useTransitionState=void 0;var n=r("Alic");e.useTransitionState=n.useTransitionState;var i=r("V2YU");e.useTriggerTransition=i.useTriggerTransition},qT12:function(t,e,r){"use strict";var n="function"==typeof Symbol&&Symbol.for,i=n?Symbol.for("react.element"):60103,a=n?Symbol.for("react.portal"):60106,o=n?Symbol.for("react.fragment"):60107,s=n?Symbol.for("react.strict_mode"):60108,u=n?Symbol.for("react.profiler"):60114,l=n?Symbol.for("react.provider"):60109,c=n?Symbol.for("react.context"):60110,f=n?Symbol.for("react.async_mode"):60111,d=n?Symbol.for("react.concurrent_mode"):60111,h=n?Symbol.for("react.forward_ref"):60112,p=n?Symbol.for("react.suspense"):60113,m=n?Symbol.for("react.suspense_list"):60120,g=n?Symbol.for("react.memo"):60115,v=n?Symbol.for("react.lazy"):60116,y=n?Symbol.for("react.block"):60121,b=n?Symbol.for("react.fundamental"):60117,_=n?Symbol.for("react.responder"):60118,w=n?Symbol.for("react.scope"):60119;function x(t){if("object"==typeof t&&null!==t){var e=t.$$typeof;switch(e){case i:switch(t=t.type){case f:case d:case o:case u:case s:case p:return t;default:switch(t=t&&t.$$typeof){case c:case h:case v:case g:case l:return t;default:return e}}case a:return e}}}function T(t){return x(t)===d}e.AsyncMode=f,e.ConcurrentMode=d,e.ContextConsumer=c,e.ContextProvider=l,e.Element=i,e.ForwardRef=h,e.Fragment=o,e.Lazy=v,e.Memo=g,e.Portal=a,e.Profiler=u,e.StrictMode=s,e.Suspense=p,e.isAsyncMode=function(t){return T(t)||x(t)===f},e.isConcurrentMode=T,e.isContextConsumer=function(t){return x(t)===c},e.isContextProvider=function(t){return x(t)===l},e.isElement=function(t){return"object"==typeof t&&null!==t&&t.$$typeof===i},e.isForwardRef=function(t){return x(t)===h},e.isFragment=function(t){return x(t)===o},e.isLazy=function(t){return x(t)===v},e.isMemo=function(t){return x(t)===g},e.isPortal=function(t){return x(t)===a},e.isProfiler=function(t){return x(t)===u},e.isStrictMode=function(t){return x(t)===s},e.isSuspense=function(t){return x(t)===p},e.isValidElementType=function(t){return"string"==typeof t||"function"==typeof t||t===o||t===d||t===u||t===s||t===p||t===m||"object"==typeof t&&null!==t&&(t.$$typeof===v||t.$$typeof===g||t.$$typeof===l||t.$$typeof===c||t.$$typeof===h||t.$$typeof===b||t.$$typeof===_||t.$$typeof===w||t.$$typeof===y)},e.typeOf=x},qhky:function(t,e,r){"use strict";(function(t){r.d(e,"a",(function(){return mt}));r("E9XD");var n,i,a,o,s=r("17x9"),u=r.n(s),l=r("8+s/"),c=r.n(l),f=r("ZhWT"),d=r.n(f),h=r("q1tI"),p=r.n(h),m=r("YVoz"),g=r.n(m),v="bodyAttributes",y="htmlAttributes",b="titleAttributes",_={BASE:"base",BODY:"body",HEAD:"head",HTML:"html",LINK:"link",META:"meta",NOSCRIPT:"noscript",SCRIPT:"script",STYLE:"style",TITLE:"title"},w=(Object.keys(_).map((function(t){return _[t]})),"charset"),x="cssText",T="href",k="http-equiv",S="innerHTML",O="itemprop",C="name",E="property",A="rel",M="src",P="target",I={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},j="defaultTitle",R="defer",N="encodeSpecialCharacters",z="onChangeClientState",L="titleTemplate",D=Object.keys(I).reduce((function(t,e){return t[I[e]]=e,t}),{}),F=[_.NOSCRIPT,_.SCRIPT,_.STYLE],V="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},q=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},B=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),H=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},U=function(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r},Y=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e},G=function(t){var e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return!1===e?String(t):String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")},$=function(t){var e=J(t,_.TITLE),r=J(t,L);if(r&&e)return r.replace(/%s/g,(function(){return Array.isArray(e)?e.join(""):e}));var n=J(t,j);return e||n||void 0},W=function(t){return J(t,z)||function(){}},X=function(t,e){return e.filter((function(e){return void 0!==e[t]})).map((function(e){return e[t]})).reduce((function(t,e){return H({},t,e)}),{})},Q=function(t,e){return e.filter((function(t){return void 0!==t[_.BASE]})).map((function(t){return t[_.BASE]})).reverse().reduce((function(e,r){if(!e.length)for(var n=Object.keys(r),i=0;i<n.length;i++){var a=n[i].toLowerCase();if(-1!==t.indexOf(a)&&r[a])return e.concat(r)}return e}),[])},Z=function(t,e,r){var n={};return r.filter((function(e){return!!Array.isArray(e[t])||(void 0!==e[t]&&nt("Helmet: "+t+' should be of type "Array". Instead found type "'+V(e[t])+'"'),!1)})).map((function(e){return e[t]})).reverse().reduce((function(t,r){var i={};r.filter((function(t){for(var r=void 0,a=Object.keys(t),o=0;o<a.length;o++){var s=a[o],u=s.toLowerCase();-1===e.indexOf(u)||r===A&&"canonical"===t[r].toLowerCase()||u===A&&"stylesheet"===t[u].toLowerCase()||(r=u),-1===e.indexOf(s)||s!==S&&s!==x&&s!==O||(r=s)}if(!r||!t[r])return!1;var l=t[r].toLowerCase();return n[r]||(n[r]={}),i[r]||(i[r]={}),!n[r][l]&&(i[r][l]=!0,!0)})).reverse().forEach((function(e){return t.push(e)}));for(var a=Object.keys(i),o=0;o<a.length;o++){var s=a[o],u=g()({},n[s],i[s]);n[s]=u}return t}),[]).reverse()},J=function(t,e){for(var r=t.length-1;r>=0;r--){var n=t[r];if(n.hasOwnProperty(e))return n[e]}return null},K=(n=Date.now(),function(t){var e=Date.now();e-n>16?(n=e,t(e)):setTimeout((function(){K(t)}),0)}),tt=function(t){return clearTimeout(t)},et="undefined"!=typeof window?window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||K:t.requestAnimationFrame||K,rt="undefined"!=typeof window?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||tt:t.cancelAnimationFrame||tt,nt=function(t){return console&&"function"==typeof console.warn&&console.warn(t)},it=null,at=function(t,e){var r=t.baseTag,n=t.bodyAttributes,i=t.htmlAttributes,a=t.linkTags,o=t.metaTags,s=t.noscriptTags,u=t.onChangeClientState,l=t.scriptTags,c=t.styleTags,f=t.title,d=t.titleAttributes;ut(_.BODY,n),ut(_.HTML,i),st(f,d);var h={baseTag:lt(_.BASE,r),linkTags:lt(_.LINK,a),metaTags:lt(_.META,o),noscriptTags:lt(_.NOSCRIPT,s),scriptTags:lt(_.SCRIPT,l),styleTags:lt(_.STYLE,c)},p={},m={};Object.keys(h).forEach((function(t){var e=h[t],r=e.newTags,n=e.oldTags;r.length&&(p[t]=r),n.length&&(m[t]=h[t].oldTags)})),e&&e(),u(t,p,m)},ot=function(t){return Array.isArray(t)?t.join(""):t},st=function(t,e){void 0!==t&&document.title!==t&&(document.title=ot(t)),ut(_.TITLE,e)},ut=function(t,e){var r=document.getElementsByTagName(t)[0];if(r){for(var n=r.getAttribute("data-react-helmet"),i=n?n.split(","):[],a=[].concat(i),o=Object.keys(e),s=0;s<o.length;s++){var u=o[s],l=e[u]||"";r.getAttribute(u)!==l&&r.setAttribute(u,l),-1===i.indexOf(u)&&i.push(u);var c=a.indexOf(u);-1!==c&&a.splice(c,1)}for(var f=a.length-1;f>=0;f--)r.removeAttribute(a[f]);i.length===a.length?r.removeAttribute("data-react-helmet"):r.getAttribute("data-react-helmet")!==o.join(",")&&r.setAttribute("data-react-helmet",o.join(","))}},lt=function(t,e){var r=document.head||document.querySelector(_.HEAD),n=r.querySelectorAll(t+"[data-react-helmet]"),i=Array.prototype.slice.call(n),a=[],o=void 0;return e&&e.length&&e.forEach((function(e){var r=document.createElement(t);for(var n in e)if(e.hasOwnProperty(n))if(n===S)r.innerHTML=e.innerHTML;else if(n===x)r.styleSheet?r.styleSheet.cssText=e.cssText:r.appendChild(document.createTextNode(e.cssText));else{var s=void 0===e[n]?"":e[n];r.setAttribute(n,s)}r.setAttribute("data-react-helmet","true"),i.some((function(t,e){return o=e,r.isEqualNode(t)}))?i.splice(o,1):a.push(r)})),i.forEach((function(t){return t.parentNode.removeChild(t)})),a.forEach((function(t){return r.appendChild(t)})),{oldTags:i,newTags:a}},ct=function(t){return Object.keys(t).reduce((function(e,r){var n=void 0!==t[r]?r+'="'+t[r]+'"':""+r;return e?e+" "+n:n}),"")},ft=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(t).reduce((function(e,r){return e[I[r]||r]=t[r],e}),e)},dt=function(t,e,r){switch(t){case _.TITLE:return{toComponent:function(){return t=e.title,r=e.titleAttributes,(n={key:t})["data-react-helmet"]=!0,i=ft(r,n),[p.a.createElement(_.TITLE,i,t)];var t,r,n,i},toString:function(){return function(t,e,r,n){var i=ct(r),a=ot(e);return i?"<"+t+' data-react-helmet="true" '+i+">"+G(a,n)+"</"+t+">":"<"+t+' data-react-helmet="true">'+G(a,n)+"</"+t+">"}(t,e.title,e.titleAttributes,r)}};case v:case y:return{toComponent:function(){return ft(e)},toString:function(){return ct(e)}};default:return{toComponent:function(){return function(t,e){return e.map((function(e,r){var n,i=((n={key:r})["data-react-helmet"]=!0,n);return Object.keys(e).forEach((function(t){var r=I[t]||t;if(r===S||r===x){var n=e.innerHTML||e.cssText;i.dangerouslySetInnerHTML={__html:n}}else i[r]=e[t]})),p.a.createElement(t,i)}))}(t,e)},toString:function(){return function(t,e,r){return e.reduce((function(e,n){var i=Object.keys(n).filter((function(t){return!(t===S||t===x)})).reduce((function(t,e){var i=void 0===n[e]?e:e+'="'+G(n[e],r)+'"';return t?t+" "+i:i}),""),a=n.innerHTML||n.cssText||"",o=-1===F.indexOf(t);return e+"<"+t+' data-react-helmet="true" '+i+(o?"/>":">"+a+"</"+t+">")}),"")}(t,e,r)}}}},ht=function(t){var e=t.baseTag,r=t.bodyAttributes,n=t.encode,i=t.htmlAttributes,a=t.linkTags,o=t.metaTags,s=t.noscriptTags,u=t.scriptTags,l=t.styleTags,c=t.title,f=void 0===c?"":c,d=t.titleAttributes;return{base:dt(_.BASE,e,n),bodyAttributes:dt(v,r,n),htmlAttributes:dt(y,i,n),link:dt(_.LINK,a,n),meta:dt(_.META,o,n),noscript:dt(_.NOSCRIPT,s,n),script:dt(_.SCRIPT,u,n),style:dt(_.STYLE,l,n),title:dt(_.TITLE,{title:f,titleAttributes:d},n)}},pt=c()((function(t){return{baseTag:Q([T,P],t),bodyAttributes:X(v,t),defer:J(t,R),encode:J(t,N),htmlAttributes:X(y,t),linkTags:Z(_.LINK,[A,T],t),metaTags:Z(_.META,[C,w,k,E,O],t),noscriptTags:Z(_.NOSCRIPT,[S],t),onChangeClientState:W(t),scriptTags:Z(_.SCRIPT,[M,S],t),styleTags:Z(_.STYLE,[x],t),title:$(t),titleAttributes:X(b,t)}}),(function(t){it&&rt(it),t.defer?it=et((function(){at(t,(function(){it=null}))})):(at(t),it=null)}),ht)((function(){return null})),mt=(i=pt,o=a=function(t){function e(){return q(this,e),Y(this,t.apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),e.prototype.shouldComponentUpdate=function(t){return!d()(this.props,t)},e.prototype.mapNestedChildrenToProps=function(t,e){if(!e)return null;switch(t.type){case _.SCRIPT:case _.NOSCRIPT:return{innerHTML:e};case _.STYLE:return{cssText:e}}throw new Error("<"+t.type+" /> elements are self-closing and can not contain children. Refer to our API for more information.")},e.prototype.flattenArrayTypeChildren=function(t){var e,r=t.child,n=t.arrayTypeChildren,i=t.newChildProps,a=t.nestedChildren;return H({},n,((e={})[r.type]=[].concat(n[r.type]||[],[H({},i,this.mapNestedChildrenToProps(r,a))]),e))},e.prototype.mapObjectTypeChildren=function(t){var e,r,n=t.child,i=t.newProps,a=t.newChildProps,o=t.nestedChildren;switch(n.type){case _.TITLE:return H({},i,((e={})[n.type]=o,e.titleAttributes=H({},a),e));case _.BODY:return H({},i,{bodyAttributes:H({},a)});case _.HTML:return H({},i,{htmlAttributes:H({},a)})}return H({},i,((r={})[n.type]=H({},a),r))},e.prototype.mapArrayTypeChildrenToProps=function(t,e){var r=H({},e);return Object.keys(t).forEach((function(e){var n;r=H({},r,((n={})[e]=t[e],n))})),r},e.prototype.warnOnInvalidChildren=function(t,e){return!0},e.prototype.mapChildrenToProps=function(t,e){var r=this,n={};return p.a.Children.forEach(t,(function(t){if(t&&t.props){var i=t.props,a=i.children,o=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(t).reduce((function(e,r){return e[D[r]||r]=t[r],e}),e)}(U(i,["children"]));switch(r.warnOnInvalidChildren(t,a),t.type){case _.LINK:case _.META:case _.NOSCRIPT:case _.SCRIPT:case _.STYLE:n=r.flattenArrayTypeChildren({child:t,arrayTypeChildren:n,newChildProps:o,nestedChildren:a});break;default:e=r.mapObjectTypeChildren({child:t,newProps:e,newChildProps:o,nestedChildren:a})}}})),e=this.mapArrayTypeChildrenToProps(n,e)},e.prototype.render=function(){var t=this.props,e=t.children,r=U(t,["children"]),n=H({},r);return e&&(n=this.mapChildrenToProps(e,n)),p.a.createElement(i,n)},B(e,null,[{key:"canUseDOM",set:function(t){i.canUseDOM=t}}]),e}(p.a.Component),a.propTypes={base:u.a.object,bodyAttributes:u.a.object,children:u.a.oneOfType([u.a.arrayOf(u.a.node),u.a.node]),defaultTitle:u.a.string,defer:u.a.bool,encodeSpecialCharacters:u.a.bool,htmlAttributes:u.a.object,link:u.a.arrayOf(u.a.object),meta:u.a.arrayOf(u.a.object),noscript:u.a.arrayOf(u.a.object),onChangeClientState:u.a.func,script:u.a.arrayOf(u.a.object),style:u.a.arrayOf(u.a.object),title:u.a.string,titleAttributes:u.a.object,titleTemplate:u.a.string},a.defaultProps={defer:!0,encodeSpecialCharacters:!0},a.peek=i.peek,a.rewind=function(){var t=i.rewind();return t||(t=ht({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}})),t},o);mt.renderStatic=mt.rewind}).call(this,r("yLpj"))},t1N5:function(t,e,r){var n=r("T016"),i={};for(var a in n)n.hasOwnProperty(a)&&(i[n[a]]=a);var o=t.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var s in o)if(o.hasOwnProperty(s)){if(!("channels"in o[s]))throw new Error("missing channels property: "+s);if(!("labels"in o[s]))throw new Error("missing channel labels property: "+s);if(o[s].labels.length!==o[s].channels)throw new Error("channel and label counts mismatch: "+s);var u=o[s].channels,l=o[s].labels;delete o[s].channels,delete o[s].labels,Object.defineProperty(o[s],"channels",{value:u}),Object.defineProperty(o[s],"labels",{value:l})}o.rgb.hsl=function(t){var e,r,n=t[0]/255,i=t[1]/255,a=t[2]/255,o=Math.min(n,i,a),s=Math.max(n,i,a),u=s-o;return s===o?e=0:n===s?e=(i-a)/u:i===s?e=2+(a-n)/u:a===s&&(e=4+(n-i)/u),(e=Math.min(60*e,360))<0&&(e+=360),r=(o+s)/2,[e,100*(s===o?0:r<=.5?u/(s+o):u/(2-s-o)),100*r]},o.rgb.hsv=function(t){var e,r,n,i,a,o=t[0]/255,s=t[1]/255,u=t[2]/255,l=Math.max(o,s,u),c=l-Math.min(o,s,u),f=function(t){return(l-t)/6/c+.5};return 0===c?i=a=0:(a=c/l,e=f(o),r=f(s),n=f(u),o===l?i=n-r:s===l?i=1/3+e-n:u===l&&(i=2/3+r-e),i<0?i+=1:i>1&&(i-=1)),[360*i,100*a,100*l]},o.rgb.hwb=function(t){var e=t[0],r=t[1],n=t[2];return[o.rgb.hsl(t)[0],100*(1/255*Math.min(e,Math.min(r,n))),100*(n=1-1/255*Math.max(e,Math.max(r,n)))]},o.rgb.cmyk=function(t){var e,r=t[0]/255,n=t[1]/255,i=t[2]/255;return[100*((1-r-(e=Math.min(1-r,1-n,1-i)))/(1-e)||0),100*((1-n-e)/(1-e)||0),100*((1-i-e)/(1-e)||0),100*e]},o.rgb.keyword=function(t){var e=i[t];if(e)return e;var r,a,o,s=1/0;for(var u in n)if(n.hasOwnProperty(u)){var l=n[u],c=(a=t,o=l,Math.pow(a[0]-o[0],2)+Math.pow(a[1]-o[1],2)+Math.pow(a[2]-o[2],2));c<s&&(s=c,r=u)}return r},o.keyword.rgb=function(t){return n[t]},o.rgb.xyz=function(t){var e=t[0]/255,r=t[1]/255,n=t[2]/255;return[100*(.4124*(e=e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92)+.3576*(r=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92)+.1805*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)),100*(.2126*e+.7152*r+.0722*n),100*(.0193*e+.1192*r+.9505*n)]},o.rgb.lab=function(t){var e=o.rgb.xyz(t),r=e[0],n=e[1],i=e[2];return n/=100,i/=108.883,r=(r/=95.047)>.008856?Math.pow(r,1/3):7.787*r+16/116,[116*(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116)-16,500*(r-n),200*(n-(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116))]},o.hsl.rgb=function(t){var e,r,n,i,a,o=t[0]/360,s=t[1]/100,u=t[2]/100;if(0===s)return[a=255*u,a,a];e=2*u-(r=u<.5?u*(1+s):u+s-u*s),i=[0,0,0];for(var l=0;l<3;l++)(n=o+1/3*-(l-1))<0&&n++,n>1&&n--,a=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,i[l]=255*a;return i},o.hsl.hsv=function(t){var e=t[0],r=t[1]/100,n=t[2]/100,i=r,a=Math.max(n,.01);return r*=(n*=2)<=1?n:2-n,i*=a<=1?a:2-a,[e,100*(0===n?2*i/(a+i):2*r/(n+r)),100*((n+r)/2)]},o.hsv.rgb=function(t){var e=t[0]/60,r=t[1]/100,n=t[2]/100,i=Math.floor(e)%6,a=e-Math.floor(e),o=255*n*(1-r),s=255*n*(1-r*a),u=255*n*(1-r*(1-a));switch(n*=255,i){case 0:return[n,u,o];case 1:return[s,n,o];case 2:return[o,n,u];case 3:return[o,s,n];case 4:return[u,o,n];case 5:return[n,o,s]}},o.hsv.hsl=function(t){var e,r,n,i=t[0],a=t[1]/100,o=t[2]/100,s=Math.max(o,.01);return n=(2-a)*o,r=a*s,[i,100*(r=(r/=(e=(2-a)*s)<=1?e:2-e)||0),100*(n/=2)]},o.hwb.rgb=function(t){var e,r,n,i,a,o,s,u=t[0]/360,l=t[1]/100,c=t[2]/100,f=l+c;switch(f>1&&(l/=f,c/=f),n=6*u-(e=Math.floor(6*u)),0!=(1&e)&&(n=1-n),i=l+n*((r=1-c)-l),e){default:case 6:case 0:a=r,o=i,s=l;break;case 1:a=i,o=r,s=l;break;case 2:a=l,o=r,s=i;break;case 3:a=l,o=i,s=r;break;case 4:a=i,o=l,s=r;break;case 5:a=r,o=l,s=i}return[255*a,255*o,255*s]},o.cmyk.rgb=function(t){var e=t[0]/100,r=t[1]/100,n=t[2]/100,i=t[3]/100;return[255*(1-Math.min(1,e*(1-i)+i)),255*(1-Math.min(1,r*(1-i)+i)),255*(1-Math.min(1,n*(1-i)+i))]},o.xyz.rgb=function(t){var e,r,n,i=t[0]/100,a=t[1]/100,o=t[2]/100;return r=-.9689*i+1.8758*a+.0415*o,n=.0557*i+-.204*a+1.057*o,e=(e=3.2406*i+-1.5372*a+-.4986*o)>.0031308?1.055*Math.pow(e,1/2.4)-.055:12.92*e,r=r>.0031308?1.055*Math.pow(r,1/2.4)-.055:12.92*r,n=n>.0031308?1.055*Math.pow(n,1/2.4)-.055:12.92*n,[255*(e=Math.min(Math.max(0,e),1)),255*(r=Math.min(Math.max(0,r),1)),255*(n=Math.min(Math.max(0,n),1))]},o.xyz.lab=function(t){var e=t[0],r=t[1],n=t[2];return r/=100,n/=108.883,e=(e/=95.047)>.008856?Math.pow(e,1/3):7.787*e+16/116,[116*(r=r>.008856?Math.pow(r,1/3):7.787*r+16/116)-16,500*(e-r),200*(r-(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116))]},o.lab.xyz=function(t){var e,r,n,i=t[0];e=t[1]/500+(r=(i+16)/116),n=r-t[2]/200;var a=Math.pow(r,3),o=Math.pow(e,3),s=Math.pow(n,3);return r=a>.008856?a:(r-16/116)/7.787,e=o>.008856?o:(e-16/116)/7.787,n=s>.008856?s:(n-16/116)/7.787,[e*=95.047,r*=100,n*=108.883]},o.lab.lch=function(t){var e,r=t[0],n=t[1],i=t[2];return(e=360*Math.atan2(i,n)/2/Math.PI)<0&&(e+=360),[r,Math.sqrt(n*n+i*i),e]},o.lch.lab=function(t){var e,r=t[0],n=t[1];return e=t[2]/360*2*Math.PI,[r,n*Math.cos(e),n*Math.sin(e)]},o.rgb.ansi16=function(t){var e=t[0],r=t[1],n=t[2],i=1 in arguments?arguments[1]:o.rgb.hsv(t)[2];if(0===(i=Math.round(i/50)))return 30;var a=30+(Math.round(n/255)<<2|Math.round(r/255)<<1|Math.round(e/255));return 2===i&&(a+=60),a},o.hsv.ansi16=function(t){return o.rgb.ansi16(o.hsv.rgb(t),t[2])},o.rgb.ansi256=function(t){var e=t[0],r=t[1],n=t[2];return e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},o.ansi16.rgb=function(t){var e=t%10;if(0===e||7===e)return t>50&&(e+=3.5),[e=e/10.5*255,e,e];var r=.5*(1+~~(t>50));return[(1&e)*r*255,(e>>1&1)*r*255,(e>>2&1)*r*255]},o.ansi256.rgb=function(t){if(t>=232){var e=10*(t-232)+8;return[e,e,e]}var r;return t-=16,[Math.floor(t/36)/5*255,Math.floor((r=t%36)/6)/5*255,r%6/5*255]},o.rgb.hex=function(t){var e=(((255&Math.round(t[0]))<<16)+((255&Math.round(t[1]))<<8)+(255&Math.round(t[2]))).toString(16).toUpperCase();return"000000".substring(e.length)+e},o.hex.rgb=function(t){var e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];var r=e[0];3===e[0].length&&(r=r.split("").map((function(t){return t+t})).join(""));var n=parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},o.rgb.hcg=function(t){var e,r=t[0]/255,n=t[1]/255,i=t[2]/255,a=Math.max(Math.max(r,n),i),o=Math.min(Math.min(r,n),i),s=a-o;return e=s<=0?0:a===r?(n-i)/s%6:a===n?2+(i-r)/s:4+(r-n)/s+4,e/=6,[360*(e%=1),100*s,100*(s<1?o/(1-s):0)]},o.hsl.hcg=function(t){var e=t[1]/100,r=t[2]/100,n=1,i=0;return(n=r<.5?2*e*r:2*e*(1-r))<1&&(i=(r-.5*n)/(1-n)),[t[0],100*n,100*i]},o.hsv.hcg=function(t){var e=t[1]/100,r=t[2]/100,n=e*r,i=0;return n<1&&(i=(r-n)/(1-n)),[t[0],100*n,100*i]},o.hcg.rgb=function(t){var e=t[0]/360,r=t[1]/100,n=t[2]/100;if(0===r)return[255*n,255*n,255*n];var i,a=[0,0,0],o=e%1*6,s=o%1,u=1-s;switch(Math.floor(o)){case 0:a[0]=1,a[1]=s,a[2]=0;break;case 1:a[0]=u,a[1]=1,a[2]=0;break;case 2:a[0]=0,a[1]=1,a[2]=s;break;case 3:a[0]=0,a[1]=u,a[2]=1;break;case 4:a[0]=s,a[1]=0,a[2]=1;break;default:a[0]=1,a[1]=0,a[2]=u}return i=(1-r)*n,[255*(r*a[0]+i),255*(r*a[1]+i),255*(r*a[2]+i)]},o.hcg.hsv=function(t){var e=t[1]/100,r=e+t[2]/100*(1-e),n=0;return r>0&&(n=e/r),[t[0],100*n,100*r]},o.hcg.hsl=function(t){var e=t[1]/100,r=t[2]/100*(1-e)+.5*e,n=0;return r>0&&r<.5?n=e/(2*r):r>=.5&&r<1&&(n=e/(2*(1-r))),[t[0],100*n,100*r]},o.hcg.hwb=function(t){var e=t[1]/100,r=e+t[2]/100*(1-e);return[t[0],100*(r-e),100*(1-r)]},o.hwb.hcg=function(t){var e=t[1]/100,r=1-t[2]/100,n=r-e,i=0;return n<1&&(i=(r-n)/(1-n)),[t[0],100*n,100*i]},o.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]},o.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]},o.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]},o.gray.hsl=o.gray.hsv=function(t){return[0,0,t[0]]},o.gray.hwb=function(t){return[0,100,t[0]]},o.gray.cmyk=function(t){return[0,0,0,t[0]]},o.gray.lab=function(t){return[t[0],0,0]},o.gray.hex=function(t){var e=255&Math.round(t[0]/100*255),r=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(r.length)+r},o.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}},tiwY:function(t,e,r){"use strict";var n=r("8OQS"),i=r("PJYZ"),a=r("VbXa"),o=r("TqRt"),s=r("284h");e.__esModule=!0,e.default=void 0;var u=o(r("pVnL")),l=s(r("q1tI")),c=s(r("plVc")),f=o(r("z/o8")),d="/Users/tyler/Documents/GitHub/gatsby-plugins/transition-link/gatsby-plugin-transition-link/src/AniLink/Cover.js",h=function(t){function e(e){var r;return(r=t.call(this,e)||this).getCoverEl=function(){return document.querySelector(".tl-cover-el")},r.horizontal=function(t){var e=t.node,n=t.props.length,i=t.direction,a="left"===i?"-100%":"100%",o="left"===i?"100%":"-100%",s=n/6,u=(n-s)/2,l=r.getCoverEl();return f.default.timeline().set(l,{y:0,x:o,display:"block"}).to(l,{x:"0%",ease:"power1.easeInOut",duration:u}).set(e,{opacity:0}).to(l,{x:a,ease:"power1.easeInOut",duration:u},"+="+s)},r.vertical=function(t){var e=t.node,n=t.props.length,i=t.direction,a="up"===i?"-100%":"100%",o="up"===i?"100%":"-100%",s=n/6,u=(n-s)/2,l=r.getCoverEl();return f.default.timeline().set(l,{y:o}).to(l,{y:"0%",ease:"power1.easeInOut",duration:u}).set(e,{opacity:0}).to(l,{y:a,ease:"power1.easeIn",duration:u},"+="+s)},r.moveInDirection=function(t){var e=t.props,n=t.direction,i=t.node;return"left"===n||"right"===n?r.horizontal({props:e,direction:n,node:i}):r.vertical({props:e,direction:n,node:i})},r.horizontal=r.horizontal.bind(i(r)),r.vertical=r.vertical.bind(i(r)),r}return a(e,t),e.prototype.render=function(){var t=this,e=this.props.direction||"left",r=this.props.duration||1,i=this.props,a=(i.exit,i.entry,i.cover,n(i,["exit","entry","cover"]));return l.default.createElement(l.default.Fragment,null,l.default.createElement(c.default,(0,u.default)({exit:{length:r,trigger:function(r){var n=r.exit,i=r.node;return t.moveInDirection({props:n,node:i,direction:e})}},entry:{delay:r/2}},a,{__self:this,__source:{fileName:d,lineNumber:92,columnNumber:5}}),this.props.children),l.default.createElement(c.TransitionPortal,{__self:this,__source:{fileName:d,lineNumber:110,columnNumber:5}},l.default.createElement("div",{className:"tl-cover-el",style:{position:"fixed",background:this.props.bg||"#4b2571",top:0,left:0,right:0,zIndex:1e3,width:"100vw",height:"100vh",transform:"translateY(100%)"},__self:this,__source:{fileName:d,lineNumber:111,columnNumber:6}})))},e}(l.Component);e.default=h},uxXc:function(t,e,r){var n=r("t1N5"),i=r("onlc"),a={};Object.keys(n).forEach((function(t){a[t]={},Object.defineProperty(a[t],"channels",{value:n[t].channels}),Object.defineProperty(a[t],"labels",{value:n[t].labels});var e=i(t);Object.keys(e).forEach((function(r){var n=e[r];a[t][r]=function(t){var e=function(e){if(null==e)return e;arguments.length>1&&(e=Array.prototype.slice.call(arguments));var r=t(e);if("object"==typeof r)for(var n=r.length,i=0;i<n;i++)r[i]=Math.round(r[i]);return r};return"conversion"in t&&(e.conversion=t.conversion),e}(n),a[t][r].raw=function(t){var e=function(e){return null==e?e:(arguments.length>1&&(e=Array.prototype.slice.call(arguments)),t(e))};return"conversion"in t&&(e.conversion=t.conversion),e}(n)}))})),t.exports=a},vOnD:function(t,e,r){"use strict";(function(t){r.d(e,"a",(function(){return jt})),r.d(e,"b",(function(){return vt}));r("E9XD");var n=r("TOwV"),i=r("q1tI"),a=r.n(i),o=r("Gytx"),s=r.n(o),u=r("0x0X"),l=r("ME5O"),c=r("9uj6"),f=r("2mql"),d=r.n(f);function h(){return(h=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}var p=function(t,e){for(var r=[t[0]],n=0,i=e.length;n<i;n+=1)r.push(e[n],t[n+1]);return r},m=function(t){return null!==t&&"object"==typeof t&&"[object Object]"===(t.toString?t.toString():Object.prototype.toString.call(t))&&!Object(n.typeOf)(t)},g=Object.freeze([]),v=Object.freeze({});function y(t){return"function"==typeof t}function b(t){return t.displayName||t.name||"Component"}function _(t){return t&&"string"==typeof t.styledComponentId}var w=void 0!==t&&({}.REACT_APP_SC_ATTR||{}.SC_ATTR)||"data-styled",x="undefined"!=typeof window&&"HTMLElement"in window,T=Boolean("boolean"==typeof SC_DISABLE_SPEEDY?SC_DISABLE_SPEEDY:void 0!==t&&void 0!=={}.REACT_APP_SC_DISABLE_SPEEDY&&""!=={}.REACT_APP_SC_DISABLE_SPEEDY?"false"!=={}.REACT_APP_SC_DISABLE_SPEEDY&&{}.REACT_APP_SC_DISABLE_SPEEDY:void 0!==t&&void 0!=={}.SC_DISABLE_SPEEDY&&""!=={}.SC_DISABLE_SPEEDY&&("false"!=={}.SC_DISABLE_SPEEDY&&{}.SC_DISABLE_SPEEDY)),k={};function S(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;n<e;n++)r[n-1]=arguments[n];throw new Error("An error occurred. See https://git.io/JUIaE#"+t+" for more information."+(r.length>0?" Args: "+r.join(", "):""))}var O=function(){function t(t){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=t}var e=t.prototype;return e.indexOfGroup=function(t){for(var e=0,r=0;r<t;r++)e+=this.groupSizes[r];return e},e.insertRules=function(t,e){if(t>=this.groupSizes.length){for(var r=this.groupSizes,n=r.length,i=n;t>=i;)(i<<=1)<0&&S(16,""+t);this.groupSizes=new Uint32Array(i),this.groupSizes.set(r),this.length=i;for(var a=n;a<i;a++)this.groupSizes[a]=0}for(var o=this.indexOfGroup(t+1),s=0,u=e.length;s<u;s++)this.tag.insertRule(o,e[s])&&(this.groupSizes[t]++,o++)},e.clearGroup=function(t){if(t<this.length){var e=this.groupSizes[t],r=this.indexOfGroup(t),n=r+e;this.groupSizes[t]=0;for(var i=r;i<n;i++)this.tag.deleteRule(r)}},e.getGroup=function(t){var e="";if(t>=this.length||0===this.groupSizes[t])return e;for(var r=this.groupSizes[t],n=this.indexOfGroup(t),i=n+r,a=n;a<i;a++)e+=this.tag.getRule(a)+"/*!sc*/\n";return e},t}(),C=new Map,E=new Map,A=1,M=function(t){if(C.has(t))return C.get(t);for(;E.has(A);)A++;var e=A++;return C.set(t,e),E.set(e,t),e},P=function(t){return E.get(t)},I=function(t,e){C.set(t,e),E.set(e,t)},j="style["+w+'][data-styled-version="5.2.1"]',R=new RegExp("^"+w+'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)'),N=function(t,e,r){for(var n,i=r.split(","),a=0,o=i.length;a<o;a++)(n=i[a])&&t.registerName(e,n)},z=function(t,e){for(var r=e.innerHTML.split("/*!sc*/\n"),n=[],i=0,a=r.length;i<a;i++){var o=r[i].trim();if(o){var s=o.match(R);if(s){var u=0|parseInt(s[1],10),l=s[2];0!==u&&(I(l,u),N(t,l,s[3]),t.getTag().insertRules(u,n)),n.length=0}else n.push(o)}}},L=function(){return r.nc},D=function(t){var e=document.head,r=t||e,n=document.createElement("style"),i=function(t){for(var e=t.childNodes,r=e.length;r>=0;r--){var n=e[r];if(n&&1===n.nodeType&&n.hasAttribute(w))return n}}(r),a=void 0!==i?i.nextSibling:null;n.setAttribute(w,"active"),n.setAttribute("data-styled-version","5.2.1");var o=L();return o&&n.setAttribute("nonce",o),r.insertBefore(n,a),n},F=function(){function t(t){var e=this.element=D(t);e.appendChild(document.createTextNode("")),this.sheet=function(t){if(t.sheet)return t.sheet;for(var e=document.styleSheets,r=0,n=e.length;r<n;r++){var i=e[r];if(i.ownerNode===t)return i}S(17)}(e),this.length=0}var e=t.prototype;return e.insertRule=function(t,e){try{return this.sheet.insertRule(e,t),this.length++,!0}catch(t){return!1}},e.deleteRule=function(t){this.sheet.deleteRule(t),this.length--},e.getRule=function(t){var e=this.sheet.cssRules[t];return void 0!==e&&"string"==typeof e.cssText?e.cssText:""},t}(),V=function(){function t(t){var e=this.element=D(t);this.nodes=e.childNodes,this.length=0}var e=t.prototype;return e.insertRule=function(t,e){if(t<=this.length&&t>=0){var r=document.createTextNode(e),n=this.nodes[t];return this.element.insertBefore(r,n||null),this.length++,!0}return!1},e.deleteRule=function(t){this.element.removeChild(this.nodes[t]),this.length--},e.getRule=function(t){return t<this.length?this.nodes[t].textContent:""},t}(),q=function(){function t(t){this.rules=[],this.length=0}var e=t.prototype;return e.insertRule=function(t,e){return t<=this.length&&(this.rules.splice(t,0,e),this.length++,!0)},e.deleteRule=function(t){this.rules.splice(t,1),this.length--},e.getRule=function(t){return t<this.length?this.rules[t]:""},t}(),B=x,H={isServer:!x,useCSSOMInjection:!T},U=function(){function t(t,e,r){void 0===t&&(t=v),void 0===e&&(e={}),this.options=h({},H,{},t),this.gs=e,this.names=new Map(r),!this.options.isServer&&x&&B&&(B=!1,function(t){for(var e=document.querySelectorAll(j),r=0,n=e.length;r<n;r++){var i=e[r];i&&"active"!==i.getAttribute(w)&&(z(t,i),i.parentNode&&i.parentNode.removeChild(i))}}(this))}t.registerId=function(t){return M(t)};var e=t.prototype;return e.reconstructWithOptions=function(e,r){return void 0===r&&(r=!0),new t(h({},this.options,{},e),this.gs,r&&this.names||void 0)},e.allocateGSInstance=function(t){return this.gs[t]=(this.gs[t]||0)+1},e.getTag=function(){return this.tag||(this.tag=(r=(e=this.options).isServer,n=e.useCSSOMInjection,i=e.target,t=r?new q(i):n?new F(i):new V(i),new O(t)));var t,e,r,n,i},e.hasNameForId=function(t,e){return this.names.has(t)&&this.names.get(t).has(e)},e.registerName=function(t,e){if(M(t),this.names.has(t))this.names.get(t).add(e);else{var r=new Set;r.add(e),this.names.set(t,r)}},e.insertRules=function(t,e,r){this.registerName(t,e),this.getTag().insertRules(M(t),r)},e.clearNames=function(t){this.names.has(t)&&this.names.get(t).clear()},e.clearRules=function(t){this.getTag().clearGroup(M(t)),this.clearNames(t)},e.clearTag=function(){this.tag=void 0},e.toString=function(){return function(t){for(var e=t.getTag(),r=e.length,n="",i=0;i<r;i++){var a=P(i);if(void 0!==a){var o=t.names.get(a),s=e.getGroup(i);if(void 0!==o&&0!==s.length){var u=w+".g"+i+'[id="'+a+'"]',l="";void 0!==o&&o.forEach((function(t){t.length>0&&(l+=t+",")})),n+=""+s+u+'{content:"'+l+'"}/*!sc*/\n'}}}return n}(this)},t}(),Y=/(a)(d)/gi,G=function(t){return String.fromCharCode(t+(t>25?39:97))};function $(t){var e,r="";for(e=Math.abs(t);e>52;e=e/52|0)r=G(e%52)+r;return(G(e%52)+r).replace(Y,"$1-$2")}var W=function(t,e){for(var r=e.length;r;)t=33*t^e.charCodeAt(--r);return t},X=function(t){return W(5381,t)};function Q(t){for(var e=0;e<t.length;e+=1){var r=t[e];if(y(r)&&!_(r))return!1}return!0}var Z=X("5.2.1"),J=function(){function t(t,e,r){this.rules=t,this.staticRulesId="",this.isStatic=(void 0===r||r.isStatic)&&Q(t),this.componentId=e,this.baseHash=W(Z,e),this.baseStyle=r,U.registerId(e)}return t.prototype.generateAndInjectStyles=function(t,e,r){var n=this.componentId,i=[];if(this.baseStyle&&i.push(this.baseStyle.generateAndInjectStyles(t,e,r)),this.isStatic&&!r.hash)if(this.staticRulesId&&e.hasNameForId(n,this.staticRulesId))i.push(this.staticRulesId);else{var a=gt(this.rules,t,e,r).join(""),o=$(W(this.baseHash,a.length)>>>0);if(!e.hasNameForId(n,o)){var s=r(a,"."+o,void 0,n);e.insertRules(n,o,s)}i.push(o),this.staticRulesId=o}else{for(var u=this.rules.length,l=W(this.baseHash,r.hash),c="",f=0;f<u;f++){var d=this.rules[f];if("string"==typeof d)c+=d;else if(d){var h=gt(d,t,e,r),p=Array.isArray(h)?h.join(""):h;l=W(l,p+f),c+=p}}if(c){var m=$(l>>>0);if(!e.hasNameForId(n,m)){var g=r(c,"."+m,void 0,n);e.insertRules(n,m,g)}i.push(m)}}return i.join(" ")},t}(),K=/^\s*\/\/.*$/gm,tt=[":","[",".","#"];function et(t){var e,r,n,i,a=void 0===t?v:t,o=a.options,s=void 0===o?v:o,l=a.plugins,c=void 0===l?g:l,f=new u.a(s),d=[],h=function(t){function e(e){if(e)try{t(e+"}")}catch(t){}}return function(r,n,i,a,o,s,u,l,c,f){switch(r){case 1:if(0===c&&64===n.charCodeAt(0))return t(n+";"),"";break;case 2:if(0===l)return n+"/*|*/";break;case 3:switch(l){case 102:case 112:return t(i[0]+n),"";default:return n+(0===f?"/*|*/":"")}case-2:n.split("/*|*/}").forEach(e)}}}((function(t){d.push(t)})),p=function(t,n,a){return 0===n&&tt.includes(a[r.length])||a.match(i)?t:"."+e};function m(t,a,o,s){void 0===s&&(s="&");var u=t.replace(K,""),l=a&&o?o+" "+a+" { "+u+" }":u;return e=s,r=a,n=new RegExp("\\"+r+"\\b","g"),i=new RegExp("(\\"+r+"\\b){2,}"),f(o||!a?"":a,l)}return f.use([].concat(c,[function(t,e,i){2===t&&i.length&&i[0].lastIndexOf(r)>0&&(i[0]=i[0].replace(n,p))},h,function(t){if(-2===t){var e=d;return d=[],e}}])),m.hash=c.length?c.reduce((function(t,e){return e.name||S(15),W(t,e.name)}),5381).toString():"",m}var rt=a.a.createContext(),nt=(rt.Consumer,a.a.createContext()),it=(nt.Consumer,new U),at=et();function ot(){return Object(i.useContext)(rt)||it}function st(){return Object(i.useContext)(nt)||at}function ut(t){var e=Object(i.useState)(t.stylisPlugins),r=e[0],n=e[1],o=ot(),u=Object(i.useMemo)((function(){var e=o;return t.sheet?e=t.sheet:t.target&&(e=e.reconstructWithOptions({target:t.target},!1)),t.disableCSSOMInjection&&(e=e.reconstructWithOptions({useCSSOMInjection:!1})),e}),[t.disableCSSOMInjection,t.sheet,t.target]),l=Object(i.useMemo)((function(){return et({options:{prefix:!t.disableVendorPrefixes},plugins:r})}),[t.disableVendorPrefixes,r]);return Object(i.useEffect)((function(){s()(r,t.stylisPlugins)||n(t.stylisPlugins)}),[t.stylisPlugins]),a.a.createElement(rt.Provider,{value:u},a.a.createElement(nt.Provider,{value:l},t.children))}var lt=function(){function t(t,e){var r=this;this.inject=function(t,e){void 0===e&&(e=at);var n=r.name+e.hash;t.hasNameForId(r.id,n)||t.insertRules(r.id,n,e(r.rules,n,"@keyframes"))},this.toString=function(){return S(12,String(r.name))},this.name=t,this.id="sc-keyframes-"+t,this.rules=e}return t.prototype.getName=function(t){return void 0===t&&(t=at),this.name+t.hash},t}(),ct=/([A-Z])/,ft=/([A-Z])/g,dt=/^ms-/,ht=function(t){return"-"+t.toLowerCase()};function pt(t){return ct.test(t)?t.replace(ft,ht).replace(dt,"-ms-"):t}var mt=function(t){return null==t||!1===t||""===t};function gt(t,e,r,n){if(Array.isArray(t)){for(var i,a=[],o=0,s=t.length;o<s;o+=1)""!==(i=gt(t[o],e,r,n))&&(Array.isArray(i)?a.push.apply(a,i):a.push(i));return a}return mt(t)?"":_(t)?"."+t.styledComponentId:y(t)?"function"!=typeof(u=t)||u.prototype&&u.prototype.isReactComponent||!e?t:gt(t(e),e,r,n):t instanceof lt?r?(t.inject(r,n),t.getName(n)):t:m(t)?function t(e,r){var n,i,a=[];for(var o in e)e.hasOwnProperty(o)&&!mt(e[o])&&(m(e[o])?a.push.apply(a,t(e[o],o)):y(e[o])?a.push(pt(o)+":",e[o],";"):a.push(pt(o)+": "+(n=o,(null==(i=e[o])||"boolean"==typeof i||""===i?"":"number"!=typeof i||0===i||n in l.a?String(i).trim():i+"px")+";")));return r?[r+" {"].concat(a,["}"]):a}(t):t.toString();var u}function vt(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;n<e;n++)r[n-1]=arguments[n];return y(t)||m(t)?gt(p(g,[t].concat(r))):0===r.length&&1===t.length&&"string"==typeof t[0]?t:gt(p(t,r))}new Set;var yt=function(t,e,r){return void 0===r&&(r=v),t.theme!==r.theme&&t.theme||e||r.theme},bt=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,_t=/(^-|-$)/g;function wt(t){return t.replace(bt,"-").replace(_t,"")}var xt=function(t){return $(X(t)>>>0)};function Tt(t){return"string"==typeof t&&!0}var kt=function(t){return"function"==typeof t||"object"==typeof t&&null!==t&&!Array.isArray(t)},St=function(t){return"__proto__"!==t&&"constructor"!==t&&"prototype"!==t};function Ot(t,e,r){var n=t[r];kt(e)&&kt(n)?Ct(n,e):t[r]=e}function Ct(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;n<e;n++)r[n-1]=arguments[n];for(var i=0,a=r;i<a.length;i++){var o=a[i];if(kt(o))for(var s in o)St(s)&&Ot(t,o[s],s)}return t}var Et=a.a.createContext();Et.Consumer;var At={};function Mt(t,e,r){var n=_(t),o=!Tt(t),s=e.attrs,u=void 0===s?g:s,l=e.componentId,f=void 0===l?function(t,e){var r="string"!=typeof t?"sc":wt(t);At[r]=(At[r]||0)+1;var n=r+"-"+xt("5.2.1"+r+At[r]);return e?e+"-"+n:n}(e.displayName,e.parentComponentId):l,p=e.displayName,m=void 0===p?function(t){return Tt(t)?"styled."+t:"Styled("+b(t)+")"}(t):p,w=e.displayName&&e.componentId?wt(e.displayName)+"-"+e.componentId:e.componentId||f,x=n&&t.attrs?Array.prototype.concat(t.attrs,u).filter(Boolean):u,T=e.shouldForwardProp;n&&t.shouldForwardProp&&(T=e.shouldForwardProp?function(r,n){return t.shouldForwardProp(r,n)&&e.shouldForwardProp(r,n)}:t.shouldForwardProp);var k,S=new J(r,w,n?t.componentStyle:void 0),O=S.isStatic&&0===u.length,C=function(t,e){return function(t,e,r,n){var a=t.attrs,o=t.componentStyle,s=t.defaultProps,u=t.foldedComponentIds,l=t.shouldForwardProp,f=t.styledComponentId,d=t.target,p=function(t,e,r){void 0===t&&(t=v);var n=h({},e,{theme:t}),i={};return r.forEach((function(t){var e,r,a,o=t;for(e in y(o)&&(o=o(n)),o)n[e]=i[e]="className"===e?(r=i[e],a=o[e],r&&a?r+" "+a:r||a):o[e]})),[n,i]}(yt(e,Object(i.useContext)(Et),s)||v,e,a),m=p[0],g=p[1],b=function(t,e,r,n){var i=ot(),a=st();return e?t.generateAndInjectStyles(v,i,a):t.generateAndInjectStyles(r,i,a)}(o,n,m),_=r,w=g.$as||e.$as||g.as||e.as||d,x=Tt(w),T=g!==e?h({},e,{},g):e,k={};for(var S in T)"$"!==S[0]&&"as"!==S&&("forwardedAs"===S?k.as=T[S]:(l?l(S,c.a):!x||Object(c.a)(S))&&(k[S]=T[S]));return e.style&&g.style!==e.style&&(k.style=h({},e.style,{},g.style)),k.className=Array.prototype.concat(u,f,b!==f?b:null,e.className,g.className).filter(Boolean).join(" "),k.ref=_,Object(i.createElement)(w,k)}(k,t,e,O)};return C.displayName=m,(k=a.a.forwardRef(C)).attrs=x,k.componentStyle=S,k.displayName=m,k.shouldForwardProp=T,k.foldedComponentIds=n?Array.prototype.concat(t.foldedComponentIds,t.styledComponentId):g,k.styledComponentId=w,k.target=n?t.target:t,k.withComponent=function(t){var n=e.componentId,i=function(t,e){if(null==t)return{};var r,n,i={},a=Object.keys(t);for(n=0;n<a.length;n++)r=a[n],e.indexOf(r)>=0||(i[r]=t[r]);return i}(e,["componentId"]),a=n&&n+"-"+(Tt(t)?t:wt(b(t)));return Mt(t,h({},i,{attrs:x,componentId:a}),r)},Object.defineProperty(k,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(e){this._foldedDefaultProps=n?Ct({},t.defaultProps,e):e}}),k.toString=function(){return"."+k.styledComponentId},o&&d()(k,t,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0,withComponent:!0}),k}var Pt=function(t){return function t(e,r,i){if(void 0===i&&(i=v),!Object(n.isValidElementType)(r))return S(1,String(r));var a=function(){return e(r,i,vt.apply(void 0,arguments))};return a.withConfig=function(n){return t(e,r,h({},i,{},n))},a.attrs=function(n){return t(e,r,h({},i,{attrs:Array.prototype.concat(i.attrs,n).filter(Boolean)}))},a}(Mt,t)};["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"].forEach((function(t){Pt[t]=Pt(t)}));var It=function(){function t(t,e){this.rules=t,this.componentId=e,this.isStatic=Q(t),U.registerId(this.componentId+1)}var e=t.prototype;return e.createStyles=function(t,e,r,n){var i=n(gt(this.rules,e,r,n).join(""),""),a=this.componentId+t;r.insertRules(a,a,i)},e.removeStyles=function(t,e){e.clearRules(this.componentId+t)},e.renderStyles=function(t,e,r,n){t>2&&U.registerId(this.componentId+t),this.removeStyles(t,r),this.createStyles(t,e,r,n)},t}();function jt(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;n<e;n++)r[n-1]=arguments[n];var o=vt.apply(void 0,[t].concat(r)),s="sc-global-"+xt(JSON.stringify(o)),u=new It(o,s);function l(t){var e=ot(),r=st(),n=Object(i.useContext)(Et),a=Object(i.useRef)(e.allocateGSInstance(s)).current;return Object(i.useLayoutEffect)((function(){return c(a,t,e,n,r),function(){return u.removeStyles(a,e)}}),[a,t,e,n,r]),null}function c(t,e,r,n,i){if(u.isStatic)u.renderStyles(t,k,r,i);else{var a=h({},e,{theme:yt(e,n,l.defaultProps)});u.renderStyles(t,a,r,i)}}return a.a.memo(l)}!function(){function t(){var t=this;this._emitSheetCSS=function(){var e=t.instance.toString(),r=L();return"<style "+[r&&'nonce="'+r+'"',w+'="true"','data-styled-version="5.2.1"'].filter(Boolean).join(" ")+">"+e+"</style>"},this.getStyleTags=function(){return t.sealed?S(2):t._emitSheetCSS()},this.getStyleElement=function(){var e;if(t.sealed)return S(2);var r=((e={})[w]="",e["data-styled-version"]="5.2.1",e.dangerouslySetInnerHTML={__html:t.instance.toString()},e),n=L();return n&&(r.nonce=n),[a.a.createElement("style",h({},r,{key:"sc-0-0"}))]},this.seal=function(){t.sealed=!0},this.instance=new U({isServer:!0}),this.sealed=!1}var e=t.prototype;e.collectStyles=function(t){return this.sealed?S(2):a.a.createElement(ut,{sheet:this.instance},t)},e.interleaveWithNodeStream=function(t){return S(3)}}();e.c=Pt}).call(this,r("8oxB"))},vrFN:function(t,e,r){"use strict";var n=r("q1tI"),i=r.n(n),a=r("qhky"),o=r("Wbzz");function s(t){var e,r,n=t.description,s=t.lang,u=t.meta,l=t.title,c=t.image,f=Object(o.useStaticQuery)("764694655").site,d=n||f.siteMetadata.description,h=null===(e=f.siteMetadata)||void 0===e?void 0:e.title,p=""+f.siteMetadata.siteUrl+(c||"assets/img/cover.img");return i.a.createElement(a.a,{htmlAttributes:{lang:s},title:l,titleTemplate:h?"%s | "+h:null,meta:[{name:"description",content:d},{property:"og:title",content:l},{property:"og:description",content:d},{property:"og:image",content:p},{property:"og:type",content:"website"},{name:"twitter:card",content:"summary_large_image"},{name:"twitter:image:src",content:p},{name:"twitter:creator",content:(null===(r=f.siteMetadata)||void 0===r?void 0:r.author)||""},{name:"twitter:title",content:l},{name:"twitter:description",content:d}].concat(u)})}s.defaultProps={lang:"en",meta:[],description:""},e.a=s},yXPU:function(t,e){function r(t,e,r,n,i,a,o){try{var s=t[a](o),u=s.value}catch(l){return void r(l)}s.done?e(u):Promise.resolve(u).then(n,i)}t.exports=function(t){return function(){var e=this,n=arguments;return new Promise((function(i,a){var o=t.apply(e,n);function s(t){r(o,i,a,s,u,"next",t)}function u(t){r(o,i,a,s,u,"throw",t)}s(void 0)}))}}},"z/o8":function(t,e,r){"use strict";r.r(e),r.d(e,"gsap",(function(){return Un})),r.d(e,"default",(function(){return Un})),r.d(e,"CSSPlugin",(function(){return Hn})),r.d(e,"TweenMax",(function(){return Yn})),r.d(e,"TweenLite",(function(){return Xe})),r.d(e,"TimelineMax",(function(){return Ve})),r.d(e,"TimelineLite",(function(){return Ve})),r.d(e,"Power0",(function(){return xr})),r.d(e,"Power1",(function(){return Tr})),r.d(e,"Power2",(function(){return kr})),r.d(e,"Power3",(function(){return Sr})),r.d(e,"Power4",(function(){return Or})),r.d(e,"Linear",(function(){return Cr})),r.d(e,"Quad",(function(){return Er})),r.d(e,"Cubic",(function(){return Ar})),r.d(e,"Quart",(function(){return Mr})),r.d(e,"Quint",(function(){return Pr})),r.d(e,"Strong",(function(){return Ir})),r.d(e,"Elastic",(function(){return jr})),r.d(e,"Back",(function(){return Rr})),r.d(e,"SteppedEase",(function(){return Nr})),r.d(e,"Bounce",(function(){return zr})),r.d(e,"Sine",(function(){return Lr})),r.d(e,"Expo",(function(){return Dr})),r.d(e,"Circ",(function(){return Fr}));r("E9XD");function n(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function i(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var a,o,s,u,l,c,f,d,h,p,m,g,v,y,b,_,w,x,T,k,S,O,C,E,A,M,P,I={autoSleep:120,force3D:"auto",nullTargetWarn:1,units:{lineHeight:""}},j={duration:.5,overwrite:!1,delay:0},R=1e8,N=2*Math.PI,z=N/4,L=0,D=Math.sqrt,F=Math.cos,V=Math.sin,q=function(t){return"string"==typeof t},B=function(t){return"function"==typeof t},H=function(t){return"number"==typeof t},U=function(t){return void 0===t},Y=function(t){return"object"==typeof t},G=function(t){return!1!==t},$=function(){return"undefined"!=typeof window},W=function(t){return B(t)||q(t)},X="function"==typeof ArrayBuffer&&ArrayBuffer.isView||function(){},Q=Array.isArray,Z=/(?:-?\.?\d|\.)+/gi,J=/[-+=.]*\d+[.e\-+]*\d*[e\-\+]*\d*/g,K=/[-+=.]*\d+[.e-]*\d*[a-z%]*/g,tt=/[-+=.]*\d+(?:\.|e-|e)*\d*/gi,et=/[+-]=-?[\.\d]+/,rt=/[#\-+.]*\b[a-z\d-=+%.]+/gi,nt={},it={},at=function(t){return(it=Pt(t,nt))&&hr},ot=function(t,e){return console.warn("Invalid property",t,"set to",e,"Missing plugin? gsap.registerPlugin()")},st=function(t,e){return!e&&console.warn(t)},ut=function(t,e){return t&&(nt[t]=e)&&it&&(it[t]=e)||nt},lt=function(){return 0},ct={},ft=[],dt={},ht={},pt={},mt=30,gt=[],vt="",yt=function(t){var e,r,n=t[0];if(Y(n)||B(n)||(t=[t]),!(e=(n._gsap||{}).harness)){for(r=gt.length;r--&&!gt[r].targetTest(n););e=gt[r]}for(r=t.length;r--;)t[r]&&(t[r]._gsap||(t[r]._gsap=new De(t[r],e)))||t.splice(r,1);return t},bt=function(t){return t._gsap||yt(ie(t))[0]._gsap},_t=function(t,e,r){return(r=t[e])&&B(r)?t[e]():U(r)&&t.getAttribute&&t.getAttribute(e)||r},wt=function(t,e){return(t=t.split(",")).forEach(e)||t},xt=function(t){return Math.round(1e5*t)/1e5||0},Tt=function(t,e){for(var r=e.length,n=0;t.indexOf(e[n])<0&&++n<r;);return n<r},kt=function(t,e,r){var n,i=H(t[1]),a=(i?2:1)+(e<2?0:1),o=t[a];if(i&&(o.duration=t[1]),o.parent=r,e){for(n=o;r&&!("immediateRender"in n);)n=r.vars.defaults||{},r=G(r.vars.inherit)&&r.parent;o.immediateRender=G(n.immediateRender),e<2?o.runBackwards=1:o.startAt=t[a-1]}return o},St=function(){var t,e,r=ft.length,n=ft.slice(0);for(dt={},ft.length=0,t=0;t<r;t++)(e=n[t])&&e._lazy&&(e.render(e._lazy[0],e._lazy[1],!0)._lazy=0)},Ot=function(t,e,r,n){ft.length&&St(),t.render(e,r,n),ft.length&&St()},Ct=function(t){var e=parseFloat(t);return(e||0===e)&&(t+"").match(rt).length<2?e:q(t)?t.trim():t},Et=function(t){return t},At=function(t,e){for(var r in e)r in t||(t[r]=e[r]);return t},Mt=function(t,e){for(var r in e)r in t||"duration"===r||"ease"===r||(t[r]=e[r])},Pt=function(t,e){for(var r in e)t[r]=e[r];return t},It=function t(e,r){for(var n in r)e[n]=Y(r[n])?t(e[n]||(e[n]={}),r[n]):r[n];return e},jt=function(t,e){var r,n={};for(r in t)r in e||(n[r]=t[r]);return n},Rt=function(t){var e=t.parent||a,r=t.keyframes?Mt:At;if(G(t.inherit))for(;e;)r(t,e.vars.defaults),e=e.parent||e._dp;return t},Nt=function(t,e,r,n){void 0===r&&(r="_first"),void 0===n&&(n="_last");var i=e._prev,a=e._next;i?i._next=a:t[r]===e&&(t[r]=a),a?a._prev=i:t[n]===e&&(t[n]=i),e._next=e._prev=e.parent=null},zt=function(t,e){t.parent&&(!e||t.parent.autoRemoveChildren)&&t.parent.remove(t),t._act=0},Lt=function(t,e){if(t&&(!e||e._end>t._dur||e._start<0))for(var r=t;r;)r._dirty=1,r=r.parent;return t},Dt=function(t){for(var e=t.parent;e&&e.parent;)e._dirty=1,e.totalDuration(),e=e.parent;return t},Ft=function(t){return t._repeat?Vt(t._tTime,t=t.duration()+t._rDelay)*t:0},Vt=function(t,e){return(t/=e)&&~~t===t?~~t-1:~~t},qt=function(t,e){return(t-e._start)*e._ts+(e._ts>=0?0:e._dirty?e.totalDuration():e._tDur)},Bt=function(t){return t._end=xt(t._start+(t._tDur/Math.abs(t._ts||t._rts||1e-8)||0))},Ht=function(t,e){var r=t._dp;return r&&r.smoothChildTiming&&t._ts&&(t._start=xt(t._dp._time-(t._ts>0?e/t._ts:((t._dirty?t.totalDuration():t._tDur)-e)/-t._ts)),Bt(t),r._dirty||Lt(r,t)),t},Ut=function(t,e){var r;if((e._time||e._initted&&!e._dur)&&(r=qt(t.rawTime(),e),(!e._dur||Kt(0,e.totalDuration(),r)-e._tTime>1e-8)&&e.render(r,!0)),Lt(t,e)._dp&&t._initted&&t._time>=t._dur&&t._ts){if(t._dur<t.duration())for(r=t;r._dp;)r.rawTime()>=0&&r.totalTime(r._tTime),r=r._dp;t._zTime=-1e-8}},Yt=function(t,e,r,n){return e.parent&&zt(e),e._start=xt(r+e._delay),e._end=xt(e._start+(e.totalDuration()/Math.abs(e.timeScale())||0)),function(t,e,r,n,i){void 0===r&&(r="_first"),void 0===n&&(n="_last");var a,o=t[n];if(i)for(a=e[i];o&&o[i]>a;)o=o._prev;o?(e._next=o._next,o._next=e):(e._next=t[r],t[r]=e),e._next?e._next._prev=e:t[n]=e,e._prev=o,e.parent=e._dp=t}(t,e,"_first","_last",t._sort?"_start":0),t._recent=e,n||Ut(t,e),t},Gt=function(t,e){return(nt.ScrollTrigger||ot("scrollTrigger",e))&&nt.ScrollTrigger.create(e,t)},$t=function(t,e,r,n){return Ye(t,e),t._initted?!r&&t._pt&&(t._dur&&!1!==t.vars.lazy||!t._dur&&t.vars.lazy)&&c!==Se.frame?(ft.push(t),t._lazy=[e,n],1):void 0:1},Wt=function(t,e,r,n){var i=t._repeat,a=xt(e)||0,o=t._tTime/t._tDur;return o&&!n&&(t._time*=a/t._dur),t._dur=a,t._tDur=i?i<0?1e10:xt(a*(i+1)+t._rDelay*i):a,o&&!n?Ht(t,t._tTime=t._tDur*o):t.parent&&Bt(t),r||Lt(t.parent,t),t},Xt=function(t){return t instanceof Ve?Lt(t):Wt(t,t._dur)},Qt={_start:0,endTime:lt},Zt=function t(e,r){var n,i,a=e.labels,o=e._recent||Qt,s=e.duration()>=R?o.endTime(!1):e._dur;return q(r)&&(isNaN(r)||r in a)?"<"===(n=r.charAt(0))||">"===n?("<"===n?o._start:o.endTime(o._repeat>=0))+(parseFloat(r.substr(1))||0):(n=r.indexOf("="))<0?(r in a||(a[r]=s),a[r]):(i=+(r.charAt(n-1)+r.substr(n+1)),n>1?t(e,r.substr(0,n-1))+i:s+i):null==r?s:+r},Jt=function(t,e){return t||0===t?e(t):e},Kt=function(t,e,r){return r<t?t:r>e?e:r},te=function(t){return(t=(t+"").substr((parseFloat(t)+"").length))&&isNaN(t)?t:""},ee=[].slice,re=function(t,e){return t&&Y(t)&&"length"in t&&(!e&&!t.length||t.length-1 in t&&Y(t[0]))&&!t.nodeType&&t!==o},ne=function(t,e,r){return void 0===r&&(r=[]),t.forEach((function(t){var n;return q(t)&&!e||re(t,1)?(n=r).push.apply(n,ie(t)):r.push(t)}))||r},ie=function(t,e){return!q(t)||e||!s&&Oe()?Q(t)?ne(t,e):re(t)?ee.call(t,0):t?[t]:[]:ee.call(u.querySelectorAll(t),0)},ae=function(t){return t.sort((function(){return.5-Math.random()}))},oe=function(t){if(B(t))return t;var e=Y(t)?t:{each:t},r=je(e.ease),n=e.from||0,i=parseFloat(e.base)||0,a={},o=n>0&&n<1,s=isNaN(n)||o,u=e.axis,l=n,c=n;return q(n)?l=c={center:.5,edges:.5,end:1}[n]||0:!o&&s&&(l=n[0],c=n[1]),function(t,o,f){var d,h,p,m,g,v,y,b,_,w=(f||e).length,x=a[w];if(!x){if(!(_="auto"===e.grid?0:(e.grid||[1,R])[1])){for(y=-R;y<(y=f[_++].getBoundingClientRect().left)&&_<w;);_--}for(x=a[w]=[],d=s?Math.min(_,w)*l-.5:n%_,h=s?w*c/_-.5:n/_|0,y=0,b=R,v=0;v<w;v++)p=v%_-d,m=h-(v/_|0),x[v]=g=u?Math.abs("y"===u?m:p):D(p*p+m*m),g>y&&(y=g),g<b&&(b=g);"random"===n&&ae(x),x.max=y-b,x.min=b,x.v=w=(parseFloat(e.amount)||parseFloat(e.each)*(_>w?w-1:u?"y"===u?w/_:_:Math.max(_,w/_))||0)*("edges"===n?-1:1),x.b=w<0?i-w:i,x.u=te(e.amount||e.each)||0,r=r&&w<0?Pe(r):r}return w=(x[t]-x.min)/x.max||0,xt(x.b+(r?r(w):w)*x.v)+x.u}},se=function(t){var e=t<1?Math.pow(10,(t+"").length-2):1;return function(r){return Math.floor(Math.round(parseFloat(r)/t)*t*e)/e+(H(r)?0:te(r))}},ue=function(t,e){var r,n,i=Q(t);return!i&&Y(t)&&(r=i=t.radius||R,t.values?(t=ie(t.values),(n=!H(t[0]))&&(r*=r)):t=se(t.increment)),Jt(e,i?B(t)?function(e){return n=t(e),Math.abs(n-e)<=r?n:e}:function(e){for(var i,a,o=parseFloat(n?e.x:e),s=parseFloat(n?e.y:0),u=R,l=0,c=t.length;c--;)(i=n?(i=t[c].x-o)*i+(a=t[c].y-s)*a:Math.abs(t[c]-o))<u&&(u=i,l=c);return l=!r||u<=r?t[l]:e,n||l===e||H(e)?l:l+te(e)}:se(t))},le=function(t,e,r,n){return Jt(Q(t)?!e:!0===r?!!(r=0):!n,(function(){return Q(t)?t[~~(Math.random()*t.length)]:(r=r||1e-5)&&(n=r<1?Math.pow(10,(r+"").length-2):1)&&Math.floor(Math.round((t+Math.random()*(e-t))/r)*r*n)/n}))},ce=function(t,e,r){return Jt(r,(function(r){return t[~~e(r)]}))},fe=function(t){for(var e,r,n,i,a=0,o="";~(e=t.indexOf("random(",a));)n=t.indexOf(")",e),i="["===t.charAt(e+7),r=t.substr(e+7,n-e-7).match(i?rt:Z),o+=t.substr(a,e-a)+le(i?r:+r[0],i?0:+r[1],+r[2]||1e-5),a=n+1;return o+t.substr(a,t.length-a)},de=function(t,e,r,n,i){var a=e-t,o=n-r;return Jt(i,(function(e){return r+((e-t)/a*o||0)}))},he=function(t,e,r){var n,i,a,o=t.labels,s=R;for(n in o)(i=o[n]-e)<0==!!r&&i&&s>(i=Math.abs(i))&&(a=n,s=i);return a},pe=function(t,e,r){var n,i,a=t.vars,o=a[e];if(o)return n=a[e+"Params"],i=a.callbackScope||t,r&&ft.length&&St(),n?o.apply(i,n):o.call(i)},me=function(t){return zt(t),t.progress()<1&&pe(t,"onInterrupt"),t},ge=function(t){var e=(t=!t.name&&t.default||t).name,r=B(t),n=e&&!r&&t.init?function(){this._props=[]}:t,i={init:lt,render:ir,add:He,kill:or,modifier:ar,rawVars:0},a={targetTest:0,get:0,getSetter:tr,aliases:{},register:0};if(Oe(),t!==n){if(ht[e])return;At(n,At(jt(t,i),a)),Pt(n.prototype,Pt(i,jt(t,a))),ht[n.prop=e]=n,t.targetTest&&(gt.push(n),ct[e]=1),e=("css"===e?"CSS":e.charAt(0).toUpperCase()+e.substr(1))+"Plugin"}ut(e,n),t.register&&t.register(hr,n,lr)},ve={aqua:[0,255,255],lime:[0,255,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,255],navy:[0,0,128],white:[255,255,255],olive:[128,128,0],yellow:[255,255,0],orange:[255,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[255,0,0],pink:[255,192,203],cyan:[0,255,255],transparent:[255,255,255,0]},ye=function(t,e,r){return 255*(6*(t=t<0?t+1:t>1?t-1:t)<1?e+(r-e)*t*6:t<.5?r:3*t<2?e+(r-e)*(2/3-t)*6:e)+.5|0},be=function(t,e,r){var n,i,a,o,s,u,l,c,f,d,h=t?H(t)?[t>>16,t>>8&255,255&t]:0:ve.black;if(!h){if(","===t.substr(-1)&&(t=t.substr(0,t.length-1)),ve[t])h=ve[t];else if("#"===t.charAt(0))4===t.length&&(n=t.charAt(1),i=t.charAt(2),a=t.charAt(3),t="#"+n+n+i+i+a+a),h=[(t=parseInt(t.substr(1),16))>>16,t>>8&255,255&t];else if("hsl"===t.substr(0,3))if(h=d=t.match(Z),e){if(~t.indexOf("="))return h=t.match(J),r&&h.length<4&&(h[3]=1),h}else o=+h[0]%360/360,s=+h[1]/100,n=2*(u=+h[2]/100)-(i=u<=.5?u*(s+1):u+s-u*s),h.length>3&&(h[3]*=1),h[0]=ye(o+1/3,n,i),h[1]=ye(o,n,i),h[2]=ye(o-1/3,n,i);else h=t.match(Z)||ve.transparent;h=h.map(Number)}return e&&!d&&(n=h[0]/255,i=h[1]/255,a=h[2]/255,u=((l=Math.max(n,i,a))+(c=Math.min(n,i,a)))/2,l===c?o=s=0:(f=l-c,s=u>.5?f/(2-l-c):f/(l+c),o=l===n?(i-a)/f+(i<a?6:0):l===i?(a-n)/f+2:(n-i)/f+4,o*=60),h[0]=~~(o+.5),h[1]=~~(100*s+.5),h[2]=~~(100*u+.5)),r&&h.length<4&&(h[3]=1),h},_e=function(t){var e=[],r=[],n=-1;return t.split(xe).forEach((function(t){var i=t.match(K)||[];e.push.apply(e,i),r.push(n+=i.length+1)})),e.c=r,e},we=function(t,e,r){var n,i,a,o,s="",u=(t+s).match(xe),l=e?"hsla(":"rgba(",c=0;if(!u)return t;if(u=u.map((function(t){return(t=be(t,e,1))&&l+(e?t[0]+","+t[1]+"%,"+t[2]+"%,"+t[3]:t.join(","))+")"})),r&&(a=_e(t),(n=r.c).join(s)!==a.c.join(s)))for(o=(i=t.replace(xe,"1").split(K)).length-1;c<o;c++)s+=i[c]+(~n.indexOf(c)?u.shift()||l+"0,0,0,0)":(a.length?a:u.length?u:r).shift());if(!i)for(o=(i=t.split(xe)).length-1;c<o;c++)s+=i[c]+u[c];return s+i[o]},xe=function(){var t,e="(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3}){1,2}\\b";for(t in ve)e+="|"+t+"\\b";return new RegExp(e+")","gi")}(),Te=/hsl[a]?\(/,ke=function(t){var e,r=t.join(" ");if(xe.lastIndex=0,xe.test(r))return e=Te.test(r),t[1]=we(t[1],e),t[0]=we(t[0],e,_e(t[1])),!0},Se=(b=Date.now,_=500,w=33,x=b(),T=x,S=k=1e3/240,C=function t(e){var r,n,i,a,o=b()-T,s=!0===e;if(o>_&&(x+=o-w),((r=(i=(T+=o)-x)-S)>0||s)&&(a=++g.frame,v=i-1e3*g.time,g.time=i/=1e3,S+=r+(r>=k?4:k-r),n=1),s||(h=p(t)),n)for(y=0;y<O.length;y++)O[y](i,v,a,e)},g={time:0,frame:0,tick:function(){C(!0)},deltaRatio:function(t){return v/(1e3/(t||60))},wake:function(){l&&(!s&&$()&&(o=s=window,u=o.document||{},nt.gsap=hr,(o.gsapVersions||(o.gsapVersions=[])).push(hr.version),at(it||o.GreenSockGlobals||!o.gsap&&o||{}),m=o.requestAnimationFrame),h&&g.sleep(),p=m||function(t){return setTimeout(t,S-1e3*g.time+1|0)},d=1,C(2))},sleep:function(){(m?o.cancelAnimationFrame:clearTimeout)(h),d=0,p=lt},lagSmoothing:function(t,e){_=t||1/1e-8,w=Math.min(e,_,0)},fps:function(t){k=1e3/(t||240),S=1e3*g.time+k},add:function(t){O.indexOf(t)<0&&O.push(t),Oe()},remove:function(t){var e;~(e=O.indexOf(t))&&O.splice(e,1)&&y>=e&&y--},_listeners:O=[]}),Oe=function(){return!d&&Se.wake()},Ce={},Ee=/^[\d.\-M][\d.\-,\s]/,Ae=/["']/g,Me=function(t){for(var e,r,n,i={},a=t.substr(1,t.length-3).split(":"),o=a[0],s=1,u=a.length;s<u;s++)r=a[s],e=s!==u-1?r.lastIndexOf(","):r.length,n=r.substr(0,e),i[o]=isNaN(n)?n.replace(Ae,"").trim():+n,o=r.substr(e+1).trim();return i},Pe=function(t){return function(e){return 1-t(1-e)}},Ie=function t(e,r){for(var n,i=e._first;i;)i instanceof Ve?t(i,r):!i.vars.yoyoEase||i._yoyo&&i._repeat||i._yoyo===r||(i.timeline?t(i.timeline,r):(n=i._ease,i._ease=i._yEase,i._yEase=n,i._yoyo=r)),i=i._next},je=function(t,e){return t&&(B(t)?t:Ce[t]||function(t){var e,r,n,i,a=(t+"").split("("),o=Ce[a[0]];return o&&a.length>1&&o.config?o.config.apply(null,~t.indexOf("{")?[Me(a[1])]:(e=t,r=e.indexOf("(")+1,n=e.indexOf(")"),i=e.indexOf("(",r),e.substring(r,~i&&i<n?e.indexOf(")",n+1):n)).split(",").map(Ct)):Ce._CE&&Ee.test(t)?Ce._CE("",t):o}(t))||e},Re=function(t,e,r,n){void 0===r&&(r=function(t){return 1-e(1-t)}),void 0===n&&(n=function(t){return t<.5?e(2*t)/2:1-e(2*(1-t))/2});var i,a={easeIn:e,easeOut:r,easeInOut:n};return wt(t,(function(t){for(var e in Ce[t]=nt[t]=a,Ce[i=t.toLowerCase()]=r,a)Ce[i+("easeIn"===e?".in":"easeOut"===e?".out":".inOut")]=Ce[t+"."+e]=a[e]})),a},Ne=function(t){return function(e){return e<.5?(1-t(1-2*e))/2:.5+t(2*(e-.5))/2}},ze=function t(e,r,n){var i=r>=1?r:1,a=(n||(e?.3:.45))/(r<1?r:1),o=a/N*(Math.asin(1/i)||0),s=function(t){return 1===t?1:i*Math.pow(2,-10*t)*V((t-o)*a)+1},u="out"===e?s:"in"===e?function(t){return 1-s(1-t)}:Ne(s);return a=N/a,u.config=function(r,n){return t(e,r,n)},u},Le=function t(e,r){void 0===r&&(r=1.70158);var n=function(t){return t?--t*t*((r+1)*t+r)+1:0},i="out"===e?n:"in"===e?function(t){return 1-n(1-t)}:Ne(n);return i.config=function(r){return t(e,r)},i};wt("Linear,Quad,Cubic,Quart,Quint,Strong",(function(t,e){var r=e<5?e+1:e;Re(t+",Power"+(r-1),e?function(t){return Math.pow(t,r)}:function(t){return t},(function(t){return 1-Math.pow(1-t,r)}),(function(t){return t<.5?Math.pow(2*t,r)/2:1-Math.pow(2*(1-t),r)/2}))})),Ce.Linear.easeNone=Ce.none=Ce.Linear.easeIn,Re("Elastic",ze("in"),ze("out"),ze()),E=7.5625,M=1/(A=2.75),Re("Bounce",(function(t){return 1-P(1-t)}),P=function(t){return t<M?E*t*t:t<.7272727272727273?E*Math.pow(t-1.5/A,2)+.75:t<.9090909090909092?E*(t-=2.25/A)*t+.9375:E*Math.pow(t-2.625/A,2)+.984375}),Re("Expo",(function(t){return t?Math.pow(2,10*(t-1)):0})),Re("Circ",(function(t){return-(D(1-t*t)-1)})),Re("Sine",(function(t){return 1===t?1:1-F(t*z)})),Re("Back",Le("in"),Le("out"),Le()),Ce.SteppedEase=Ce.steps=nt.SteppedEase={config:function(t,e){void 0===t&&(t=1);var r=1/t,n=t+(e?0:1),i=e?1:0;return function(t){return((n*Kt(0,1-1e-8,t)|0)+i)*r}}},j.ease=Ce["quad.out"],wt("onComplete,onUpdate,onStart,onRepeat,onReverseComplete,onInterrupt",(function(t){return vt+=t+","+t+"Params,"}));var De=function(t,e){this.id=L++,t._gsap=this,this.target=t,this.harness=e,this.get=e?e.get:_t,this.set=e?e.getSetter:tr},Fe=function(){function t(t,e){var r=t.parent||a;this.vars=t,this._delay=+t.delay||0,(this._repeat=t.repeat||0)&&(this._rDelay=t.repeatDelay||0,this._yoyo=!!t.yoyo||!!t.yoyoEase),this._ts=1,Wt(this,+t.duration,1,1),this.data=t.data,d||Se.wake(),r&&Yt(r,this,e||0===e?e:r._time,1),t.reversed&&this.reverse(),t.paused&&this.paused(!0)}var e=t.prototype;return e.delay=function(t){return t||0===t?(this.parent&&this.parent.smoothChildTiming&&this.startTime(this._start+t-this._delay),this._delay=t,this):this._delay},e.duration=function(t){return arguments.length?this.totalDuration(this._repeat>0?t+(t+this._rDelay)*this._repeat:t):this.totalDuration()&&this._dur},e.totalDuration=function(t){return arguments.length?(this._dirty=0,Wt(this,this._repeat<0?t:(t-this._repeat*this._rDelay)/(this._repeat+1))):this._tDur},e.totalTime=function(t,e){if(Oe(),!arguments.length)return this._tTime;var r=this._dp;if(r&&r.smoothChildTiming&&this._ts){for(Ht(this,t);r.parent;)r.parent._time!==r._start+(r._ts>=0?r._tTime/r._ts:(r.totalDuration()-r._tTime)/-r._ts)&&r.totalTime(r._tTime,!0),r=r.parent;!this.parent&&this._dp.autoRemoveChildren&&(this._ts>0&&t<this._tDur||this._ts<0&&t>0||!this._tDur&&!t)&&Yt(this._dp,this,this._start-this._delay)}return(this._tTime!==t||!this._dur&&!e||this._initted&&1e-8===Math.abs(this._zTime)||!t&&!this._initted&&(this.add||this._ptLookup))&&(this._ts||(this._pTime=t),Ot(this,t,e)),this},e.time=function(t,e){return arguments.length?this.totalTime(Math.min(this.totalDuration(),t+Ft(this))%this._dur||(t?this._dur:0),e):this._time},e.totalProgress=function(t,e){return arguments.length?this.totalTime(this.totalDuration()*t,e):this.totalDuration()?Math.min(1,this._tTime/this._tDur):this.ratio},e.progress=function(t,e){return arguments.length?this.totalTime(this.duration()*(!this._yoyo||1&this.iteration()?t:1-t)+Ft(this),e):this.duration()?Math.min(1,this._time/this._dur):this.ratio},e.iteration=function(t,e){var r=this.duration()+this._rDelay;return arguments.length?this.totalTime(this._time+(t-1)*r,e):this._repeat?Vt(this._tTime,r)+1:1},e.timeScale=function(t){if(!arguments.length)return-1e-8===this._rts?0:this._rts;if(this._rts===t)return this;var e=this.parent&&this._ts?qt(this.parent._time,this):this._tTime;return this._rts=+t||0,this._ts=this._ps||-1e-8===t?0:this._rts,Dt(this.totalTime(Kt(-this._delay,this._tDur,e),!0))},e.paused=function(t){return arguments.length?(this._ps!==t&&(this._ps=t,t?(this._pTime=this._tTime||Math.max(-this._delay,this.rawTime()),this._ts=this._act=0):(Oe(),this._ts=this._rts,this.totalTime(this.parent&&!this.parent.smoothChildTiming?this.rawTime():this._tTime||this._pTime,1===this.progress()&&(this._tTime-=1e-8)&&1e-8!==Math.abs(this._zTime)))),this):this._ps},e.startTime=function(t){if(arguments.length){this._start=t;var e=this.parent||this._dp;return e&&(e._sort||!this.parent)&&Yt(e,this,t-this._delay),this}return this._start},e.endTime=function(t){return this._start+(G(t)?this.totalDuration():this.duration())/Math.abs(this._ts)},e.rawTime=function(t){var e=this.parent||this._dp;return e?t&&(!this._ts||this._repeat&&this._time&&this.totalProgress()<1)?this._tTime%(this._dur+this._rDelay):this._ts?qt(e.rawTime(t),this):this._tTime:this._tTime},e.globalTime=function(t){for(var e=this,r=arguments.length?t:e.rawTime();e;)r=e._start+r/(e._ts||1),e=e._dp;return r},e.repeat=function(t){return arguments.length?(this._repeat=t,Xt(this)):this._repeat},e.repeatDelay=function(t){return arguments.length?(this._rDelay=t,Xt(this)):this._rDelay},e.yoyo=function(t){return arguments.length?(this._yoyo=t,this):this._yoyo},e.seek=function(t,e){return this.totalTime(Zt(this,t),G(e))},e.restart=function(t,e){return this.play().totalTime(t?-this._delay:0,G(e))},e.play=function(t,e){return null!=t&&this.seek(t,e),this.reversed(!1).paused(!1)},e.reverse=function(t,e){return null!=t&&this.seek(t||this.totalDuration(),e),this.reversed(!0).paused(!1)},e.pause=function(t,e){return null!=t&&this.seek(t,e),this.paused(!0)},e.resume=function(){return this.paused(!1)},e.reversed=function(t){return arguments.length?(!!t!==this.reversed()&&this.timeScale(-this._rts||(t?-1e-8:0)),this):this._rts<0},e.invalidate=function(){return this._initted=0,this._zTime=-1e-8,this},e.isActive=function(){var t,e=this.parent||this._dp,r=this._start;return!(e&&!(this._ts&&this._initted&&e.isActive()&&(t=e.rawTime(!0))>=r&&t<this.endTime(!0)-1e-8))},e.eventCallback=function(t,e,r){var n=this.vars;return arguments.length>1?(e?(n[t]=e,r&&(n[t+"Params"]=r),"onUpdate"===t&&(this._onUpdate=e)):delete n[t],this):n[t]},e.then=function(t){var e=this;return new Promise((function(r){var n=B(t)?t:Et,i=function(){var t=e.then;e.then=null,B(n)&&(n=n(e))&&(n.then||n===e)&&(e.then=t),r(n),e.then=t};e._initted&&1===e.totalProgress()&&e._ts>=0||!e._tTime&&e._ts<0?i():e._prom=i}))},e.kill=function(){me(this)},t}();At(Fe.prototype,{_time:0,_start:0,_end:0,_tTime:0,_tDur:0,_dirty:0,_repeat:0,_yoyo:!1,parent:null,_initted:!1,_rDelay:0,_ts:1,_dp:0,ratio:0,_zTime:-1e-8,_prom:0,_ps:!1,_rts:1});var Ve=function(t){function e(e,r){var i;return void 0===e&&(e={}),(i=t.call(this,e,r)||this).labels={},i.smoothChildTiming=!!e.smoothChildTiming,i.autoRemoveChildren=!!e.autoRemoveChildren,i._sort=G(e.sortChildren),i.parent&&Ut(i.parent,n(i)),e.scrollTrigger&&Gt(n(i),e.scrollTrigger),i}i(e,t);var r=e.prototype;return r.to=function(t,e,r){return new Xe(t,kt(arguments,0,this),Zt(this,H(e)?arguments[3]:r)),this},r.from=function(t,e,r){return new Xe(t,kt(arguments,1,this),Zt(this,H(e)?arguments[3]:r)),this},r.fromTo=function(t,e,r,n){return new Xe(t,kt(arguments,2,this),Zt(this,H(e)?arguments[4]:n)),this},r.set=function(t,e,r){return e.duration=0,e.parent=this,Rt(e).repeatDelay||(e.repeat=0),e.immediateRender=!!e.immediateRender,new Xe(t,e,Zt(this,r),1),this},r.call=function(t,e,r){return Yt(this,Xe.delayedCall(0,t,e),Zt(this,r))},r.staggerTo=function(t,e,r,n,i,a,o){return r.duration=e,r.stagger=r.stagger||n,r.onComplete=a,r.onCompleteParams=o,r.parent=this,new Xe(t,r,Zt(this,i)),this},r.staggerFrom=function(t,e,r,n,i,a,o){return r.runBackwards=1,Rt(r).immediateRender=G(r.immediateRender),this.staggerTo(t,e,r,n,i,a,o)},r.staggerFromTo=function(t,e,r,n,i,a,o,s){return n.startAt=r,Rt(n).immediateRender=G(n.immediateRender),this.staggerTo(t,e,n,i,a,o,s)},r.render=function(t,e,r){var n,i,o,s,u,l,c,f,d,h,p,m,g=this._time,v=this._dirty?this.totalDuration():this._tDur,y=this._dur,b=this!==a&&t>v-1e-8&&t>=0?v:t<1e-8?0:t,_=this._zTime<0!=t<0&&(this._initted||!y);if(b!==this._tTime||r||_){if(g!==this._time&&y&&(b+=this._time-g,t+=this._time-g),n=b,d=this._start,l=!(f=this._ts),_&&(y||(g=this._zTime),(t||!e)&&(this._zTime=t)),this._repeat&&(p=this._yoyo,u=y+this._rDelay,n=xt(b%u),b===v?(s=this._repeat,n=y):((s=~~(b/u))&&s===b/u&&(n=y,s--),n>y&&(n=y)),h=Vt(this._tTime,u),!g&&this._tTime&&h!==s&&(h=s),p&&1&s&&(n=y-n,m=1),s!==h&&!this._lock)){var w=p&&1&h,x=w===(p&&1&s);if(s<h&&(w=!w),g=w?0:y,this._lock=1,this.render(g||(m?0:xt(s*u)),e,!y)._lock=0,!e&&this.parent&&pe(this,"onRepeat"),this.vars.repeatRefresh&&!m&&(this.invalidate()._lock=1),g!==this._time||l!==!this._ts)return this;if(y=this._dur,v=this._tDur,x&&(this._lock=2,g=w?y:-1e-4,this.render(g,!0),this.vars.repeatRefresh&&!m&&this.invalidate()),this._lock=0,!this._ts&&!l)return this;Ie(this,m)}if(this._hasPause&&!this._forcing&&this._lock<2&&(c=function(t,e,r){var n;if(r>e)for(n=t._first;n&&n._start<=r;){if(!n._dur&&"isPause"===n.data&&n._start>e)return n;n=n._next}else for(n=t._last;n&&n._start>=r;){if(!n._dur&&"isPause"===n.data&&n._start<e)return n;n=n._prev}}(this,xt(g),xt(n)))&&(b-=n-(n=c._start)),this._tTime=b,this._time=n,this._act=!f,this._initted||(this._onUpdate=this.vars.onUpdate,this._initted=1,this._zTime=t),!g&&n&&!e&&pe(this,"onStart"),n>=g&&t>=0)for(i=this._first;i;){if(o=i._next,(i._act||n>=i._start)&&i._ts&&c!==i){if(i.parent!==this)return this.render(t,e,r);if(i.render(i._ts>0?(n-i._start)*i._ts:(i._dirty?i.totalDuration():i._tDur)+(n-i._start)*i._ts,e,r),n!==this._time||!this._ts&&!l){c=0,o&&(b+=this._zTime=-1e-8);break}}i=o}else{i=this._last;for(var T=t<0?t:n;i;){if(o=i._prev,(i._act||T<=i._end)&&i._ts&&c!==i){if(i.parent!==this)return this.render(t,e,r);if(i.render(i._ts>0?(T-i._start)*i._ts:(i._dirty?i.totalDuration():i._tDur)+(T-i._start)*i._ts,e,r),n!==this._time||!this._ts&&!l){c=0,o&&(b+=this._zTime=T?-1e-8:1e-8);break}}i=o}}if(c&&!e&&(this.pause(),c.render(n>=g?0:-1e-8)._zTime=n>=g?1:-1,this._ts))return this._start=d,Bt(this),this.render(t,e,r);this._onUpdate&&!e&&pe(this,"onUpdate",!0),(b===v&&v>=this.totalDuration()||!b&&g)&&(d!==this._start&&Math.abs(f)===Math.abs(this._ts)||this._lock||((t||!y)&&(b===v&&this._ts>0||!b&&this._ts<0)&&zt(this,1),e||t<0&&!g||!b&&!g||(pe(this,b===v?"onComplete":"onReverseComplete",!0),this._prom&&!(b<v&&this.timeScale()>0)&&this._prom())))}return this},r.add=function(t,e){var r=this;if(H(e)||(e=Zt(this,e)),!(t instanceof Fe)){if(Q(t))return t.forEach((function(t){return r.add(t,e)})),this;if(q(t))return this.addLabel(t,e);if(!B(t))return this;t=Xe.delayedCall(0,t)}return this!==t?Yt(this,t,e):this},r.getChildren=function(t,e,r,n){void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===r&&(r=!0),void 0===n&&(n=-R);for(var i=[],a=this._first;a;)a._start>=n&&(a instanceof Xe?e&&i.push(a):(r&&i.push(a),t&&i.push.apply(i,a.getChildren(!0,e,r)))),a=a._next;return i},r.getById=function(t){for(var e=this.getChildren(1,1,1),r=e.length;r--;)if(e[r].vars.id===t)return e[r]},r.remove=function(t){return q(t)?this.removeLabel(t):B(t)?this.killTweensOf(t):(Nt(this,t),t===this._recent&&(this._recent=this._last),Lt(this))},r.totalTime=function(e,r){return arguments.length?(this._forcing=1,!this._dp&&this._ts&&(this._start=xt(Se.time-(this._ts>0?e/this._ts:(this.totalDuration()-e)/-this._ts))),t.prototype.totalTime.call(this,e,r),this._forcing=0,this):this._tTime},r.addLabel=function(t,e){return this.labels[t]=Zt(this,e),this},r.removeLabel=function(t){return delete this.labels[t],this},r.addPause=function(t,e,r){var n=Xe.delayedCall(0,e||lt,r);return n.data="isPause",this._hasPause=1,Yt(this,n,Zt(this,t))},r.removePause=function(t){var e=this._first;for(t=Zt(this,t);e;)e._start===t&&"isPause"===e.data&&zt(e),e=e._next},r.killTweensOf=function(t,e,r){for(var n=this.getTweensOf(t,r),i=n.length;i--;)qe!==n[i]&&n[i].kill(t,e);return this},r.getTweensOf=function(t,e){for(var r,n=[],i=ie(t),a=this._first,o=H(e);a;)a instanceof Xe?Tt(a._targets,i)&&(o?(!qe||a._initted&&a._ts)&&a.globalTime(0)<=e&&a.globalTime(a.totalDuration())>e:!e||a.isActive())&&n.push(a):(r=a.getTweensOf(i,e)).length&&n.push.apply(n,r),a=a._next;return n},r.tweenTo=function(t,e){e=e||{};var r=this,n=Zt(r,t),i=e,a=i.startAt,o=i.onStart,s=i.onStartParams,u=Xe.to(r,At(e,{ease:"none",lazy:!1,time:n,overwrite:"auto",duration:e.duration||Math.abs((n-(a&&"time"in a?a.time:r._time))/r.timeScale())||1e-8,onStart:function(){r.pause();var t=e.duration||Math.abs((n-r._time)/r.timeScale());u._dur!==t&&Wt(u,t,0,1).render(u._time,!0,!0),o&&o.apply(u,s||[])}}));return u},r.tweenFromTo=function(t,e,r){return this.tweenTo(e,At({startAt:{time:Zt(this,t)}},r))},r.recent=function(){return this._recent},r.nextLabel=function(t){return void 0===t&&(t=this._time),he(this,Zt(this,t))},r.previousLabel=function(t){return void 0===t&&(t=this._time),he(this,Zt(this,t),1)},r.currentLabel=function(t){return arguments.length?this.seek(t,!0):this.previousLabel(this._time+1e-8)},r.shiftChildren=function(t,e,r){void 0===r&&(r=0);for(var n,i=this._first,a=this.labels;i;)i._start>=r&&(i._start+=t,i._end+=t),i=i._next;if(e)for(n in a)a[n]>=r&&(a[n]+=t);return Lt(this)},r.invalidate=function(){var e=this._first;for(this._lock=0;e;)e.invalidate(),e=e._next;return t.prototype.invalidate.call(this)},r.clear=function(t){void 0===t&&(t=!0);for(var e,r=this._first;r;)e=r._next,this.remove(r),r=e;return this._time=this._tTime=this._pTime=0,t&&(this.labels={}),Lt(this)},r.totalDuration=function(t){var e,r,n,i=0,o=this,s=o._last,u=R;if(arguments.length)return o.timeScale((o._repeat<0?o.duration():o.totalDuration())/(o.reversed()?-t:t));if(o._dirty){for(n=o.parent;s;)e=s._prev,s._dirty&&s.totalDuration(),(r=s._start)>u&&o._sort&&s._ts&&!o._lock?(o._lock=1,Yt(o,s,r-s._delay,1)._lock=0):u=r,r<0&&s._ts&&(i-=r,(!n&&!o._dp||n&&n.smoothChildTiming)&&(o._start+=r/o._ts,o._time-=r,o._tTime-=r),o.shiftChildren(-r,!1,-Infinity),u=0),s._end>i&&s._ts&&(i=s._end),s=e;Wt(o,o===a&&o._time>i?o._time:i,1,1),o._dirty=0}return o._tDur},e.updateRoot=function(t){if(a._ts&&(Ot(a,qt(t,a)),c=Se.frame),Se.frame>=mt){mt+=I.autoSleep||120;var e=a._first;if((!e||!e._ts)&&I.autoSleep&&Se._listeners.length<2){for(;e&&!e._ts;)e=e._next;e||Se.sleep()}}},e}(Fe);At(Ve.prototype,{_lock:0,_hasPause:0,_forcing:0});var qe,Be=function(t,e,r,n,i,a,o){var s,u,l,c,f,d,h,p,m=new lr(this._pt,t,e,0,1,nr,null,i),g=0,v=0;for(m.b=r,m.e=n,r+="",(h=~(n+="").indexOf("random("))&&(n=fe(n)),a&&(a(p=[r,n],t,e),r=p[0],n=p[1]),u=r.match(tt)||[];s=tt.exec(n);)c=s[0],f=n.substring(g,s.index),l?l=(l+1)%5:"rgba("===f.substr(-5)&&(l=1),c!==u[v++]&&(d=parseFloat(u[v-1])||0,m._pt={_next:m._pt,p:f||1===v?f:",",s:d,c:"="===c.charAt(1)?parseFloat(c.substr(2))*("-"===c.charAt(0)?-1:1):parseFloat(c)-d,m:l&&l<4?Math.round:0},g=tt.lastIndex);return m.c=g<n.length?n.substring(g,n.length):"",m.fp=o,(et.test(n)||h)&&(m.e=0),this._pt=m,m},He=function(t,e,r,n,i,a,o,s,u){B(n)&&(n=n(i||0,t,a));var l,c=t[e],f="get"!==r?r:B(c)?u?t[e.indexOf("set")||!B(t["get"+e.substr(3)])?e:"get"+e.substr(3)](u):t[e]():c,d=B(c)?u?Je:Ze:Qe;if(q(n)&&(~n.indexOf("random(")&&(n=fe(n)),"="===n.charAt(1)&&(n=parseFloat(f)+parseFloat(n.substr(2))*("-"===n.charAt(0)?-1:1)+(te(f)||0))),f!==n)return isNaN(f*n)?(!c&&!(e in t)&&ot(e,n),Be.call(this,t,e,f,n,d,s||I.stringFilter,u)):(l=new lr(this._pt,t,e,+f||0,n-(f||0),"boolean"==typeof c?rr:er,0,d),u&&(l.fp=u),o&&l.modifier(o,this,t),this._pt=l)},Ue=function(t,e,r,n,i,a){var o,s,u,l;if(ht[t]&&!1!==(o=new ht[t]).init(i,o.rawVars?e[t]:function(t,e,r,n,i){if(B(t)&&(t=Ge(t,i,e,r,n)),!Y(t)||t.style&&t.nodeType||Q(t)||X(t))return q(t)?Ge(t,i,e,r,n):t;var a,o={};for(a in t)o[a]=Ge(t[a],i,e,r,n);return o}(e[t],n,i,a,r),r,n,a)&&(r._pt=s=new lr(r._pt,i,t,0,1,o.render,o,0,o.priority),r!==f))for(u=r._ptLookup[r._targets.indexOf(i)],l=o._props.length;l--;)u[o._props[l]]=s;return o},Ye=function t(e,r){var n,i,o,s,u,l,c,f,d,h,p,m,g,v=e.vars,y=v.ease,b=v.startAt,_=v.immediateRender,w=v.lazy,x=v.onUpdate,T=v.onUpdateParams,k=v.callbackScope,S=v.runBackwards,O=v.yoyoEase,C=v.keyframes,E=v.autoRevert,A=e._dur,M=e._startAt,P=e._targets,I=e.parent,R=I&&"nested"===I.data?I.parent._targets:P,N="auto"===e._overwrite,z=e.timeline;if(z&&(!C||!y)&&(y="none"),e._ease=je(y,j.ease),e._yEase=O?Pe(je(!0===O?y:O,j.ease)):0,O&&e._yoyo&&!e._repeat&&(O=e._yEase,e._yEase=e._ease,e._ease=O),!z){if(m=(f=P[0]?bt(P[0]).harness:0)&&v[f.prop],n=jt(v,ct),M&&M.render(-1,!0).kill(),b){if(zt(e._startAt=Xe.set(P,At({data:"isStart",overwrite:!1,parent:I,immediateRender:!0,lazy:G(w),startAt:null,delay:0,onUpdate:x,onUpdateParams:T,callbackScope:k,stagger:0},b))),_)if(r>0)E||(e._startAt=0);else if(A&&!(r<0&&M))return void(r&&(e._zTime=r))}else if(S&&A)if(M)!E&&(e._startAt=0);else if(r&&(_=!1),o=At({overwrite:!1,data:"isFromStart",lazy:_&&G(w),immediateRender:_,stagger:0,parent:I},n),m&&(o[f.prop]=m),zt(e._startAt=Xe.set(P,o)),_){if(!r)return}else t(e._startAt,1e-8);for(e._pt=0,w=A&&G(w)||w&&!A,i=0;i<P.length;i++){if(c=(u=P[i])._gsap||yt(P)[i]._gsap,e._ptLookup[i]=h={},dt[c.id]&&ft.length&&St(),p=R===P?i:R.indexOf(u),f&&!1!==(d=new f).init(u,m||n,e,p,R)&&(e._pt=s=new lr(e._pt,u,d.name,0,1,d.render,d,0,d.priority),d._props.forEach((function(t){h[t]=s})),d.priority&&(l=1)),!f||m)for(o in n)ht[o]&&(d=Ue(o,n,e,p,u,R))?d.priority&&(l=1):h[o]=s=He.call(e,u,o,"get",n[o],p,R,0,v.stringFilter);e._op&&e._op[i]&&e.kill(u,e._op[i]),N&&e._pt&&(qe=e,a.killTweensOf(u,h,e.globalTime(0)),g=!e.parent,qe=0),e._pt&&w&&(dt[c.id]=1)}l&&ur(e),e._onInit&&e._onInit(e)}e._from=!z&&!!v.runBackwards,e._onUpdate=x,e._initted=(!e._op||e._pt)&&!g},Ge=function(t,e,r,n,i){return B(t)?t.call(e,r,n,i):q(t)&&~t.indexOf("random(")?fe(t):t},$e=vt+"repeat,repeatDelay,yoyo,repeatRefresh,yoyoEase",We=($e+",id,stagger,delay,duration,paused,scrollTrigger").split(","),Xe=function(t){function e(e,r,i,o){var s;"number"==typeof r&&(i.duration=r,r=i,i=null);var u,l,c,f,d,h,p,m,g=(s=t.call(this,o?r:Rt(r),i)||this).vars,v=g.duration,y=g.delay,b=g.immediateRender,_=g.stagger,w=g.overwrite,x=g.keyframes,T=g.defaults,k=g.scrollTrigger,S=g.yoyoEase,O=s.parent,C=(Q(e)||X(e)?H(e[0]):"length"in r)?[e]:ie(e);if(s._targets=C.length?yt(C):st("GSAP target "+e+" not found. https://greensock.com",!I.nullTargetWarn)||[],s._ptLookup=[],s._overwrite=w,x||_||W(v)||W(y)){if(r=s.vars,(u=s.timeline=new Ve({data:"nested",defaults:T||{}})).kill(),u.parent=n(s),x)At(u.vars.defaults,{ease:"none"}),x.forEach((function(t){return u.to(C,t,">")}));else{if(f=C.length,p=_?oe(_):lt,Y(_))for(d in _)~$e.indexOf(d)&&(m||(m={}),m[d]=_[d]);for(l=0;l<f;l++){for(d in c={},r)We.indexOf(d)<0&&(c[d]=r[d]);c.stagger=0,S&&(c.yoyoEase=S),m&&Pt(c,m),h=C[l],c.duration=+Ge(v,n(s),l,h,C),c.delay=(+Ge(y,n(s),l,h,C)||0)-s._delay,!_&&1===f&&c.delay&&(s._delay=y=c.delay,s._start+=y,c.delay=0),u.to(h,c,p(l,h,C))}u.duration()?v=y=0:s.timeline=0}v||s.duration(v=u.duration())}else s.timeline=0;return!0===w&&(qe=n(s),a.killTweensOf(C),qe=0),O&&Ut(O,n(s)),(b||!v&&!x&&s._start===xt(O._time)&&G(b)&&function t(e){return!e||e._ts&&t(e.parent)}(n(s))&&"nested"!==O.data)&&(s._tTime=-1e-8,s.render(Math.max(0,-y))),k&&Gt(n(s),k),s}i(e,t);var r=e.prototype;return r.render=function(t,e,r){var n,i,a,o,s,u,l,c,f,d=this._time,h=this._tDur,p=this._dur,m=t>h-1e-8&&t>=0?h:t<1e-8?0:t;if(p){if(m!==this._tTime||!t||r||this._startAt&&this._zTime<0!=t<0){if(n=m,c=this.timeline,this._repeat){if(o=p+this._rDelay,n=xt(m%o),m===h?(a=this._repeat,n=p):((a=~~(m/o))&&a===m/o&&(n=p,a--),n>p&&(n=p)),(u=this._yoyo&&1&a)&&(f=this._yEase,n=p-n),s=Vt(this._tTime,o),n===d&&!r&&this._initted)return this;a!==s&&(c&&this._yEase&&Ie(c,u),!this.vars.repeatRefresh||u||this._lock||(this._lock=r=1,this.render(xt(o*a),!0).invalidate()._lock=0))}if(!this._initted){if($t(this,t<0?t:n,r,e))return this._tTime=0,this;if(p!==this._dur)return this.render(t,e,r)}for(this._tTime=m,this._time=n,!this._act&&this._ts&&(this._act=1,this._lazy=0),this.ratio=l=(f||this._ease)(n/p),this._from&&(this.ratio=l=1-l),n&&!d&&!e&&pe(this,"onStart"),i=this._pt;i;)i.r(l,i.d),i=i._next;c&&c.render(t<0?t:!n&&u?-1e-8:c._dur*l,e,r)||this._startAt&&(this._zTime=t),this._onUpdate&&!e&&(t<0&&this._startAt&&this._startAt.render(t,!0,r),pe(this,"onUpdate")),this._repeat&&a!==s&&this.vars.onRepeat&&!e&&this.parent&&pe(this,"onRepeat"),m!==this._tDur&&m||this._tTime!==m||(t<0&&this._startAt&&!this._onUpdate&&this._startAt.render(t,!0,!0),(t||!p)&&(m===this._tDur&&this._ts>0||!m&&this._ts<0)&&zt(this,1),e||t<0&&!d||!m&&!d||(pe(this,m===h?"onComplete":"onReverseComplete",!0),this._prom&&!(m<h&&this.timeScale()>0)&&this._prom()))}}else!function(t,e,r,n){var i,a,o=t.ratio,s=e<0||!e&&o&&!t._start&&t._zTime>1e-8&&!t._dp._lock||(t._ts<0||t._dp._ts<0)&&"isFromStart"!==t.data&&"isStart"!==t.data?0:1,u=t._rDelay,l=0;if(u&&t._repeat&&(l=Kt(0,t._tDur,e),Vt(l,u)!==(a=Vt(t._tTime,u))&&(o=1-s,t.vars.repeatRefresh&&t._initted&&t.invalidate())),s!==o||n||1e-8===t._zTime||!e&&t._zTime){if(!t._initted&&$t(t,e,n,r))return;for(a=t._zTime,t._zTime=e||(r?1e-8:0),r||(r=e&&!a),t.ratio=s,t._from&&(s=1-s),t._time=0,t._tTime=l,r||pe(t,"onStart"),i=t._pt;i;)i.r(s,i.d),i=i._next;t._startAt&&e<0&&t._startAt.render(e,!0,!0),t._onUpdate&&!r&&pe(t,"onUpdate"),l&&t._repeat&&!r&&t.parent&&pe(t,"onRepeat"),(e>=t._tDur||e<0)&&t.ratio===s&&(s&&zt(t,1),r||(pe(t,s?"onComplete":"onReverseComplete",!0),t._prom&&t._prom()))}else t._zTime||(t._zTime=e)}(this,t,e,r);return this},r.targets=function(){return this._targets},r.invalidate=function(){return this._pt=this._op=this._startAt=this._onUpdate=this._act=this._lazy=0,this._ptLookup=[],this.timeline&&this.timeline.invalidate(),t.prototype.invalidate.call(this)},r.kill=function(t,e){if(void 0===e&&(e="all"),!(t||e&&"all"!==e)&&(this._lazy=0,this.parent))return me(this);if(this.timeline){var r=this.timeline.totalDuration();return this.timeline.killTweensOf(t,e,qe&&!0!==qe.vars.overwrite)._first||me(this),this.parent&&r!==this.timeline.totalDuration()&&Wt(this,this._dur*this.timeline._tDur/r,0,1),this}var n,i,a,o,s,u,l,c=this._targets,f=t?ie(t):c,d=this._ptLookup,h=this._pt;if((!e||"all"===e)&&function(t,e){for(var r=t.length,n=r===e.length;n&&r--&&t[r]===e[r];);return r<0}(c,f))return"all"===e&&(this._pt=0),me(this);for(n=this._op=this._op||[],"all"!==e&&(q(e)&&(s={},wt(e,(function(t){return s[t]=1})),e=s),e=function(t,e){var r,n,i,a,o=t[0]?bt(t[0]).harness:0,s=o&&o.aliases;if(!s)return e;for(n in r=Pt({},e),s)if(n in r)for(i=(a=s[n].split(",")).length;i--;)r[a[i]]=r[n];return r}(c,e)),l=c.length;l--;)if(~f.indexOf(c[l]))for(s in i=d[l],"all"===e?(n[l]=e,o=i,a={}):(a=n[l]=n[l]||{},o=e),o)(u=i&&i[s])&&("kill"in u.d&&!0!==u.d.kill(s)||Nt(this,u,"_pt"),delete i[s]),"all"!==a&&(a[s]=1);return this._initted&&!this._pt&&h&&me(this),this},e.to=function(t,r){return new e(t,r,arguments[2])},e.from=function(t,r){return new e(t,kt(arguments,1))},e.delayedCall=function(t,r,n,i){return new e(r,0,{immediateRender:!1,lazy:!1,overwrite:!1,delay:t,onComplete:r,onReverseComplete:r,onCompleteParams:n,onReverseCompleteParams:n,callbackScope:i})},e.fromTo=function(t,r,n){return new e(t,kt(arguments,2))},e.set=function(t,r){return r.duration=0,r.repeatDelay||(r.repeat=0),new e(t,r)},e.killTweensOf=function(t,e,r){return a.killTweensOf(t,e,r)},e}(Fe);At(Xe.prototype,{_targets:[],_lazy:0,_startAt:0,_op:0,_onInit:0}),wt("staggerTo,staggerFrom,staggerFromTo",(function(t){Xe[t]=function(){var e=new Ve,r=ee.call(arguments,0);return r.splice("staggerFromTo"===t?5:4,0,0),e[t].apply(e,r)}}));var Qe=function(t,e,r){return t[e]=r},Ze=function(t,e,r){return t[e](r)},Je=function(t,e,r,n){return t[e](n.fp,r)},Ke=function(t,e,r){return t.setAttribute(e,r)},tr=function(t,e){return B(t[e])?Ze:U(t[e])&&t.setAttribute?Ke:Qe},er=function(t,e){return e.set(e.t,e.p,Math.round(1e4*(e.s+e.c*t))/1e4,e)},rr=function(t,e){return e.set(e.t,e.p,!!(e.s+e.c*t),e)},nr=function(t,e){var r=e._pt,n="";if(!t&&e.b)n=e.b;else if(1===t&&e.e)n=e.e;else{for(;r;)n=r.p+(r.m?r.m(r.s+r.c*t):Math.round(1e4*(r.s+r.c*t))/1e4)+n,r=r._next;n+=e.c}e.set(e.t,e.p,n,e)},ir=function(t,e){for(var r=e._pt;r;)r.r(t,r.d),r=r._next},ar=function(t,e,r,n){for(var i,a=this._pt;a;)i=a._next,a.p===n&&a.modifier(t,e,r),a=i},or=function(t){for(var e,r,n=this._pt;n;)r=n._next,n.p===t&&!n.op||n.op===t?Nt(this,n,"_pt"):n.dep||(e=1),n=r;return!e},sr=function(t,e,r,n){n.mSet(t,e,n.m.call(n.tween,r,n.mt),n)},ur=function(t){for(var e,r,n,i,a=t._pt;a;){for(e=a._next,r=n;r&&r.pr>a.pr;)r=r._next;(a._prev=r?r._prev:i)?a._prev._next=a:n=a,(a._next=r)?r._prev=a:i=a,a=e}t._pt=n},lr=function(){function t(t,e,r,n,i,a,o,s,u){this.t=e,this.s=n,this.c=i,this.p=r,this.r=a||er,this.d=o||this,this.set=s||Qe,this.pr=u||0,this._next=t,t&&(t._prev=this)}return t.prototype.modifier=function(t,e,r){this.mSet=this.mSet||this.set,this.set=sr,this.m=t,this.mt=r,this.tween=e},t}();wt(vt+"parent,duration,ease,delay,overwrite,runBackwards,startAt,yoyo,immediateRender,repeat,repeatDelay,data,paused,reversed,lazy,callbackScope,stringFilter,id,yoyoEase,stagger,inherit,repeatRefresh,keyframes,autoRevert,scrollTrigger",(function(t){return ct[t]=1})),nt.TweenMax=nt.TweenLite=Xe,nt.TimelineLite=nt.TimelineMax=Ve,a=new Ve({sortChildren:!1,defaults:j,autoRemoveChildren:!0,id:"root",smoothChildTiming:!0}),I.stringFilter=ke;var cr={registerPlugin:function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];e.forEach((function(t){return ge(t)}))},timeline:function(t){return new Ve(t)},getTweensOf:function(t,e){return a.getTweensOf(t,e)},getProperty:function(t,e,r,n){q(t)&&(t=ie(t)[0]);var i=bt(t||{}).get,a=r?Et:Ct;return"native"===r&&(r=""),t?e?a((ht[e]&&ht[e].get||i)(t,e,r,n)):function(e,r,n){return a((ht[e]&&ht[e].get||i)(t,e,r,n))}:t},quickSetter:function(t,e,r){if((t=ie(t)).length>1){var n=t.map((function(t){return hr.quickSetter(t,e,r)})),i=n.length;return function(t){for(var e=i;e--;)n[e](t)}}t=t[0]||{};var a=ht[e],o=bt(t),s=o.harness&&(o.harness.aliases||{})[e]||e,u=a?function(e){var n=new a;f._pt=0,n.init(t,r?e+r:e,f,0,[t]),n.render(1,n),f._pt&&ir(1,f)}:o.set(t,s);return a?u:function(e){return u(t,s,r?e+r:e,o,1)}},isTweening:function(t){return a.getTweensOf(t,!0).length>0},defaults:function(t){return t&&t.ease&&(t.ease=je(t.ease,j.ease)),It(j,t||{})},config:function(t){return It(I,t||{})},registerEffect:function(t){var e=t.name,r=t.effect,n=t.plugins,i=t.defaults,a=t.extendTimeline;(n||"").split(",").forEach((function(t){return t&&!ht[t]&&!nt[t]&&st(e+" effect requires "+t+" plugin.")})),pt[e]=function(t,e,n){return r(ie(t),At(e||{},i),n)},a&&(Ve.prototype[e]=function(t,r,n){return this.add(pt[e](t,Y(r)?r:(n=r)&&{},this),n)})},registerEase:function(t,e){Ce[t]=je(e)},parseEase:function(t,e){return arguments.length?je(t,e):Ce},getById:function(t){return a.getById(t)},exportRoot:function(t,e){void 0===t&&(t={});var r,n,i=new Ve(t);for(i.smoothChildTiming=G(t.smoothChildTiming),a.remove(i),i._dp=0,i._time=i._tTime=a._time,r=a._first;r;)n=r._next,!e&&!r._dur&&r instanceof Xe&&r.vars.onComplete===r._targets[0]||Yt(i,r,r._start-r._delay),r=n;return Yt(a,i,0),i},utils:{wrap:function t(e,r,n){var i=r-e;return Q(e)?ce(e,t(0,e.length),r):Jt(n,(function(t){return(i+(t-e)%i)%i+e}))},wrapYoyo:function t(e,r,n){var i=r-e,a=2*i;return Q(e)?ce(e,t(0,e.length-1),r):Jt(n,(function(t){return e+((t=(a+(t-e)%a)%a||0)>i?a-t:t)}))},distribute:oe,random:le,snap:ue,normalize:function(t,e,r){return de(t,e,0,1,r)},getUnit:te,clamp:function(t,e,r){return Jt(r,(function(r){return Kt(t,e,r)}))},splitColor:be,toArray:ie,mapRange:de,pipe:function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return function(t){return e.reduce((function(t,e){return e(t)}),t)}},unitize:function(t,e){return function(r){return t(parseFloat(r))+(e||te(r))}},interpolate:function t(e,r,n,i){var a=isNaN(e+r)?0:function(t){return(1-t)*e+t*r};if(!a){var o,s,u,l,c,f=q(e),d={};if(!0===n&&(i=1)&&(n=null),f)e={p:e},r={p:r};else if(Q(e)&&!Q(r)){for(u=[],l=e.length,c=l-2,s=1;s<l;s++)u.push(t(e[s-1],e[s]));l--,a=function(t){t*=l;var e=Math.min(c,~~t);return u[e](t-e)},n=r}else i||(e=Pt(Q(e)?[]:{},e));if(!u){for(o in r)He.call(d,e,o,"get",r[o]);a=function(t){return ir(t,d)||(f?e.p:e)}}}return Jt(n,a)},shuffle:ae},install:at,effects:pt,ticker:Se,updateRoot:Ve.updateRoot,plugins:ht,globalTimeline:a,core:{PropTween:lr,globals:ut,Tween:Xe,Timeline:Ve,Animation:Fe,getCache:bt,_removeLinkedListItem:Nt}};wt("to,from,fromTo,delayedCall,set,killTweensOf",(function(t){return cr[t]=Xe[t]})),Se.add(Ve.updateRoot),f=cr.to({},{duration:0});var fr=function(t,e){for(var r=t._pt;r&&r.p!==e&&r.op!==e&&r.fp!==e;)r=r._next;return r},dr=function(t,e){return{name:t,rawVars:1,init:function(t,r,n){n._onInit=function(t){var n,i;if(q(r)&&(n={},wt(r,(function(t){return n[t]=1})),r=n),e){for(i in n={},r)n[i]=e(r[i]);r=n}!function(t,e){var r,n,i,a=t._targets;for(r in e)for(n=a.length;n--;)(i=t._ptLookup[n][r])&&(i=i.d)&&(i._pt&&(i=fr(i,r)),i&&i.modifier&&i.modifier(e[r],t,a[n],r))}(t,r)}}}},hr=cr.registerPlugin({name:"attr",init:function(t,e,r,n,i){var a,o;for(a in e)(o=this.add(t,"setAttribute",(t.getAttribute(a)||0)+"",e[a],n,i,0,0,a))&&(o.op=a),this._props.push(a)}},{name:"endArray",init:function(t,e){for(var r=e.length;r--;)this.add(t,r,t[r]||0,e[r])}},dr("roundProps",se),dr("modifiers"),dr("snap",ue))||cr;Xe.version=Ve.version=hr.version="3.5.1",l=1,$()&&Oe();var pr,mr,gr,vr,yr,br,_r,wr,xr=Ce.Power0,Tr=Ce.Power1,kr=Ce.Power2,Sr=Ce.Power3,Or=Ce.Power4,Cr=Ce.Linear,Er=Ce.Quad,Ar=Ce.Cubic,Mr=Ce.Quart,Pr=Ce.Quint,Ir=Ce.Strong,jr=Ce.Elastic,Rr=Ce.Back,Nr=Ce.SteppedEase,zr=Ce.Bounce,Lr=Ce.Sine,Dr=Ce.Expo,Fr=Ce.Circ,Vr={},qr=180/Math.PI,Br=Math.PI/180,Hr=Math.atan2,Ur=/([A-Z])/g,Yr=/(?:left|right|width|margin|padding|x)/i,Gr=/[\s,\(]\S/,$r={autoAlpha:"opacity,visibility",scale:"scaleX,scaleY",alpha:"opacity"},Wr=function(t,e){return e.set(e.t,e.p,Math.round(1e4*(e.s+e.c*t))/1e4+e.u,e)},Xr=function(t,e){return e.set(e.t,e.p,1===t?e.e:Math.round(1e4*(e.s+e.c*t))/1e4+e.u,e)},Qr=function(t,e){return e.set(e.t,e.p,t?Math.round(1e4*(e.s+e.c*t))/1e4+e.u:e.b,e)},Zr=function(t,e){var r=e.s+e.c*t;e.set(e.t,e.p,~~(r+(r<0?-.5:.5))+e.u,e)},Jr=function(t,e){return e.set(e.t,e.p,t?e.e:e.b,e)},Kr=function(t,e){return e.set(e.t,e.p,1!==t?e.b:e.e,e)},tn=function(t,e,r){return t.style[e]=r},en=function(t,e,r){return t.style.setProperty(e,r)},rn=function(t,e,r){return t._gsap[e]=r},nn=function(t,e,r){return t._gsap.scaleX=t._gsap.scaleY=r},an=function(t,e,r,n,i){var a=t._gsap;a.scaleX=a.scaleY=r,a.renderTransform(i,a)},on=function(t,e,r,n,i){var a=t._gsap;a[e]=r,a.renderTransform(i,a)},sn="transform",un=sn+"Origin",ln=function(t,e){var r=mr.createElementNS?mr.createElementNS((e||"http://www.w3.org/1999/xhtml").replace(/^https/,"http"),t):mr.createElement(t);return r.style?r:mr.createElement(t)},cn=function t(e,r,n){var i=getComputedStyle(e);return i[r]||i.getPropertyValue(r.replace(Ur,"-$1").toLowerCase())||i.getPropertyValue(r)||!n&&t(e,dn(r)||r,1)||""},fn="O,Moz,ms,Ms,Webkit".split(","),dn=function(t,e,r){var n=(e||yr).style,i=5;if(t in n&&!r)return t;for(t=t.charAt(0).toUpperCase()+t.substr(1);i--&&!(fn[i]+t in n););return i<0?null:(3===i?"ms":i>=0?fn[i]:"")+t},hn=function(){"undefined"!=typeof window&&window.document&&(pr=window,mr=pr.document,gr=mr.documentElement,yr=ln("div")||{style:{}},br=ln("div"),sn=dn(sn),un=sn+"Origin",yr.style.cssText="border-width:0;line-height:0;position:absolute;padding:0",wr=!!dn("perspective"),vr=1)},pn=function t(e){var r,n=ln("svg",this.ownerSVGElement&&this.ownerSVGElement.getAttribute("xmlns")||"http://www.w3.org/2000/svg"),i=this.parentNode,a=this.nextSibling,o=this.style.cssText;if(gr.appendChild(n),n.appendChild(this),this.style.display="block",e)try{r=this.getBBox(),this._gsapBBox=this.getBBox,this.getBBox=t}catch(s){}else this._gsapBBox&&(r=this._gsapBBox());return i&&(a?i.insertBefore(this,a):i.appendChild(this)),gr.removeChild(n),this.style.cssText=o,r},mn=function(t,e){for(var r=e.length;r--;)if(t.hasAttribute(e[r]))return t.getAttribute(e[r])},gn=function(t){var e;try{e=t.getBBox()}catch(r){e=pn.call(t,!0)}return e&&(e.width||e.height)||t.getBBox===pn||(e=pn.call(t,!0)),!e||e.width||e.x||e.y?e:{x:+mn(t,["x","cx","x1"])||0,y:+mn(t,["y","cy","y1"])||0,width:0,height:0}},vn=function(t){return!(!t.getCTM||t.parentNode&&!t.ownerSVGElement||!gn(t))},yn=function(t,e){if(e){var r=t.style;e in Vr&&e!==un&&(e=sn),r.removeProperty?("ms"!==e.substr(0,2)&&"webkit"!==e.substr(0,6)||(e="-"+e),r.removeProperty(e.replace(Ur,"-$1").toLowerCase())):r.removeAttribute(e)}},bn=function(t,e,r,n,i,a){var o=new lr(t._pt,e,r,0,1,a?Kr:Jr);return t._pt=o,o.b=n,o.e=i,t._props.push(r),o},_n={deg:1,rad:1,turn:1},wn=function t(e,r,n,i){var a,o,s,u,l=parseFloat(n)||0,c=(n+"").trim().substr((l+"").length)||"px",f=yr.style,d=Yr.test(r),h="svg"===e.tagName.toLowerCase(),p=(h?"client":"offset")+(d?"Width":"Height"),m="px"===i,g="%"===i;return i===c||!l||_n[i]||_n[c]?l:("px"!==c&&!m&&(l=t(e,r,n,"px")),u=e.getCTM&&vn(e),g&&(Vr[r]||~r.indexOf("adius"))?xt(l/(u?e.getBBox()[d?"width":"height"]:e[p])*100):(f[d?"width":"height"]=100+(m?c:i),o=~r.indexOf("adius")||"em"===i&&e.appendChild&&!h?e:e.parentNode,u&&(o=(e.ownerSVGElement||{}).parentNode),o&&o!==mr&&o.appendChild||(o=mr.body),(s=o._gsap)&&g&&s.width&&d&&s.time===Se.time?xt(l/s.width*100):((g||"%"===c)&&(f.position=cn(e,"position")),o===e&&(f.position="static"),o.appendChild(yr),a=yr[p],o.removeChild(yr),f.position="absolute",d&&g&&((s=bt(o)).time=Se.time,s.width=o[p]),xt(m?a*l/100:a&&l?100/a*l:0))))},xn=function(t,e,r,n){var i;return vr||hn(),e in $r&&"transform"!==e&&~(e=$r[e]).indexOf(",")&&(e=e.split(",")[0]),Vr[e]&&"transform"!==e?(i=jn(t,n),i="transformOrigin"!==e?i[e]:Rn(cn(t,un))+" "+i.zOrigin+"px"):(!(i=t.style[e])||"auto"===i||n||~(i+"").indexOf("calc("))&&(i=On[e]&&On[e](t,e,r)||cn(t,e)||_t(t,e)||("opacity"===e?1:0)),r&&!~(i+"").indexOf(" ")?wn(t,e,i,r)+r:i},Tn=function(t,e,r,n){if(!r||"none"===r){var i=dn(e,t,1),a=i&&cn(t,i,1);a&&a!==r?(e=i,r=a):"borderColor"===e&&(r=cn(t,"borderTopColor"))}var o,s,u,l,c,f,d,h,p,m,g,v,y=new lr(this._pt,t.style,e,0,1,nr),b=0,_=0;if(y.b=r,y.e=n,r+="","auto"===(n+="")&&(t.style[e]=n,n=cn(t,e)||n,t.style[e]=r),ke(o=[r,n]),n=o[1],u=(r=o[0]).match(K)||[],(n.match(K)||[]).length){for(;s=K.exec(n);)d=s[0],p=n.substring(b,s.index),c?c=(c+1)%5:"rgba("!==p.substr(-5)&&"hsla("!==p.substr(-5)||(c=1),d!==(f=u[_++]||"")&&(l=parseFloat(f)||0,g=f.substr((l+"").length),(v="="===d.charAt(1)?+(d.charAt(0)+"1"):0)&&(d=d.substr(2)),h=parseFloat(d),m=d.substr((h+"").length),b=K.lastIndex-m.length,m||(m=m||I.units[e]||g,b===n.length&&(n+=m,y.e+=m)),g!==m&&(l=wn(t,e,f,m)||0),y._pt={_next:y._pt,p:p||1===_?p:",",s:l,c:v?v*h:h-l,m:c&&c<4?Math.round:0});y.c=b<n.length?n.substring(b,n.length):""}else y.r="display"===e&&"none"===n?Kr:Jr;return et.test(n)&&(y.e=0),this._pt=y,y},kn={top:"0%",bottom:"100%",left:"0%",right:"100%",center:"50%"},Sn=function(t,e){if(e.tween&&e.tween._time===e.tween._dur){var r,n,i,a=e.t,o=a.style,s=e.u,u=a._gsap;if("all"===s||!0===s)o.cssText="",n=1;else for(i=(s=s.split(",")).length;--i>-1;)r=s[i],Vr[r]&&(n=1,r="transformOrigin"===r?un:sn),yn(a,r);n&&(yn(a,sn),u&&(u.svg&&a.removeAttribute("transform"),jn(a,1),u.uncache=1))}},On={clearProps:function(t,e,r,n,i){if("isFromStart"!==i.data){var a=t._pt=new lr(t._pt,e,r,0,0,Sn);return a.u=n,a.pr=-10,a.tween=i,t._props.push(r),1}}},Cn=[1,0,0,1,0,0],En={},An=function(t){return"matrix(1, 0, 0, 1, 0, 0)"===t||"none"===t||!t},Mn=function(t){var e=cn(t,sn);return An(e)?Cn:e.substr(7).match(J).map(xt)},Pn=function(t,e){var r,n,i,a,o=t._gsap||bt(t),s=t.style,u=Mn(t);return o.svg&&t.getAttribute("transform")?"1,0,0,1,0,0"===(u=[(i=t.transform.baseVal.consolidate().matrix).a,i.b,i.c,i.d,i.e,i.f]).join(",")?Cn:u:(u!==Cn||t.offsetParent||t===gr||o.svg||(i=s.display,s.display="block",(r=t.parentNode)&&t.offsetParent||(a=1,n=t.nextSibling,gr.appendChild(t)),u=Mn(t),i?s.display=i:yn(t,"display"),a&&(n?r.insertBefore(t,n):r?r.appendChild(t):gr.removeChild(t))),e&&u.length>6?[u[0],u[1],u[4],u[5],u[12],u[13]]:u)},In=function(t,e,r,n,i,a){var o,s,u,l=t._gsap,c=i||Pn(t,!0),f=l.xOrigin||0,d=l.yOrigin||0,h=l.xOffset||0,p=l.yOffset||0,m=c[0],g=c[1],v=c[2],y=c[3],b=c[4],_=c[5],w=e.split(" "),x=parseFloat(w[0])||0,T=parseFloat(w[1])||0;r?c!==Cn&&(s=m*y-g*v)&&(u=x*(-g/s)+T*(m/s)-(m*_-g*b)/s,x=x*(y/s)+T*(-v/s)+(v*_-y*b)/s,T=u):(x=(o=gn(t)).x+(~w[0].indexOf("%")?x/100*o.width:x),T=o.y+(~(w[1]||w[0]).indexOf("%")?T/100*o.height:T)),n||!1!==n&&l.smooth?(b=x-f,_=T-d,l.xOffset=h+(b*m+_*v)-b,l.yOffset=p+(b*g+_*y)-_):l.xOffset=l.yOffset=0,l.xOrigin=x,l.yOrigin=T,l.smooth=!!n,l.origin=e,l.originIsAbsolute=!!r,t.style[un]="0px 0px",a&&(bn(a,l,"xOrigin",f,x),bn(a,l,"yOrigin",d,T),bn(a,l,"xOffset",h,l.xOffset),bn(a,l,"yOffset",p,l.yOffset)),t.setAttribute("data-svg-origin",x+" "+T)},jn=function(t,e){var r=t._gsap||new De(t);if("x"in r&&!e&&!r.uncache)return r;var n,i,a,o,s,u,l,c,f,d,h,p,m,g,v,y,b,_,w,x,T,k,S,O,C,E,A,M,P,j,R,N,z=t.style,L=r.scaleX<0,D=cn(t,un)||"0";return n=i=a=u=l=c=f=d=h=0,o=s=1,r.svg=!(!t.getCTM||!vn(t)),g=Pn(t,r.svg),r.svg&&(O=!r.uncache&&t.getAttribute("data-svg-origin"),In(t,O||D,!!O||r.originIsAbsolute,!1!==r.smooth,g)),p=r.xOrigin||0,m=r.yOrigin||0,g!==Cn&&(_=g[0],w=g[1],x=g[2],T=g[3],n=k=g[4],i=S=g[5],6===g.length?(o=Math.sqrt(_*_+w*w),s=Math.sqrt(T*T+x*x),u=_||w?Hr(w,_)*qr:0,(f=x||T?Hr(x,T)*qr+u:0)&&(s*=Math.cos(f*Br)),r.svg&&(n-=p-(p*_+m*x),i-=m-(p*w+m*T))):(N=g[6],j=g[7],A=g[8],M=g[9],P=g[10],R=g[11],n=g[12],i=g[13],a=g[14],l=(v=Hr(N,P))*qr,v&&(O=k*(y=Math.cos(-v))+A*(b=Math.sin(-v)),C=S*y+M*b,E=N*y+P*b,A=k*-b+A*y,M=S*-b+M*y,P=N*-b+P*y,R=j*-b+R*y,k=O,S=C,N=E),c=(v=Hr(-x,P))*qr,v&&(y=Math.cos(-v),R=T*(b=Math.sin(-v))+R*y,_=O=_*y-A*b,w=C=w*y-M*b,x=E=x*y-P*b),u=(v=Hr(w,_))*qr,v&&(O=_*(y=Math.cos(v))+w*(b=Math.sin(v)),C=k*y+S*b,w=w*y-_*b,S=S*y-k*b,_=O,k=C),l&&Math.abs(l)+Math.abs(u)>359.9&&(l=u=0,c=180-c),o=xt(Math.sqrt(_*_+w*w+x*x)),s=xt(Math.sqrt(S*S+N*N)),v=Hr(k,S),f=Math.abs(v)>2e-4?v*qr:0,h=R?1/(R<0?-R:R):0),r.svg&&(O=t.getAttribute("transform"),r.forceCSS=t.setAttribute("transform","")||!An(cn(t,sn)),O&&t.setAttribute("transform",O))),Math.abs(f)>90&&Math.abs(f)<270&&(L?(o*=-1,f+=u<=0?180:-180,u+=u<=0?180:-180):(s*=-1,f+=f<=0?180:-180)),r.x=((r.xPercent=n&&Math.round(t.offsetWidth/2)===Math.round(-n)?-50:0)?0:n)+"px",r.y=((r.yPercent=i&&Math.round(t.offsetHeight/2)===Math.round(-i)?-50:0)?0:i)+"px",r.z=a+"px",r.scaleX=xt(o),r.scaleY=xt(s),r.rotation=xt(u)+"deg",r.rotationX=xt(l)+"deg",r.rotationY=xt(c)+"deg",r.skewX=f+"deg",r.skewY=d+"deg",r.transformPerspective=h+"px",(r.zOrigin=parseFloat(D.split(" ")[2])||0)&&(z[un]=Rn(D)),r.xOffset=r.yOffset=0,r.force3D=I.force3D,r.renderTransform=r.svg?Dn:wr?Ln:zn,r.uncache=0,r},Rn=function(t){return(t=t.split(" "))[0]+" "+t[1]},Nn=function(t,e,r){var n=te(e);return xt(parseFloat(e)+parseFloat(wn(t,"x",r+"px",n)))+n},zn=function(t,e){e.z="0px",e.rotationY=e.rotationX="0deg",e.force3D=0,Ln(t,e)},Ln=function(t,e){var r=e||this,n=r.xPercent,i=r.yPercent,a=r.x,o=r.y,s=r.z,u=r.rotation,l=r.rotationY,c=r.rotationX,f=r.skewX,d=r.skewY,h=r.scaleX,p=r.scaleY,m=r.transformPerspective,g=r.force3D,v=r.target,y=r.zOrigin,b="",_="auto"===g&&t&&1!==t||!0===g;if(y&&("0deg"!==c||"0deg"!==l)){var w,x=parseFloat(l)*Br,T=Math.sin(x),k=Math.cos(x);x=parseFloat(c)*Br,w=Math.cos(x),a=Nn(v,a,T*w*-y),o=Nn(v,o,-Math.sin(x)*-y),s=Nn(v,s,k*w*-y+y)}"0px"!==m&&(b+="perspective("+m+") "),(n||i)&&(b+="translate("+n+"%, "+i+"%) "),(_||"0px"!==a||"0px"!==o||"0px"!==s)&&(b+="0px"!==s||_?"translate3d("+a+", "+o+", "+s+") ":"translate("+a+", "+o+") "),"0deg"!==u&&(b+="rotate("+u+") "),"0deg"!==l&&(b+="rotateY("+l+") "),"0deg"!==c&&(b+="rotateX("+c+") "),"0deg"===f&&"0deg"===d||(b+="skew("+f+", "+d+") "),1===h&&1===p||(b+="scale("+h+", "+p+") "),v.style[sn]=b||"translate(0, 0)"},Dn=function(t,e){var r,n,i,a,o,s=e||this,u=s.xPercent,l=s.yPercent,c=s.x,f=s.y,d=s.rotation,h=s.skewX,p=s.skewY,m=s.scaleX,g=s.scaleY,v=s.target,y=s.xOrigin,b=s.yOrigin,_=s.xOffset,w=s.yOffset,x=s.forceCSS,T=parseFloat(c),k=parseFloat(f);d=parseFloat(d),h=parseFloat(h),(p=parseFloat(p))&&(h+=p=parseFloat(p),d+=p),d||h?(d*=Br,h*=Br,r=Math.cos(d)*m,n=Math.sin(d)*m,i=Math.sin(d-h)*-g,a=Math.cos(d-h)*g,h&&(p*=Br,o=Math.tan(h-p),i*=o=Math.sqrt(1+o*o),a*=o,p&&(o=Math.tan(p),r*=o=Math.sqrt(1+o*o),n*=o)),r=xt(r),n=xt(n),i=xt(i),a=xt(a)):(r=m,a=g,n=i=0),(T&&!~(c+"").indexOf("px")||k&&!~(f+"").indexOf("px"))&&(T=wn(v,"x",c,"px"),k=wn(v,"y",f,"px")),(y||b||_||w)&&(T=xt(T+y-(y*r+b*i)+_),k=xt(k+b-(y*n+b*a)+w)),(u||l)&&(o=v.getBBox(),T=xt(T+u/100*o.width),k=xt(k+l/100*o.height)),o="matrix("+r+","+n+","+i+","+a+","+T+","+k+")",v.setAttribute("transform",o),x&&(v.style[sn]=o)},Fn=function(t,e,r,n,i,a){var o,s,u=q(i),l=parseFloat(i)*(u&&~i.indexOf("rad")?qr:1),c=a?l*a:l-n,f=n+c+"deg";return u&&("short"===(o=i.split("_")[1])&&(c%=360)!==c%180&&(c+=c<0?360:-360),"cw"===o&&c<0?c=(c+36e9)%360-360*~~(c/360):"ccw"===o&&c>0&&(c=(c-36e9)%360-360*~~(c/360))),t._pt=s=new lr(t._pt,e,r,n,c,Xr),s.e=f,s.u="deg",t._props.push(r),s},Vn=function(t,e,r){var n,i,a,o,s,u,l,c=br.style,f=r._gsap;for(i in c.cssText=getComputedStyle(r).cssText+";position:absolute;display:block;",c[sn]=e,mr.body.appendChild(br),n=jn(br,1),Vr)(a=f[i])!==(o=n[i])&&"perspective,force3D,transformOrigin,svgOrigin".indexOf(i)<0&&(s=te(a)!==(l=te(o))?wn(r,i,a,l):parseFloat(a),u=parseFloat(o),t._pt=new lr(t._pt,f,i,s,u-s,Wr),t._pt.u=l||0,t._props.push(i));mr.body.removeChild(br)};wt("padding,margin,Width,Radius",(function(t,e){var r="Top",n="Right",i="Bottom",a="Left",o=(e<3?[r,n,i,a]:[r+a,r+n,i+n,i+a]).map((function(r){return e<2?t+r:"border"+r+t}));On[e>1?"border"+t:t]=function(t,e,r,n,i){var a,s;if(arguments.length<4)return a=o.map((function(e){return xn(t,e,r)})),5===(s=a.join(" ")).split(a[0]).length?a[0]:s;a=(n+"").split(" "),s={},o.forEach((function(t,e){return s[t]=a[e]=a[e]||a[(e-1)/2|0]})),t.init(e,s,i)}}));var qn,Bn,Hn={name:"css",register:hn,targetTest:function(t){return t.style&&t.nodeType},init:function(t,e,r,n,i){var a,o,s,u,l,c,f,d,h,p,m,g,v,y,b,_,w,x,T,k=this._props,S=t.style;for(f in vr||hn(),e)if("autoRound"!==f&&(o=e[f],!ht[f]||!Ue(f,e,r,n,t,i)))if(l=typeof o,c=On[f],"function"===l&&(l=typeof(o=o.call(r,n,t,i))),"string"===l&&~o.indexOf("random(")&&(o=fe(o)),c)c(this,t,f,o,r)&&(b=1);else if("--"===f.substr(0,2))this.add(S,"setProperty",getComputedStyle(t).getPropertyValue(f)+"",o+"",n,i,0,0,f);else if("undefined"!==l){if(a=xn(t,f),u=parseFloat(a),(p="string"===l&&"="===o.charAt(1)?+(o.charAt(0)+"1"):0)&&(o=o.substr(2)),s=parseFloat(o),f in $r&&("autoAlpha"===f&&(1===u&&"hidden"===xn(t,"visibility")&&s&&(u=0),bn(this,S,"visibility",u?"inherit":"hidden",s?"inherit":"hidden",!s)),"scale"!==f&&"transform"!==f&&~(f=$r[f]).indexOf(",")&&(f=f.split(",")[0])),m=f in Vr)if(g||((v=t._gsap).renderTransform||jn(t),y=!1!==e.smoothOrigin&&v.smooth,(g=this._pt=new lr(this._pt,S,sn,0,1,v.renderTransform,v,0,-1)).dep=1),"scale"===f)this._pt=new lr(this._pt,v,"scaleY",v.scaleY,p?p*s:s-v.scaleY),k.push("scaleY",f),f+="X";else{if("transformOrigin"===f){w=void 0,x=void 0,T=void 0,w=(_=o).split(" "),x=w[0],T=w[1]||"50%","top"!==x&&"bottom"!==x&&"left"!==T&&"right"!==T||(_=x,x=T,T=_),w[0]=kn[x]||x,w[1]=kn[T]||T,o=w.join(" "),v.svg?In(t,o,0,y,0,this):((h=parseFloat(o.split(" ")[2])||0)!==v.zOrigin&&bn(this,v,"zOrigin",v.zOrigin,h),bn(this,S,f,Rn(a),Rn(o)));continue}if("svgOrigin"===f){In(t,o,1,y,0,this);continue}if(f in En){Fn(this,v,f,u,o,p);continue}if("smoothOrigin"===f){bn(this,v,"smooth",v.smooth,o);continue}if("force3D"===f){v[f]=o;continue}if("transform"===f){Vn(this,o,t);continue}}else f in S||(f=dn(f)||f);if(m||(s||0===s)&&(u||0===u)&&!Gr.test(o)&&f in S)s||(s=0),(d=(a+"").substr((u+"").length))!==(h=te(o)||(f in I.units?I.units[f]:d))&&(u=wn(t,f,a,h)),this._pt=new lr(this._pt,m?v:S,f,u,p?p*s:s-u,"px"!==h||!1===e.autoRound||m?Wr:Zr),this._pt.u=h||0,d!==h&&(this._pt.b=a,this._pt.r=Qr);else if(f in S)Tn.call(this,t,f,a,o);else{if(!(f in t)){ot(f,o);continue}this.add(t,f,t[f],o,n,i)}k.push(f)}b&&ur(this)},get:xn,aliases:$r,getSetter:function(t,e,r){var n=$r[e];return n&&n.indexOf(",")<0&&(e=n),e in Vr&&e!==un&&(t._gsap.x||xn(t,"x"))?r&&_r===r?"scale"===e?nn:rn:(_r=r||{})&&("scale"===e?an:on):t.style&&!U(t.style[e])?tn:~e.indexOf("-")?en:tr(t,e)},core:{_removeProperty:yn,_getMatrix:Pn}};hr.utils.checkPrefix=dn,Bn=wt("x,y,z,scale,scaleX,scaleY,xPercent,yPercent,"+(qn="rotation,rotationX,rotationY,skewX,skewY")+",transform,transformOrigin,svgOrigin,force3D,smoothOrigin,transformPerspective",(function(t){Vr[t]=1})),wt(qn,(function(t){I.units[t]="deg",En[t]=1})),$r[Bn[13]]="x,y,z,scale,scaleX,scaleY,xPercent,yPercent,"+qn,wt("0:translateX,1:translateY,2:translateZ,8:rotate,8:rotationZ,8:rotateZ,9:rotateX,10:rotateY",(function(t){var e=t.split(":");$r[e[1]]=Bn[e[0]]})),wt("x,y,z,top,right,bottom,left,width,height,fontSize,padding,margin,perspective",(function(t){I.units[t]="px"})),hr.registerPlugin(Hn);var Un=hr.registerPlugin(Hn)||hr,Yn=Un.core.Tween}}]);
//# sourceMappingURL=207e61d01b9a6e9d440f6c73e1b6c16da759b29a-53910a28a02fdba66c0a.js.map
|
// This file has been autogenerated.
exports.setEnvironment = function() {
process.env['AZURE_STORAGE_CONNECTION_STRING'] = 'DefaultEndpointsProtocol=http;AccountName=xplat;AccountKey=null';
}
exports.scopes = [[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1?restype=share')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'e47a4d0c-001a-0045-4e52-cf4b96000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:47 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1?restype=share')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:47 GMT',
etag: '"0x8D29D692DB3059E"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'f7543ef4-001a-0024-3a52-cf0f49000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:47 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata2?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'cbbd6d24-001a-0004-7652-cf6385000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:46 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata2?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:48 GMT',
etag: '"0x8D29D692E129D15"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '704105d6-001a-000b-2252-cf8e73000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:47 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata2?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:48 GMT',
etag: '"0x8D29D692E129D15"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '50efbabd-001a-003b-7352-cfd459000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:48 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:48 GMT',
etag: '"0x8D29D692E714DD8"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '449254e6-001a-001d-6652-cf4fed000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:48 GMT',
connection: 'close' });
return result; }],
[],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata5?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:49 GMT',
etag: '"0x8D29D692EA11B8A"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '14380995-001a-004c-5c52-cf5118000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:48 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata5?restype=directory')
.reply(409, "<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ResourceAlreadyExists</Code><Message>The specified resource already exists.\nRequestId:cbbd6d28-001a-0004-7752-cf6385000000\nTime:2015-08-05T07:40:49.4148642Z</Message></Error>", { 'content-length': '228',
'content-type': 'application/xml',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'cbbd6d28-001a-0004-7752-cf6385000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:48 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.delete('/directory-test-share-testdata1/dir-testdata5?restype=directory')
.reply(202, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'ba9fc255-001a-0033-7252-cfcf2a000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:49 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata7/?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:50 GMT',
etag: '"0x8D29D692F3280D3"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '633ac1b2-001a-0026-0a52-cf0db3000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:49 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata7/?restype=directory')
.reply(409, "<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ResourceAlreadyExists</Code><Message>The specified resource already exists.\nRequestId:be5b130d-001a-002e-4252-cf16c0000000\nTime:2015-08-05T07:40:49.9681095Z</Message></Error>", { 'content-length': '228',
'content-type': 'application/xml',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'be5b130d-001a-002e-4252-cf16c0000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:49 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.delete('/directory-test-share-testdata1/dir-testdata7/?restype=directory')
.reply(202, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'fb463fd4-001a-0049-0e52-cfa567000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:49 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata8?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'c63c65ff-001a-0001-7852-cf97fa000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:50 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata8?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:51 GMT',
etag: '"0x8D29D692FE8DBD8"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '449254eb-001a-001d-6752-cf4fed000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:50 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata8?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:51 GMT',
etag: '"0x8D29D692FE8DBD8"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '14380999-001a-004c-5d52-cf5118000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:51 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata8?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:51 GMT',
etag: '"0x8D29D692FE8DBD8"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '03f96123-001a-003f-3752-cf21db000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:51 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.delete('/directory-test-share-testdata1/dir-testdata8?restype=directory')
.reply(202, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'ba9fc259-001a-0033-7352-cfcf2a000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:51 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata8?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '633ac1b6-001a-0026-0b52-cf0db3000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:51 GMT',
connection: 'close' });
return result; }],
[],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata10?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'd76b9b86-001a-0042-3752-cfbd13000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:52 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata10?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'fb463fd8-001a-0049-0f52-cfa567000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:52 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata10?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:53 GMT',
etag: '"0x8D29D6931274B3D"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'c63c667a-001a-0001-6e52-cf97fa000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:53 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata10?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:53 GMT',
etag: '"0x8D29D6931274B3D"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '17efca9b-001a-0030-2052-cfcc2d000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:53 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.delete('/directory-test-share-testdata1/dir-testdata10?restype=directory')
.reply(202, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'f6e08abc-001a-0038-2c52-cfd75e000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:53 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata10?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '03f96136-001a-003f-4652-cf21db000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:53 GMT',
connection: 'close' });
return result; }],
[],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata12?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '5d5be712-001a-0047-2e52-cf496c000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:54 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata12?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:54 GMT',
etag: '"0x8D29D69321081D8"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '418f25fe-001a-0012-6352-cfa21b000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:54 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata12?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:54 GMT',
etag: '"0x8D29D69321081D8"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'd76b9b8a-001a-0042-3952-cfbd13000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:54 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.delete('/directory-test-share-testdata1/dir-testdata12?restype=directory')
.reply(202, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '5a6dc983-001a-0021-5352-cffb36000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:55 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:48 GMT',
etag: '"0x8D29D692E714DD8"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '566c3d00-001a-0029-4752-cfe045000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:55 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata18?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '17efcab2-001a-0030-3452-cfcc2d000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:56 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata18?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:56 GMT',
etag: '"0x8D29D6932F7470A"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'f6e08aff-001a-0038-6d52-cfd75e000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:56 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.get('/directory-test-share-testdata1/dir-testdata18?restype=directory&comp=list')
.reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><EnumerationResults ServiceEndpoint=\"http://xplat.file.core.windows.net/\" ShareName=\"directory-test-share-testdata1\" DirectoryPath=\"dir-testdata18\"><Entries /><NextMarker /></EnumerationResults>", { 'transfer-encoding': 'chunked',
'content-type': 'application/xml',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '2de1f10f-001a-002b-2c52-cfe2bf000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:55 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata19?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '5d5be719-001a-0047-3352-cf496c000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:57 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata19?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:57 GMT',
etag: '"0x8D29D6933885E0A"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '418f2602-001a-0012-6552-cfa21b000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:56 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata19/dir-testdata14?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:57 GMT',
etag: '"0x8D29D6933B67DA3"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'bc6721c3-001a-001a-6452-cfb968000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:57 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.get('/directory-test-share-testdata1/dir-testdata19?restype=directory&comp=list')
.reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><EnumerationResults ServiceEndpoint=\"http://xplat.file.core.windows.net/\" ShareName=\"directory-test-share-testdata1\" DirectoryPath=\"dir-testdata19\"><Entries><Directory><Name>dir-testdata14</Name><Properties /></Directory></Entries><NextMarker /></EnumerationResults>", { 'transfer-encoding': 'chunked',
'content-type': 'application/xml',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '5a6dc986-001a-0021-5452-cffb36000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:57 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata20?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '566c3d03-001a-0029-4852-cfe045000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:57 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata20?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:58 GMT',
etag: '"0x8D29D6934419FEB"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '156db6e6-001a-0044-6e52-cf4a6b000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:58 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata20/file-testdata16')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:58 GMT',
etag: '"0x8D29D693470AA20"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '82bc5823-001a-000f-4852-cf7bf1000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:58 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.get('/directory-test-share-testdata1/dir-testdata20?restype=directory&comp=list')
.reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><EnumerationResults ServiceEndpoint=\"http://xplat.file.core.windows.net/\" ShareName=\"directory-test-share-testdata1\" DirectoryPath=\"dir-testdata20\"><Entries><File><Name>file-testdata16</Name><Properties><Content-Length>0</Content-Length></Properties></File></Entries><NextMarker /></EnumerationResults>", { 'transfer-encoding': 'chunked',
'content-type': 'application/xml',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '2de1f139-001a-002b-5452-cfe2bf000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:58 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata21?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '7751ccce-001a-0046-3d52-cf4891000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:59 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata21?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:59 GMT',
etag: '"0x8D29D693503BD81"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'af41ffc4-001a-003a-4952-cfd5a4000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:59 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata21/dir-testdata14?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:00 GMT',
etag: '"0x8D29D693530561F"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'bc6721c7-001a-001a-6552-cfb968000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:40:59 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata21/dir-testdata15?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:00 GMT',
etag: '"0x8D29D69355EC3E6"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '33833ab3-001a-0035-3852-cf3852000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:00 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata21/file-testdata16')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:00 GMT',
etag: '"0x8D29D69358C4716"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'f141f875-001a-0015-3552-cf549e000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:01 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata21/file-testdata17')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:01 GMT',
etag: '"0x8D29D6935B95509"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '156db6ea-001a-0044-6f52-cf4a6b000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:00 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.get('/directory-test-share-testdata1/dir-testdata21?restype=directory&comp=list')
.reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><EnumerationResults ServiceEndpoint=\"http://xplat.file.core.windows.net/\" ShareName=\"directory-test-share-testdata1\" DirectoryPath=\"dir-testdata21\"><Entries><Directory><Name>dir-testdata14</Name><Properties /></Directory><Directory><Name>dir-testdata15</Name><Properties /></Directory><File><Name>file-testdata16</Name><Properties><Content-Length>0</Content-Length></Properties></File><File><Name>file-testdata17</Name><Properties><Content-Length>0</Content-Length></Properties></File></Entries><NextMarker /></EnumerationResults>", { 'transfer-encoding': 'chunked',
'content-type': 'application/xml',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '82bc5828-001a-000f-4952-cf7bf1000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:01 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata22?restype=directory')
.reply(404, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'e2b6c252-001a-0017-0b52-cf5664000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:01 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata22?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:02 GMT',
etag: '"0x8D29D6936438CB6"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '7751cd2b-001a-0046-1652-cf4891000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:01 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata22/file-testdata16')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:02 GMT',
etag: '"0x8D29D6936707387"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'af41ffc8-001a-003a-4b52-cfd5a4000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:02 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.get('/directory-test-share-testdata1/dir-testdata22?restype=directory&comp=list')
.reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><EnumerationResults ServiceEndpoint=\"http://xplat.file.core.windows.net/\" ShareName=\"directory-test-share-testdata1\" DirectoryPath=\"dir-testdata22\"><Entries><File><Name>file-testdata16</Name><Properties><Content-Length>0</Content-Length></Properties></File></Entries><NextMarker /></EnumerationResults>", { 'transfer-encoding': 'chunked',
'content-type': 'application/xml',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'f1183d24-001a-0006-5652-cf617f000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:02 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata22/next?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:02 GMT',
etag: '"0x8D29D6936D54036"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '33833ac0-001a-0035-4252-cf3852000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:02 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.get('/directory-test-share-testdata1/dir-testdata22?restype=directory&comp=list')
.reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><EnumerationResults ServiceEndpoint=\"http://xplat.file.core.windows.net/\" ShareName=\"directory-test-share-testdata1\" DirectoryPath=\"dir-testdata22\"><Entries><File><Name>file-testdata16</Name><Properties><Content-Length>0</Content-Length></Properties></File><Directory><Name>next</Name><Properties /></Directory></Entries><NextMarker /></EnumerationResults>", { 'transfer-encoding': 'chunked',
'content-type': 'application/xml',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'f141f87a-001a-0015-3752-cf549e000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:03 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata23?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:03 GMT',
etag: '"0x8D29D6937337BAE"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'e46cd0a3-001a-0008-5752-cf8d74000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:02 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata23?restype=directory&comp=metadata')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:03 GMT',
etag: '"0x8D29D693767901A"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '9b24eb51-001a-0037-1c52-cf3aa8000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:02 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata23?restype=directory&comp=metadata')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:03 GMT',
etag: '"0x8D29D693767901A"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'e2b6c258-001a-0017-0c52-cf5664000000',
'x-ms-version': '2015-02-21',
'x-ms-meta-class': 'Test',
date: 'Wed, 05 Aug 2015 07:41:03 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata24?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:04 GMT',
etag: '"0x8D29D6937CDE3C4"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '739d552f-001a-001e-4152-cf4cea000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:04 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata24?restype=directory&comp=metadata')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:04 GMT',
etag: '"0x8D29D6937CDE3C4"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'bc623dbd-001a-0025-1a52-cf0eb4000000',
'x-ms-version': '2015-02-21',
'x-ms-meta-class': 'Test',
date: 'Wed, 05 Aug 2015 07:41:03 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata25?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:05 GMT',
etag: '"0x8D29D69382D7F1E"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'f1183d28-001a-0006-5852-cf617f000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:05 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata25?restype=directory&comp=metadata')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:05 GMT',
etag: '"0x8D29D69385C6235"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '4f2a466d-001a-0048-2f52-cfa49a000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:05 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata25?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:05 GMT',
etag: '"0x8D29D69385C6235"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'e76b79ed-001a-0028-6552-cfe1b8000000',
'x-ms-version': '2015-02-21',
'x-ms-meta-color': 'Blue',
date: 'Wed, 05 Aug 2015 07:41:05 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata26?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:06 GMT',
etag: '"0x8D29D6938B9B316"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'e46cd0a8-001a-0008-5952-cf8d74000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:04 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata26?restype=directory&comp=metadata')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:06 GMT',
etag: '"0x8D29D6938E6E819"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '9b24eb59-001a-0037-2152-cf3aa8000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:05 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata26?restype=directory&comp=metadata')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:06 GMT',
etag: '"0x8D29D6938E6E819"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '0b079a6b-001a-0003-5152-cf9500000000',
'x-ms-version': '2015-02-21',
'x-ms-meta-class': 'Test',
date: 'Wed, 05 Aug 2015 07:41:05 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata27?restype=directory')
.reply(201, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:07 GMT',
etag: '"0x8D29D6939465C5F"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '739d5534-001a-001e-4352-cf4cea000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:06 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata27?restype=directory&comp=metadata')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:07 GMT',
etag: '"0x8D29D69397C45F3"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'bc623dc2-001a-0025-1c52-cf0eb4000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:06 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata27?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:07 GMT',
etag: '"0x8D29D69397C45F3"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '37fa73f1-001a-0019-0152-cfba6f000000',
'x-ms-version': '2015-02-21',
'x-ms-meta-color': 'blue,Orange,Red',
date: 'Wed, 05 Aug 2015 07:41:06 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.put('/directory-test-share-testdata1/dir-testdata27?restype=directory&comp=metadata')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:08 GMT',
etag: '"0x8D29D6939D7C1A7"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '4f2a4673-001a-0048-3152-cfa49a000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:07 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1/dir-testdata27?restype=directory')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:41:08 GMT',
etag: '"0x8D29D6939D7C1A7"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'e76b79f1-001a-0028-6652-cfe1b8000000',
'x-ms-version': '2015-02-21',
'x-ms-meta-color': 'white,BLACK',
date: 'Wed, 05 Aug 2015 07:41:07 GMT',
connection: 'close' });
return result; }],
[function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.head('/directory-test-share-testdata1?restype=share')
.reply(200, "", { 'transfer-encoding': 'chunked',
'last-modified': 'Wed, 05 Aug 2015 07:40:47 GMT',
etag: '"0x8D29D692DB3059E"',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '5326f713-001a-001c-7c52-cf4e10000000',
'x-ms-version': '2015-02-21',
'x-ms-share-quota': '5120',
date: 'Wed, 05 Aug 2015 07:41:07 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://xplat.file.core.windows.net:80')
.delete('/directory-test-share-testdata1?restype=share')
.reply(202, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '057fed8e-001a-004b-2452-cfa79d000000',
'x-ms-version': '2015-02-21',
date: 'Wed, 05 Aug 2015 07:41:08 GMT',
connection: 'close' });
return result; }]];
|
import random
import string
import time
from django.conf import settings
from django.test import TestCase
from django.core.urlresolvers import NoReverseMatch, reverse
if not settings.configured:
settings.configure()
from axes.decorators import COOLOFF_TIME
from axes.decorators import FAILURE_LIMIT
from axes.models import AccessLog
from axes.signals import user_locked_out
from axes.utils import reset
class AccessAttemptTest(TestCase):
"""Test case using custom settings for testing
"""
VALID_PASSWORD = 'valid-password'
LOCKED_MESSAGE = 'Account locked: too many login attempts.'
LOGIN_FORM_KEY = '<input type="submit" value="Log in" />'
def _login(self, is_valid=False, user_agent='test-browser'):
"""Login a user. A valid credential is used when is_valid is True,
otherwise it will use a random string to make a failed login.
"""
try:
admin_login = reverse('admin:login')
except NoReverseMatch:
admin_login = reverse('admin:index')
if is_valid:
# Use a valid username
username = self.user.username
else:
# Generate a wrong random username
chars = string.ascii_uppercase + string.digits
username = ''.join(random.choice(chars) for x in range(10))
response = self.client.post(admin_login, {
'username': username,
'password': self.VALID_PASSWORD,
'this_is_the_login_form': 1,
}, HTTP_USER_AGENT=user_agent)
return response
def setUp(self):
"""Create a valid user for login
"""
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
self.user = User.objects.create_superuser(
username='valid-username',
email='test@example.com',
password=self.VALID_PASSWORD,
)
def test_failure_limit_once(self):
"""Tests the login lock trying to login one more time
than failure limit
"""
for i in range(1, FAILURE_LIMIT): # test until one try before the limit
response = self._login()
# Check if we are in the same login page
self.assertContains(response, self.LOGIN_FORM_KEY)
# So, we shouldn't have gotten a lock-out yet.
# But we should get one now
response = self._login()
self.assertContains(response, self.LOCKED_MESSAGE)
def test_failure_limit_many(self):
"""Tests the login lock trying to login a lot of times more
than failure limit
"""
for i in range(1, FAILURE_LIMIT):
response = self._login()
# Check if we are in the same login page
self.assertContains(response, self.LOGIN_FORM_KEY)
# So, we shouldn't have gotten a lock-out yet.
# We should get a locked message each time we try again
for i in range(0, random.randrange(1, FAILURE_LIMIT)):
response = self._login()
self.assertContains(response, self.LOCKED_MESSAGE)
def test_failure_username_ip(self):
"""Tests the login lock based on a combination of username
and IP address
"""
with self.settings(AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP=True):
for i in range(1, FAILURE_LIMIT): # test until one try before the limit
response = self._login()
# Check if we are in the same login page
self.assertContains(response, self.LOGIN_FORM_KEY)
# So, we shouldn't have gotten a lock-out yet.
# But we should get one now
response = self._login()
self.assertContains(response, self.LOCKED_MESSAGE)
self.user.username='other-user'
self.user.save()
response = self._login()
self.test_valid_login()
def test_valid_login(self):
"""Tests a valid login for a real username
"""
response = self._login(is_valid=True)
self.assertNotContains(response, self.LOGIN_FORM_KEY, status_code=302)
def test_valid_logout(self):
"""Tests a valid logout and make sure the logout_time is updated
"""
response = self._login(is_valid=True)
self.assertEquals(AccessLog.objects.latest('id').logout_time, None)
response = self.client.get(reverse('admin:logout'))
self.assertNotEquals(AccessLog.objects.latest('id').logout_time, None)
self.assertContains(response, 'Logged out')
def test_cooling_off(self):
"""Tests if the cooling time allows a user to login
"""
self.test_failure_limit_once()
# Wait for the cooling off period
time.sleep(COOLOFF_TIME.total_seconds())
# It should be possible to login again, make sure it is.
self.test_valid_login()
def test_cooling_off_for_trusted_user(self):
"""Test the cooling time for a trusted user
"""
# Test successful login-logout, this makes the user trusted.
self.test_valid_logout()
# Try the cooling off time
self.test_cooling_off()
def test_long_user_agent_valid(self):
"""Tests if can handle a long user agent
"""
long_user_agent = 'ie6' * 1024
response = self._login(is_valid=True, user_agent=long_user_agent)
self.assertNotContains(response, self.LOGIN_FORM_KEY, status_code=302)
def test_long_user_agent_not_valid(self):
"""Tests if can handle a long user agent with failure
"""
long_user_agent = 'ie6' * 1024
for i in range(0, FAILURE_LIMIT + 1):
response = self._login(user_agent=long_user_agent)
self.assertContains(response, self.LOCKED_MESSAGE)
def test_reset_ip(self):
"""Tests if can reset an ip address
"""
# Make a lockout
self.test_failure_limit_once()
# Reset the ip so we can try again
reset(ip='127.0.0.1')
# Make a login attempt again
self.test_valid_login()
def test_reset_all(self):
"""Tests if can reset all attempts
"""
# Make a lockout
self.test_failure_limit_once()
# Reset all attempts so we can try again
reset()
# Make a login attempt again
self.test_valid_login()
def test_send_lockout_signal(self):
"""Test if the lockout signal is emitted
"""
class Scope(object): pass # this "hack" is needed so we don't have to use global variables or python3 features
scope = Scope()
scope.signal_received = 0
def signal_handler(request, username, ip_address, *args, **kwargs):
scope.signal_received += 1
self.assertIsNotNone(request)
# Connect signal handler
user_locked_out.connect(signal_handler)
# Make a lockout
self.test_failure_limit_once()
self.assertEquals(scope.signal_received, 1)
reset()
# Make another lockout
self.test_failure_limit_once()
self.assertEquals(scope.signal_received, 2)
|
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import datetime
def max_partition(
table, schema="default", field=None, filter_map=None,
metastore_conn_id='metastore_default'):
"""
Gets the max partition for a table.
:param schema: The hive schema the table lives in
:type schema: str
:param table: The hive table you are interested in, supports the dot
notation as in "my_database.my_table", if a dot is found,
the schema param is disregarded
:type table: str
:param metastore_conn_id: The hive connection you are interested in.
If your default is set you don't need to use this parameter.
:type metastore_conn_id: str
:param filter_map: partition_key:partition_value map used for partition filtering,
e.g. {'key1': 'value1', 'key2': 'value2'}.
Only partitions matching all partition_key:partition_value
pairs will be considered as candidates of max partition.
:type filter_map: map
:param field: the field to get the max value from. If there's only
one partition field, this will be inferred
:type field: str
>>> max_partition('airflow.static_babynames_partitioned')
'2015-01-01'
"""
from airflow.hooks.hive_hooks import HiveMetastoreHook
if '.' in table:
schema, table = table.split('.')
hh = HiveMetastoreHook(metastore_conn_id=metastore_conn_id)
return hh.max_partition(
schema=schema, table_name=table, field=field, filter_map=filter_map)
def _closest_date(target_dt, date_list, before_target=None):
"""
This function finds the date in a list closest to the target date.
An optional parameter can be given to get the closest before or after.
:param target_dt: The target date
:type target_dt: datetime.date
:param date_list: The list of dates to search
:type date_list: datetime.date list
:param before_target: closest before or after the target
:type before_target: bool or None
:returns: The closest date
:rtype: datetime.date or None
"""
fb = lambda d: target_dt - d if d <= target_dt else datetime.timedelta.max
fa = lambda d: d - target_dt if d >= target_dt else datetime.timedelta.max
fnone = lambda d: target_dt - d if d < target_dt else d - target_dt
if before_target is None:
return min(date_list, key=fnone).date()
if before_target:
return min(date_list, key=fb).date()
else:
return min(date_list, key=fa).date()
def closest_ds_partition(
table, ds, before=True, schema="default",
metastore_conn_id='metastore_default'):
"""
This function finds the date in a list closest to the target date.
An optional parameter can be given to get the closest before or after.
:param table: A hive table name
:type table: str
:param ds: A datestamp ``%Y-%m-%d`` e.g. ``yyyy-mm-dd``
:type ds: datetime.date list
:param before: closest before (True), after (False) or either side of ds
:type before: bool or None
:returns: The closest date
:rtype: str or None
>>> tbl = 'airflow.static_babynames_partitioned'
>>> closest_ds_partition(tbl, '2015-01-02')
'2015-01-01'
"""
from airflow.hooks.hive_hooks import HiveMetastoreHook
if '.' in table:
schema, table = table.split('.')
hh = HiveMetastoreHook(metastore_conn_id=metastore_conn_id)
partitions = hh.get_partitions(schema=schema, table_name=table)
if not partitions:
return None
part_vals = [list(p.values())[0] for p in partitions]
if ds in part_vals:
return ds
else:
parts = [datetime.datetime.strptime(pv, '%Y-%m-%d')
for pv in part_vals]
target_dt = datetime.datetime.strptime(ds, '%Y-%m-%d')
closest_ds = _closest_date(target_dt, parts, before_target=before)
return closest_ds.isoformat()
|
from __future__ import annotations
import asyncio
import logging
from typing import (
AsyncGenerator,
ClassVar, Type,
Optional, Tuple, Union,
)
import attr
import zmq, zmq.asyncio
from ..abc import RawHeaderBody
from ..auth import Identity
from . import (
AbstractAddress,
AbstractBinder, AbstractConnector,
AbstractConnection,
BaseTransport,
)
ZAP_VERSION = b'1.0'
@attr.s(auto_attribs=True, slots=True)
class ZeroMQAddress(AbstractAddress):
uri: Union[str, Tuple[str, int]]
class ZAPServer:
'''
A simple authenticator adaptor that implements ZAP protocol.
'''
def __init__(self, zctx, authenticator=None):
self._log = logging.getLogger(__name__ + '.ZAPServer')
self._authenticator = authenticator
self._zap_socket = None
self._zctx = zctx
async def serve(self):
self._zap_socket = self._zctx.socket(zmq.REP)
self._zap_socket.linger = 1
self._zap_socket.bind('inproc://zeromq.zap.01')
try:
while True:
msg = await self._zap_socket.recv_multipart()
await self.handle_zap_message(msg)
except asyncio.CancelledError:
pass
finally:
self._zap_socket.close()
self._zap_socket = None
def close(self):
if self._zap_socket is not None:
self._zap_socket.close()
self._zap_socket = None
async def handle_zap_message(self, msg):
if len(msg) < 6:
self._log.error('Invalid ZAP message, not enough frames: %r', msg)
if len(msg) < 2:
self._log.error('Not enough information to reply')
else:
await self._send_zap_reply(msg[1], b'400', b'Not enough frames')
return
version, request_id, domain, address, sock_identity, mechanism = msg[:6]
credentials = msg[6:]
domain = domain.decode('utf8', 'replace')
address = address.decode('utf8', 'replace')
if (version != ZAP_VERSION):
self._log.error('Invalid ZAP version: %r', msg)
await self._send_zap_reply(request_id, b'400', b'Invalid version')
return
self.log.debug('version: %r, request_id: %r, domain: %r, '
'address: %r, sock_identity: %r, mechanism: %r',
version, request_id, domain,
address, sock_identity, mechanism)
allowed = False
user_id = '<anonymous>'
reason = b'Access denied'
if self._authenticator is None:
# When authenticator is not set, allow any NULL auth-requests.
await self._send_zap_reply(request_id, b'200', b'OK', user_id)
return
if mechanism == b'CURVE':
# For CURVE, even a whitelisted address must authenticate
if len(credentials) != 1:
self._log.info('Invalid CURVE credentials: %r', credentials)
await self._send_zap_reply(request_id,
b'400', b'Invalid credentials')
return
key = credentials[0]
client_id = Identity(domain, key)
result = await self._authenticator.check_client(client_id)
allowed = result.success
if allowed:
user_id = result.user_id
else:
# In Callosum, we only support public-key based authentication.
# Other possible values: b'NULL', b'PLAIN', b'GSSAPI'
reason = b'Unsupported authentication mechanism'
if allowed:
await self._send_zap_reply(request_id, b'200', b'OK', user_id)
else:
await self._send_zap_reply(request_id, b'400', reason)
async def _send_zap_reply(self, request_id: bytes,
status_code: bytes, status_text: bytes,
user_id: str = ''):
metadata = b''
self._log.debug('ZAP reply code=%s text=%s', status_code, status_text)
reply = (ZAP_VERSION, request_id,
status_code, status_text,
user_id.encode('utf8', 'replace'),
metadata)
await self._zap_socket.send_multipart(reply)
class ZeroMQRPCConnection(AbstractConnection):
__slots__ = ('transport')
transport: ZeroMQRPCTransport
def __init__(self, transport):
self.transport = transport
async def recv_message(self) -> AsyncGenerator[Optional[RawHeaderBody], None]:
assert not self.transport._closed
*pre, raw_header, raw_body = await self.transport._sock.recv_multipart()
if len(pre) > 0:
# server
peer_id = pre[0]
yield RawHeaderBody(raw_header, raw_body, peer_id)
else:
# client
yield RawHeaderBody(raw_header, raw_body, None)
async def send_message(self, raw_msg: RawHeaderBody) -> None:
assert not self.transport._closed
peer_id = raw_msg.peer_id
if peer_id is not None:
# server
await self.transport._sock.send_multipart([
peer_id, raw_msg.header, raw_msg.body,
])
else:
# client
await self.transport._sock.send_multipart([
raw_msg.header, raw_msg.body,
])
class ZeroMQBaseBinder(AbstractBinder):
__slots__ = ('transport', 'addr')
socket_type: ClassVar[int] = 0
transport: ZeroMQBaseTransport
addr: ZeroMQAddress
async def __aenter__(self):
if not self.transport._closed:
return ZeroMQRPCConnection(self.transport)
server_sock = self.transport._zctx.socket(type(self).socket_type)
if self.transport.authenticator:
server_id = await self.transport.authenticator.server_identity()
server_sock.zap_domain = server_id.domain.encode('utf8')
server_sock.setsockopt(zmq.CURVE_SERVER, 1)
server_sock.setsockopt(zmq.CURVE_SECRETKEY, server_id.private_key)
for key, value in self.transport._zsock_opts.items():
server_sock.setsockopt(key, value)
server_sock.bind(self.addr.uri)
self.transport._sock = server_sock
return ZeroMQRPCConnection(self.transport)
async def __aexit__(self, exc_type, exc_obj, exc_tb):
pass
class ZeroMQBaseConnector(AbstractConnector):
__slots__ = ('transport', 'addr')
socket_type: ClassVar[int] = 0
transport: ZeroMQBaseTransport
addr: ZeroMQAddress
async def __aenter__(self):
if not self.transport._closed:
return ZeroMQRPCConnection(self.transport)
client_sock = self.transport._zctx.socket(type(self).socket_type)
if self.transport.authenticator:
auth = self.transport.authenticator
client_id = await auth.client_identity()
client_public_key = await auth.client_public_key()
server_public_key = await auth.server_public_key()
client_sock.zap_domain = client_id.domain.encode('utf8')
client_sock.setsockopt(zmq.CURVE_SERVERKEY, server_public_key)
client_sock.setsockopt(zmq.CURVE_PUBLICKEY, client_public_key)
client_sock.setsockopt(zmq.CURVE_SECRETKEY, client_id.private_key)
for key, value in self.transport._zsock_opts.items():
client_sock.setsockopt(key, value)
client_sock.connect(self.addr.uri)
self.transport._sock = client_sock
return ZeroMQRPCConnection(self.transport)
async def __aexit__(self, exc_type, exc_obj, exc_tb):
pass
class ZeroMQRouterBinder(ZeroMQBaseBinder):
socket_type: ClassVar[int] = zmq.ROUTER
transport: ZeroMQRPCTransport
class ZeroMQDealerConnector(ZeroMQBaseConnector):
socket_type: ClassVar[int] = zmq.DEALER
transport: ZeroMQRPCTransport
class ZeroMQPushBinder(ZeroMQBaseBinder):
socket_type: ClassVar[int] = zmq.PUSH
transport: ZeroMQDistributorTransport
class ZeroMQPullConnector(ZeroMQBaseConnector):
socket_type: ClassVar[int] = zmq.PULL
transport: ZeroMQDistributorTransport
class ZeroMQPubBinder(ZeroMQBaseBinder):
socket_type: ClassVar[int] = zmq.PUB
transport: ZeroMQBroadcastTransport
class ZeroMQSubConnector(ZeroMQBaseConnector):
socket_type: ClassVar[int] = zmq.SUB
transport: ZeroMQBroadcastTransport
class ZeroMQBaseTransport(BaseTransport):
'''
Implementation for the ZeorMQ-backed transport.
It keeps a single persistent connection over multiple connect/bind() calls.
As the underlying PUSH/PULL sockets work asynchronously, this effectively
achieves connection pooling reducing handshake overheads.
'''
__slots__ = BaseTransport.__slots__ + (
'_zctx', '_zsock_opts',
'_zap_server', '_zap_task',
'_sock',
)
binder_cls: ClassVar[Type[ZeroMQBaseBinder]]
connector_cls: ClassVar[Type[ZeroMQBaseConnector]]
def __init__(self, authenticator, **kwargs):
loop = asyncio.get_event_loop()
self._zap_server = None
self._zap_task = None
transport_opts = kwargs.pop('transport_opts', {})
self._zsock_opts = {
zmq.LINGER: 100,
**transport_opts.get('zsock_opts', {}),
}
super().__init__(authenticator, **kwargs)
if self.authenticator:
self._zap_server = ZAPServer(self.authenticator)
self._zap_task = loop.create_task(self.authenticator.serve())
self._zctx = zmq.asyncio.Context()
# Keep sockets during the transport lifetime.
self._sock = None
@property
def _closed(self):
if self._sock is not None:
return self._sock.closed
return True
async def close(self):
if self._sock is not None:
self._sock.close()
if self._zap_task is not None:
self._zap_task.cancel()
await self._zap_task
if self._zctx is not None:
self._zctx.destroy()
class ZeroMQRPCTransport(ZeroMQBaseTransport):
binder_cls = ZeroMQRouterBinder
connector_cls = ZeroMQDealerConnector
class ZeroMQDistributorTransport(ZeroMQBaseTransport):
binder_cls = ZeroMQPushBinder
connector_cls = ZeroMQPullConnector
class ZeroMQBroadcastTransport(ZeroMQBaseTransport):
binder_cls = ZeroMQPubBinder
connector_cls = ZeroMQSubConnector
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@interface TVHSMoviesPreviewViewControllerFactory : NSObject
{
}
+ (id)previewViewControllerForDataItem:(id)arg1; // IMP=0x00000001000062a4
@end
|
import Vue from 'vue'
import App from './App.vue'
// export const eventEmmiter = new Vue()
new Vue({
el: '#app',
render: h => h(App)
})
|
class User:
def __init__(self, first_name, last_name, birthday):
self.first_name = first_name
self.last_name = last_name
self.birthday = birthday
self.login_attempts = 0
self.password = 123456
self.account = "Aiden_zcf"
def describe_user(self):
print(
f"The user's first name is {self.first_name}, last name is {self.last_name}, birthday is {self.birthday}, account is {self.account}.")
def greet_user(self):
print(f"Morning, {self.last_name}")
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
me = User("Chaofan", "Zheng", 19980823)
me.describe_user()
me.greet_user()
me.increment_login_attempts()
me.increment_login_attempts()
me.increment_login_attempts()
print(me.login_attempts)
me.reset_login_attempts()
print(me.login_attempts)
|
#!/usr/bin/env python3
"""Typeset TLA+ specifications using `tla2tex.TLA`."""
# Copyright 2017 by California Institute of Technology
# All rights reserved. Licensed under 3-clause BSD.
#
import argparse
import datetime
import logging
import os
import subprocess
AUX_DIR = '__tlacache__/.aux'
TLA2TEX = 'tla2tex'
log = logging.getLogger(__name__)
def typeset_tla_files(files, tla2tex_options):
"""Typeset TLA+ files in `dirpath` as PDFs."""
for tlafile in files:
call_tla2tex(tlafile, tla2tex_options)
def call_tla2tex(tlafile, options):
"""Typeset `tlafile` using `TLA2TEX`."""
base, ext = os.path.splitext(tlafile)
assert ext == '.tla', tlafile
pdf = base + '.pdf'
if _is_newer(pdf, tlafile):
print((
'Skip "{tla}", because PDF file "{pdf}" '
'is newer.').format(
pdf=pdf, tla=tlafile))
return
if not os.path.isdir(AUX_DIR):
os.makedirs(AUX_DIR)
print('\nTypesetting file "{f}"'.format(f=tlafile))
cmd = [TLA2TEX, '-shade', *options, tlafile]
r = subprocess.call(cmd)
assert r == 0, r
def _is_newer(target, source):
"""Return `True` if `target` newer than `source` file."""
assert os.path.isfile(source), source
if not os.path.isfile(target):
return False
t_src = os.stat(source)[8]
t_tgt = os.stat(target)[8]
_print_dates(source, target, t_src, t_tgt)
return t_src < t_tgt
def _print_dates(source, target, t_src, t_tgt):
s = _format_time(t_src)
t = _format_time(t_tgt)
log.info((
'last modification dates:\n'
' Source ({source}): {s}\n'
' Target ({target}): {t}').format(
source=source, target=target,
s=s, t=t))
def _format_time(t):
"""Return time readable by humans."""
return datetime.datetime.fromtimestamp(t)
def _parse_args():
"""Return input file names and options for `tla2tex.TeX`."""
p = argparse.ArgumentParser()
p.add_argument('-i', '--input', nargs='+', type=str, required=True,
help='''input `*.tla` files. Additional arguments are passed
to `tla2tex.TLA`, for example:
tla2pdf.py \
-style $HOME/path/tlatex.sty \
-i *.tla
''')
args, unknown = p.parse_known_args()
files = args.input
tla2tex_options = unknown # assume `tla2tex` knows other args
log.info('input files: {fs}'.format(fs=files))
log.info('options for `tla2tex.TeX`: {opt}'.format(
opt=tla2tex_options))
return files, tla2tex_options
if __name__ == '__main__':
# log.addHandler(logging.StreamHandler())
# log.setLevel(logging.DEBUG)
files, tla2tex_options = _parse_args()
typeset_tla_files(files, tla2tex_options)
|
const Person = require('./02_Person');
function getPeople() {
//put the class in the function when submitting the problem in the Judge system
/*
class Person {
//let age = 18; can't be written because everything in the class has to be a function!!!!
constructor(firstName, lastName, age, email){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.email = email;
}
toString(){
return `${this.firstName} ${this.lastName} (age: ${this.age}, email: ${this.email})`;
}
}
*/
return [
new Person('Maria', 'Petrova', 22, 'mp@yahoo.com'),
new Person('SoftUni'),
new Person('Stephan', 'Nikolov', 25),
new Person('Peter', 'Kolev', 24, 'ptr@gmail.com'),
];
}
//.join will call toString method defined in the Person class file for every element in the collection
console.log(getPeople().join('\n'));
|
# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
from collections import defaultdict
import difflib
import logging
import six
import sys
import time
import os
from packaging.version import Version
from mock import Mock, patch
from cassandra import AlreadyExists, SignatureDescriptor, UserFunctionDescriptor, UserAggregateDescriptor
from cassandra.encoder import Encoder
from cassandra.metadata import (IndexMetadata, Token, murmur3, Function, Aggregate, protect_name, protect_names,
RegisteredTableExtension, _RegisteredExtensionType, get_schema_parser,
group_keys_by_replica, NO_VALID_REPLICA)
from cassandra.util import SortedSet
from tests.integration import (get_cluster, use_singledc, PROTOCOL_VERSION, execute_until_pass,
BasicSegregatedKeyspaceUnitTestCase, BasicSharedKeyspaceUnitTestCase,
BasicExistingKeyspaceUnitTestCase, drop_keyspace_shutdown_cluster, CASSANDRA_VERSION,
greaterthanorequaldse51, greaterthanorequalcass30, lessthancass30, local,
get_supported_protocol_versions, greaterthancass20,
greaterthancass21, assert_startswith, greaterthanorequalcass40,
greaterthanorequaldse67, lessthancass40,
TestCluster, DSE_VERSION)
log = logging.getLogger(__name__)
def setup_module():
use_singledc()
class HostMetaDataTests(BasicExistingKeyspaceUnitTestCase):
@local
def test_host_addresses(self):
"""
Check to ensure that the broadcast_address, broadcast_rpc_address,
listen adresss, ports and host are is populated correctly.
@since 3.3
@jira_ticket PYTHON-332
@expected_result They are populated for C*> 2.1.6, 2.2.0
@test_category metadata
"""
# All nodes should have the broadcast_address, rpc_address and host_id set
for host in self.cluster.metadata.all_hosts():
self.assertIsNotNone(host.broadcast_address)
self.assertIsNotNone(host.broadcast_rpc_address)
self.assertIsNotNone(host.host_id)
if not DSE_VERSION and CASSANDRA_VERSION >= Version('4-a'):
self.assertIsNotNone(host.broadcast_port)
self.assertIsNotNone(host.broadcast_rpc_port)
con = self.cluster.control_connection.get_connections()[0]
local_host = con.host
# The control connection node should have the listen address set.
listen_addrs = [host.listen_address for host in self.cluster.metadata.all_hosts()]
self.assertTrue(local_host in listen_addrs)
# The control connection node should have the broadcast_rpc_address set.
rpc_addrs = [host.broadcast_rpc_address for host in self.cluster.metadata.all_hosts()]
self.assertTrue(local_host in rpc_addrs)
@unittest.skipUnless(
os.getenv('MAPPED_CASSANDRA_VERSION', None) is not None,
"Don't check the host version for test-dse")
def test_host_release_version(self):
"""
Checks the hosts release version and validates that it is equal to the
Cassandra version we are using in our test harness.
@since 3.3
@jira_ticket PYTHON-301
@expected_result host.release version should match our specified Cassandra version.
@test_category metadata
"""
for host in self.cluster.metadata.all_hosts():
assert_startswith(host.release_version, CASSANDRA_VERSION.base_version)
@local
class MetaDataRemovalTest(unittest.TestCase):
def setUp(self):
self.cluster = TestCluster(contact_points=['127.0.0.1', '127.0.0.2', '127.0.0.3', '126.0.0.186'])
self.cluster.connect()
def tearDown(self):
self.cluster.shutdown()
def test_bad_contact_point(self):
"""
Checks to ensure that hosts that are not resolvable are excluded from the contact point list.
@since 3.6
@jira_ticket PYTHON-549
@expected_result Invalid hosts on the contact list should be excluded
@test_category metadata
"""
self.assertEqual(len(self.cluster.metadata.all_hosts()), 3)
class SchemaMetadataTests(BasicSegregatedKeyspaceUnitTestCase):
def test_schema_metadata_disable(self):
"""
Checks to ensure that schema metadata_enabled, and token_metadata_enabled
flags work correctly.
@since 3.3
@jira_ticket PYTHON-327
@expected_result schema metadata will not be populated when schema_metadata_enabled is fause
token_metadata will be missing when token_metadata is set to false
@test_category metadata
"""
# Validate metadata is missing where appropriate
no_schema = TestCluster(schema_metadata_enabled=False)
no_schema_session = no_schema.connect()
self.assertEqual(len(no_schema.metadata.keyspaces), 0)
self.assertEqual(no_schema.metadata.export_schema_as_string(), '')
no_token = TestCluster(token_metadata_enabled=False)
no_token_session = no_token.connect()
self.assertEqual(len(no_token.metadata.token_map.token_to_host_owner), 0)
# Do a simple query to ensure queries are working
query = "SELECT * FROM system.local"
no_schema_rs = no_schema_session.execute(query)
no_token_rs = no_token_session.execute(query)
self.assertIsNotNone(no_schema_rs[0])
self.assertIsNotNone(no_token_rs[0])
no_schema.shutdown()
no_token.shutdown()
def make_create_statement(self, partition_cols, clustering_cols=None, other_cols=None):
clustering_cols = clustering_cols or []
other_cols = other_cols or []
statement = "CREATE TABLE %s.%s (" % (self.keyspace_name, self.function_table_name)
if len(partition_cols) == 1 and not clustering_cols:
statement += "%s text PRIMARY KEY, " % protect_name(partition_cols[0])
else:
statement += ", ".join("%s text" % protect_name(col) for col in partition_cols)
statement += ", "
statement += ", ".join("%s text" % protect_name(col) for col in clustering_cols + other_cols)
if len(partition_cols) != 1 or clustering_cols:
statement += ", PRIMARY KEY ("
if len(partition_cols) > 1:
statement += "(" + ", ".join(protect_names(partition_cols)) + ")"
else:
statement += protect_name(partition_cols[0])
if clustering_cols:
statement += ", "
statement += ", ".join(protect_names(clustering_cols))
statement += ")"
statement += ")"
return statement
def check_create_statement(self, tablemeta, original):
recreate = tablemeta.as_cql_query(formatted=False)
self.assertEqual(original, recreate[:len(original)])
execute_until_pass(self.session, "DROP TABLE {0}.{1}".format(self.keyspace_name, self.function_table_name))
execute_until_pass(self.session, recreate)
# create the table again, but with formatting enabled
execute_until_pass(self.session, "DROP TABLE {0}.{1}".format(self.keyspace_name, self.function_table_name))
recreate = tablemeta.as_cql_query(formatted=True)
execute_until_pass(self.session, recreate)
def get_table_metadata(self):
self.cluster.refresh_table_metadata(self.keyspace_name, self.function_table_name)
return self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name]
def test_basic_table_meta_properties(self):
create_statement = self.make_create_statement(["a"], [], ["b", "c"])
self.session.execute(create_statement)
self.cluster.refresh_schema_metadata()
meta = self.cluster.metadata
self.assertNotEqual(meta.cluster_name, None)
self.assertTrue(self.keyspace_name in meta.keyspaces)
ksmeta = meta.keyspaces[self.keyspace_name]
self.assertEqual(ksmeta.name, self.keyspace_name)
self.assertTrue(ksmeta.durable_writes)
self.assertEqual(ksmeta.replication_strategy.name, 'SimpleStrategy')
self.assertEqual(ksmeta.replication_strategy.replication_factor, 1)
self.assertTrue(self.function_table_name in ksmeta.tables)
tablemeta = ksmeta.tables[self.function_table_name]
self.assertEqual(tablemeta.keyspace_name, ksmeta.name)
self.assertEqual(tablemeta.name, self.function_table_name)
self.assertEqual(tablemeta.name, self.function_table_name)
self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key])
self.assertEqual([], tablemeta.clustering_key)
self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys()))
cc = self.cluster.control_connection._connection
parser = get_schema_parser(
cc,
self.cluster.metadata.get_host(cc.host).release_version,
self.cluster.metadata.get_host(cc.host).dse_version,
1
)
for option in tablemeta.options:
self.assertIn(option, parser.recognized_table_options)
self.check_create_statement(tablemeta, create_statement)
def test_compound_primary_keys(self):
create_statement = self.make_create_statement(["a"], ["b"], ["c"])
create_statement += " WITH CLUSTERING ORDER BY (b ASC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key])
self.assertEqual([u'b'], [c.name for c in tablemeta.clustering_key])
self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
def test_compound_primary_keys_protected(self):
create_statement = self.make_create_statement(["Aa"], ["Bb"], ["Cc"])
create_statement += ' WITH CLUSTERING ORDER BY ("Bb" ASC)'
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'Aa'], [c.name for c in tablemeta.partition_key])
self.assertEqual([u'Bb'], [c.name for c in tablemeta.clustering_key])
self.assertEqual([u'Aa', u'Bb', u'Cc'], sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
def test_compound_primary_keys_more_columns(self):
create_statement = self.make_create_statement(["a"], ["b", "c"], ["d", "e", "f"])
create_statement += " WITH CLUSTERING ORDER BY (b ASC, c ASC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key])
self.assertEqual([u'b', u'c'], [c.name for c in tablemeta.clustering_key])
self.assertEqual(
[u'a', u'b', u'c', u'd', u'e', u'f'],
sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
def test_composite_primary_key(self):
create_statement = self.make_create_statement(["a", "b"], [], ["c"])
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a', u'b'], [c.name for c in tablemeta.partition_key])
self.assertEqual([], tablemeta.clustering_key)
self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
def test_composite_in_compound_primary_key(self):
create_statement = self.make_create_statement(["a", "b"], ["c"], ["d", "e"])
create_statement += " WITH CLUSTERING ORDER BY (c ASC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a', u'b'], [c.name for c in tablemeta.partition_key])
self.assertEqual([u'c'], [c.name for c in tablemeta.clustering_key])
self.assertEqual([u'a', u'b', u'c', u'd', u'e'], sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
def test_compound_primary_keys_compact(self):
create_statement = self.make_create_statement(["a"], ["b"], ["c"])
create_statement += " WITH CLUSTERING ORDER BY (b ASC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key])
self.assertEqual([u'b'], [c.name for c in tablemeta.clustering_key])
self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
def test_cluster_column_ordering_reversed_metadata(self):
"""
Simple test to ensure that the metatdata associated with cluster ordering is surfaced is surfaced correctly.
Creates a table with a few clustering keys. Then checks the clustering order associated with clustering columns
and ensure it's set correctly.
@since 3.0.0
@jira_ticket PYTHON-402
@expected_result is_reversed is set on DESC order, and is False on ASC
@test_category metadata
"""
create_statement = self.make_create_statement(["a"], ["b", "c"], ["d"])
create_statement += " WITH CLUSTERING ORDER BY (b ASC, c DESC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
b_column = tablemeta.columns['b']
self.assertFalse(b_column.is_reversed)
c_column = tablemeta.columns['c']
self.assertTrue(c_column.is_reversed)
def test_compound_primary_keys_more_columns_compact(self):
create_statement = self.make_create_statement(["a"], ["b", "c"], ["d"])
create_statement += " WITH CLUSTERING ORDER BY (b ASC, c ASC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key])
self.assertEqual([u'b', u'c'], [c.name for c in tablemeta.clustering_key])
self.assertEqual([u'a', u'b', u'c', u'd'], sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
def test_composite_primary_key_compact(self):
create_statement = self.make_create_statement(["a", "b"], [], ["c"])
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a', u'b'], [c.name for c in tablemeta.partition_key])
self.assertEqual([], tablemeta.clustering_key)
self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
def test_composite_in_compound_primary_key_compact(self):
create_statement = self.make_create_statement(["a", "b"], ["c"], ["d"])
create_statement += " WITH CLUSTERING ORDER BY (c ASC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a', u'b'], [c.name for c in tablemeta.partition_key])
self.assertEqual([u'c'], [c.name for c in tablemeta.clustering_key])
self.assertEqual([u'a', u'b', u'c', u'd'], sorted(tablemeta.columns.keys()))
self.check_create_statement(tablemeta, create_statement)
@lessthancass30
def test_cql_compatibility(self):
# having more than one non-PK column is okay if there aren't any
# clustering columns
create_statement = self.make_create_statement(["a"], [], ["b", "c", "d"])
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key])
self.assertEqual([], tablemeta.clustering_key)
self.assertEqual([u'a', u'b', u'c', u'd'], sorted(tablemeta.columns.keys()))
self.assertTrue(tablemeta.is_cql_compatible)
# It will be cql compatible after CASSANDRA-10857
# since compact storage is being dropped
tablemeta.clustering_key = ["foo", "bar"]
tablemeta.columns["foo"] = None
tablemeta.columns["bar"] = None
self.assertTrue(tablemeta.is_cql_compatible)
def test_compound_primary_keys_ordering(self):
create_statement = self.make_create_statement(["a"], ["b"], ["c"])
create_statement += " WITH CLUSTERING ORDER BY (b DESC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.check_create_statement(tablemeta, create_statement)
def test_compound_primary_keys_more_columns_ordering(self):
create_statement = self.make_create_statement(["a"], ["b", "c"], ["d", "e", "f"])
create_statement += " WITH CLUSTERING ORDER BY (b DESC, c ASC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.check_create_statement(tablemeta, create_statement)
def test_composite_in_compound_primary_key_ordering(self):
create_statement = self.make_create_statement(["a", "b"], ["c"], ["d", "e"])
create_statement += " WITH CLUSTERING ORDER BY (c DESC)"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.check_create_statement(tablemeta, create_statement)
@lessthancass40
def test_compact_storage(self):
create_statement = self.make_create_statement(["a"], [], ["b"])
create_statement += " WITH COMPACT STORAGE"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.check_create_statement(tablemeta, create_statement)
@lessthancass40
def test_dense_compact_storage(self):
create_statement = self.make_create_statement(["a"], ["b"], ["c"])
create_statement += " WITH COMPACT STORAGE"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.check_create_statement(tablemeta, create_statement)
def test_counter(self):
create_statement = (
"CREATE TABLE {keyspace}.{table} ("
"key text PRIMARY KEY, a1 counter)"
).format(keyspace=self.keyspace_name, table=self.function_table_name)
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.check_create_statement(tablemeta, create_statement)
@lessthancass40
def test_counter_with_compact_storage(self):
""" PYTHON-1100 """
create_statement = (
"CREATE TABLE {keyspace}.{table} ("
"key text PRIMARY KEY, a1 counter) WITH COMPACT STORAGE"
).format(keyspace=self.keyspace_name, table=self.function_table_name)
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.check_create_statement(tablemeta, create_statement)
@lessthancass40
def test_counter_with_dense_compact_storage(self):
create_statement = (
"CREATE TABLE {keyspace}.{table} ("
"key text, c1 text, a1 counter, PRIMARY KEY (key, c1)) WITH COMPACT STORAGE"
).format(keyspace=self.keyspace_name, table=self.function_table_name)
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
self.check_create_statement(tablemeta, create_statement)
def test_indexes(self):
create_statement = self.make_create_statement(["a"], ["b", "c"], ["d", "e", "f"])
create_statement += " WITH CLUSTERING ORDER BY (b ASC, c ASC)"
execute_until_pass(self.session, create_statement)
d_index = "CREATE INDEX d_index ON %s.%s (d)" % (self.keyspace_name, self.function_table_name)
e_index = "CREATE INDEX e_index ON %s.%s (e)" % (self.keyspace_name, self.function_table_name)
execute_until_pass(self.session, d_index)
execute_until_pass(self.session, e_index)
tablemeta = self.get_table_metadata()
statements = tablemeta.export_as_string().strip()
statements = [s.strip() for s in statements.split(';')]
statements = list(filter(bool, statements))
self.assertEqual(3, len(statements))
self.assertIn(d_index, statements)
self.assertIn(e_index, statements)
# make sure indexes are included in KeyspaceMetadata.export_as_string()
ksmeta = self.cluster.metadata.keyspaces[self.keyspace_name]
statement = ksmeta.export_as_string()
self.assertIn('CREATE INDEX d_index', statement)
self.assertIn('CREATE INDEX e_index', statement)
@greaterthancass21
def test_collection_indexes(self):
self.session.execute("CREATE TABLE %s.%s (a int PRIMARY KEY, b map<text, text>)"
% (self.keyspace_name, self.function_table_name))
self.session.execute("CREATE INDEX index1 ON %s.%s (keys(b))"
% (self.keyspace_name, self.function_table_name))
tablemeta = self.get_table_metadata()
self.assertIn('(keys(b))', tablemeta.export_as_string())
self.session.execute("DROP INDEX %s.index1" % (self.keyspace_name,))
self.session.execute("CREATE INDEX index2 ON %s.%s (b)"
% (self.keyspace_name, self.function_table_name))
tablemeta = self.get_table_metadata()
target = ' (b)' if CASSANDRA_VERSION < Version("3.0") else 'values(b))' # explicit values in C* 3+
self.assertIn(target, tablemeta.export_as_string())
# test full indexes on frozen collections, if available
if CASSANDRA_VERSION >= Version("2.1.3"):
self.session.execute("DROP TABLE %s.%s" % (self.keyspace_name, self.function_table_name))
self.session.execute("CREATE TABLE %s.%s (a int PRIMARY KEY, b frozen<map<text, text>>)"
% (self.keyspace_name, self.function_table_name))
self.session.execute("CREATE INDEX index3 ON %s.%s (full(b))"
% (self.keyspace_name, self.function_table_name))
tablemeta = self.get_table_metadata()
self.assertIn('(full(b))', tablemeta.export_as_string())
def test_compression_disabled(self):
create_statement = self.make_create_statement(["a"], ["b"], ["c"])
create_statement += " WITH compression = {}"
self.session.execute(create_statement)
tablemeta = self.get_table_metadata()
expected = "compression = {}" if CASSANDRA_VERSION < Version("3.0") else "compression = {'enabled': 'false'}"
self.assertIn(expected, tablemeta.export_as_string())
def test_non_size_tiered_compaction(self):
"""
test options for non-size-tiered compaction strategy
Creates a table with LeveledCompactionStrategy, specifying one non-default option. Verifies that the option is
present in generated CQL, and that other legacy table parameters (min_threshold, max_threshold) are not included.
@since 2.6.0
@jira_ticket PYTHON-352
@expected_result the options map for LeveledCompactionStrategy does not contain min_threshold, max_threshold
@test_category metadata
"""
create_statement = self.make_create_statement(["a"], [], ["b", "c"])
create_statement += "WITH COMPACTION = {'class': 'LeveledCompactionStrategy', 'tombstone_threshold': '0.3'}"
self.session.execute(create_statement)
table_meta = self.get_table_metadata()
cql = table_meta.export_as_string()
self.assertIn("'tombstone_threshold': '0.3'", cql)
self.assertIn("LeveledCompactionStrategy", cql)
# formerly legacy options; reintroduced in 4.0
if CASSANDRA_VERSION < Version('4.0-a'):
self.assertNotIn("min_threshold", cql)
self.assertNotIn("max_threshold", cql)
def test_refresh_schema_metadata(self):
"""
test for synchronously refreshing all cluster metadata
test_refresh_schema_metadata tests all cluster metadata is refreshed when calling refresh_schema_metadata().
It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled
for schema change push events. It then alters the cluster, creating a new keyspace, using the first cluster
object, and verifies that the cluster metadata has not changed in the second cluster object. It then calls
refresh_schema_metadata() and verifies that the cluster metadata is updated in the second cluster object.
Similarly, it then proceeds to altering keyspace, table, UDT, UDF, and UDA metadata and subsequently verfies
that these metadata is updated when refresh_schema_metadata() is called.
@since 2.6.0
@jira_ticket PYTHON-291
@expected_result Cluster, keyspace, table, UDT, UDF, and UDA metadata should be refreshed when refresh_schema_metadata() is called.
@test_category metadata
"""
cluster2 = TestCluster(schema_event_refresh_window=-1)
cluster2.connect()
self.assertNotIn("new_keyspace", cluster2.metadata.keyspaces)
# Cluster metadata modification
self.session.execute("CREATE KEYSPACE new_keyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}")
self.assertNotIn("new_keyspace", cluster2.metadata.keyspaces)
cluster2.refresh_schema_metadata()
self.assertIn("new_keyspace", cluster2.metadata.keyspaces)
# Keyspace metadata modification
self.session.execute("ALTER KEYSPACE {0} WITH durable_writes = false".format(self.keyspace_name))
self.assertTrue(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes)
cluster2.refresh_schema_metadata()
self.assertFalse(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes)
# Table metadata modification
table_name = "test"
self.session.execute("CREATE TABLE {0}.{1} (a int PRIMARY KEY, b text)".format(self.keyspace_name, table_name))
cluster2.refresh_schema_metadata()
self.session.execute("ALTER TABLE {0}.{1} ADD c double".format(self.keyspace_name, table_name))
self.assertNotIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns)
cluster2.refresh_schema_metadata()
self.assertIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns)
if PROTOCOL_VERSION >= 3:
# UDT metadata modification
self.session.execute("CREATE TYPE {0}.user (age int, name text)".format(self.keyspace_name))
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].user_types, {})
cluster2.refresh_schema_metadata()
self.assertIn("user", cluster2.metadata.keyspaces[self.keyspace_name].user_types)
if PROTOCOL_VERSION >= 4:
# UDF metadata modification
self.session.execute("""CREATE FUNCTION {0}.sum_int(key int, val int)
RETURNS NULL ON NULL INPUT
RETURNS int
LANGUAGE java AS 'return key+val;';""".format(self.keyspace_name))
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].functions, {})
cluster2.refresh_schema_metadata()
self.assertIn("sum_int(int,int)", cluster2.metadata.keyspaces[self.keyspace_name].functions)
# UDA metadata modification
self.session.execute("""CREATE AGGREGATE {0}.sum_agg(int)
SFUNC sum_int
STYPE int
INITCOND 0"""
.format(self.keyspace_name))
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].aggregates, {})
cluster2.refresh_schema_metadata()
self.assertIn("sum_agg(int)", cluster2.metadata.keyspaces[self.keyspace_name].aggregates)
# Cluster metadata modification
self.session.execute("DROP KEYSPACE new_keyspace")
self.assertIn("new_keyspace", cluster2.metadata.keyspaces)
cluster2.refresh_schema_metadata()
self.assertNotIn("new_keyspace", cluster2.metadata.keyspaces)
cluster2.shutdown()
def test_refresh_keyspace_metadata(self):
"""
test for synchronously refreshing keyspace metadata
test_refresh_keyspace_metadata tests that keyspace metadata is refreshed when calling refresh_keyspace_metadata().
It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled
for schema change push events. It then alters the keyspace, disabling durable_writes, using the first cluster
object, and verifies that the keyspace metadata has not changed in the second cluster object. Finally, it calls
refresh_keyspace_metadata() and verifies that the keyspace metadata is updated in the second cluster object.
@since 2.6.0
@jira_ticket PYTHON-291
@expected_result Keyspace metadata should be refreshed when refresh_keyspace_metadata() is called.
@test_category metadata
"""
cluster2 = TestCluster(schema_event_refresh_window=-1)
cluster2.connect()
self.assertTrue(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes)
self.session.execute("ALTER KEYSPACE {0} WITH durable_writes = false".format(self.keyspace_name))
self.assertTrue(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes)
cluster2.refresh_keyspace_metadata(self.keyspace_name)
self.assertFalse(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes)
cluster2.shutdown()
def test_refresh_table_metadata(self):
"""
test for synchronously refreshing table metadata
test_refresh_table_metatadata tests that table metadata is refreshed when calling test_refresh_table_metatadata().
It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled
for schema change push events. It then alters the table, adding a new column, using the first cluster
object, and verifies that the table metadata has not changed in the second cluster object. Finally, it calls
test_refresh_table_metatadata() and verifies that the table metadata is updated in the second cluster object.
@since 2.6.0
@jira_ticket PYTHON-291
@expected_result Table metadata should be refreshed when refresh_table_metadata() is called.
@test_category metadata
"""
table_name = "test"
self.session.execute("CREATE TABLE {0}.{1} (a int PRIMARY KEY, b text)".format(self.keyspace_name, table_name))
cluster2 = TestCluster(schema_event_refresh_window=-1)
cluster2.connect()
self.assertNotIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns)
self.session.execute("ALTER TABLE {0}.{1} ADD c double".format(self.keyspace_name, table_name))
self.assertNotIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns)
cluster2.refresh_table_metadata(self.keyspace_name, table_name)
self.assertIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns)
cluster2.shutdown()
@greaterthanorequalcass30
def test_refresh_metadata_for_mv(self):
"""
test for synchronously refreshing materialized view metadata
test_refresh_table_metadata_for_materialized_views tests that materialized view metadata is refreshed when calling
test_refresh_table_metatadata() with the materialized view name as the table. It creates a second cluster object
with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events.
It then creates a new materialized view , using the first cluster object, and verifies that the materialized view
metadata has not changed in the second cluster object. Finally, it calls test_refresh_table_metatadata() with the
materialized view name as the table name, and verifies that the materialized view metadata is updated in the
second cluster object.
@since 3.0.0
@jira_ticket PYTHON-371
@expected_result Materialized view metadata should be refreshed when refresh_table_metadata() is called.
@test_category metadata
"""
self.session.execute("CREATE TABLE {0}.{1} (a int PRIMARY KEY, b text)".format(self.keyspace_name, self.function_table_name))
cluster2 = TestCluster(schema_event_refresh_window=-1)
cluster2.connect()
try:
self.assertNotIn("mv1", cluster2.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
self.session.execute("CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT a, b FROM {0}.{1} "
"WHERE a IS NOT NULL AND b IS NOT NULL PRIMARY KEY (a, b)"
.format(self.keyspace_name, self.function_table_name))
self.assertNotIn("mv1", cluster2.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
cluster2.refresh_table_metadata(self.keyspace_name, "mv1")
self.assertIn("mv1", cluster2.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
finally:
cluster2.shutdown()
original_meta = self.cluster.metadata.keyspaces[self.keyspace_name].views['mv1']
self.assertIs(original_meta, self.session.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views['mv1'])
self.cluster.refresh_materialized_view_metadata(self.keyspace_name, 'mv1')
current_meta = self.cluster.metadata.keyspaces[self.keyspace_name].views['mv1']
self.assertIsNot(current_meta, original_meta)
self.assertIsNot(original_meta, self.session.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views['mv1'])
self.assertEqual(original_meta.as_cql_query(), current_meta.as_cql_query())
cluster3 = TestCluster(schema_event_refresh_window=-1)
cluster3.connect()
try:
self.assertNotIn("mv2", cluster3.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
self.session.execute(
"CREATE MATERIALIZED VIEW {0}.mv2 AS SELECT a, b FROM {0}.{1} "
"WHERE a IS NOT NULL AND b IS NOT NULL PRIMARY KEY (a, b)".format(
self.keyspace_name, self.function_table_name)
)
self.assertNotIn("mv2", cluster3.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
cluster3.refresh_materialized_view_metadata(self.keyspace_name, 'mv2')
self.assertIn("mv2", cluster3.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
finally:
cluster3.shutdown()
def test_refresh_user_type_metadata(self):
"""
test for synchronously refreshing UDT metadata in keyspace
test_refresh_user_type_metadata tests that UDT metadata in a keyspace is refreshed when calling refresh_user_type_metadata().
It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled
for schema change push events. It then alters the keyspace, creating a new UDT, using the first cluster
object, and verifies that the UDT metadata has not changed in the second cluster object. Finally, it calls
refresh_user_type_metadata() and verifies that the UDT metadata in the keyspace is updated in the second cluster object.
@since 2.6.0
@jira_ticket PYTHON-291
@expected_result UDT metadata in the keyspace should be refreshed when refresh_user_type_metadata() is called.
@test_category metadata
"""
if PROTOCOL_VERSION < 3:
raise unittest.SkipTest("Protocol 3+ is required for UDTs, currently testing against {0}".format(PROTOCOL_VERSION))
cluster2 = TestCluster(schema_event_refresh_window=-1)
cluster2.connect()
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].user_types, {})
self.session.execute("CREATE TYPE {0}.user (age int, name text)".format(self.keyspace_name))
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].user_types, {})
cluster2.refresh_user_type_metadata(self.keyspace_name, "user")
self.assertIn("user", cluster2.metadata.keyspaces[self.keyspace_name].user_types)
cluster2.shutdown()
@greaterthancass20
def test_refresh_user_type_metadata_proto_2(self):
"""
Test to insure that protocol v1/v2 surface UDT metadata changes
@since 3.7.0
@jira_ticket PYTHON-106
@expected_result UDT metadata in the keyspace should be updated regardless of protocol version
@test_category metadata
"""
supported_versions = get_supported_protocol_versions()
if 2 not in supported_versions: # 1 and 2 were dropped in the same version
raise unittest.SkipTest("Protocol versions 1 and 2 are not supported in Cassandra version ".format(CASSANDRA_VERSION))
for protocol_version in (1, 2):
cluster = TestCluster()
session = cluster.connect()
self.assertEqual(cluster.metadata.keyspaces[self.keyspace_name].user_types, {})
session.execute("CREATE TYPE {0}.user (age int, name text)".format(self.keyspace_name))
self.assertIn("user", cluster.metadata.keyspaces[self.keyspace_name].user_types)
self.assertIn("age", cluster.metadata.keyspaces[self.keyspace_name].user_types["user"].field_names)
self.assertIn("name", cluster.metadata.keyspaces[self.keyspace_name].user_types["user"].field_names)
session.execute("ALTER TYPE {0}.user ADD flag boolean".format(self.keyspace_name))
self.assertIn("flag", cluster.metadata.keyspaces[self.keyspace_name].user_types["user"].field_names)
session.execute("ALTER TYPE {0}.user RENAME flag TO something".format(self.keyspace_name))
self.assertIn("something", cluster.metadata.keyspaces[self.keyspace_name].user_types["user"].field_names)
session.execute("DROP TYPE {0}.user".format(self.keyspace_name))
self.assertEqual(cluster.metadata.keyspaces[self.keyspace_name].user_types, {})
cluster.shutdown()
def test_refresh_user_function_metadata(self):
"""
test for synchronously refreshing UDF metadata in keyspace
test_refresh_user_function_metadata tests that UDF metadata in a keyspace is refreshed when calling
refresh_user_function_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such
that schema refreshes are disabled for schema change push events. It then alters the keyspace, creating a new
UDF, using the first cluster object, and verifies that the UDF metadata has not changed in the second cluster
object. Finally, it calls refresh_user_function_metadata() and verifies that the UDF metadata in the keyspace
is updated in the second cluster object.
@since 2.6.0
@jira_ticket PYTHON-291
@expected_result UDF metadata in the keyspace should be refreshed when refresh_user_function_metadata() is called.
@test_category metadata
"""
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest("Protocol 4+ is required for UDFs, currently testing against {0}".format(PROTOCOL_VERSION))
cluster2 = TestCluster(schema_event_refresh_window=-1)
cluster2.connect()
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].functions, {})
self.session.execute("""CREATE FUNCTION {0}.sum_int(key int, val int)
RETURNS NULL ON NULL INPUT
RETURNS int
LANGUAGE java AS ' return key + val;';""".format(self.keyspace_name))
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].functions, {})
cluster2.refresh_user_function_metadata(self.keyspace_name, UserFunctionDescriptor("sum_int", ["int", "int"]))
self.assertIn("sum_int(int,int)", cluster2.metadata.keyspaces[self.keyspace_name].functions)
cluster2.shutdown()
def test_refresh_user_aggregate_metadata(self):
"""
test for synchronously refreshing UDA metadata in keyspace
test_refresh_user_aggregate_metadata tests that UDA metadata in a keyspace is refreshed when calling
refresh_user_aggregate_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such
that schema refreshes are disabled for schema change push events. It then alters the keyspace, creating a new
UDA, using the first cluster object, and verifies that the UDA metadata has not changed in the second cluster
object. Finally, it calls refresh_user_aggregate_metadata() and verifies that the UDF metadata in the keyspace
is updated in the second cluster object.
@since 2.6.0
@jira_ticket PYTHON-291
@expected_result UDA metadata in the keyspace should be refreshed when refresh_user_aggregate_metadata() is called.
@test_category metadata
"""
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest("Protocol 4+ is required for UDAs, currently testing against {0}".format(PROTOCOL_VERSION))
cluster2 = TestCluster(schema_event_refresh_window=-1)
cluster2.connect()
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].aggregates, {})
self.session.execute("""CREATE FUNCTION {0}.sum_int(key int, val int)
RETURNS NULL ON NULL INPUT
RETURNS int
LANGUAGE java AS 'return key + val;';""".format(self.keyspace_name))
self.session.execute("""CREATE AGGREGATE {0}.sum_agg(int)
SFUNC sum_int
STYPE int
INITCOND 0"""
.format(self.keyspace_name))
self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].aggregates, {})
cluster2.refresh_user_aggregate_metadata(self.keyspace_name, UserAggregateDescriptor("sum_agg", ["int"]))
self.assertIn("sum_agg(int)", cluster2.metadata.keyspaces[self.keyspace_name].aggregates)
cluster2.shutdown()
@greaterthanorequalcass30
def test_multiple_indices(self):
"""
test multiple indices on the same column.
Creates a table and two indices. Ensures that both indices metatdata is surface appropriately.
@since 3.0.0
@jira_ticket PYTHON-276
@expected_result IndexMetadata is appropriately surfaced
@test_category metadata
"""
self.session.execute("CREATE TABLE {0}.{1} (a int PRIMARY KEY, b map<text, int>)".format(self.keyspace_name, self.function_table_name))
self.session.execute("CREATE INDEX index_1 ON {0}.{1}(b)".format(self.keyspace_name, self.function_table_name))
self.session.execute("CREATE INDEX index_2 ON {0}.{1}(keys(b))".format(self.keyspace_name, self.function_table_name))
indices = self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].indexes
self.assertEqual(len(indices), 2)
index_1 = indices["index_1"]
index_2 = indices['index_2']
self.assertEqual(index_1.table_name, "test_multiple_indices")
self.assertEqual(index_1.name, "index_1")
self.assertEqual(index_1.kind, "COMPOSITES")
self.assertEqual(index_1.index_options["target"], "values(b)")
self.assertEqual(index_1.keyspace_name, "schemametadatatests")
self.assertEqual(index_2.table_name, "test_multiple_indices")
self.assertEqual(index_2.name, "index_2")
self.assertEqual(index_2.kind, "COMPOSITES")
self.assertEqual(index_2.index_options["target"], "keys(b)")
self.assertEqual(index_2.keyspace_name, "schemametadatatests")
@greaterthanorequalcass30
def test_table_extensions(self):
s = self.session
ks = self.keyspace_name
ks_meta = s.cluster.metadata.keyspaces[ks]
t = self.function_table_name
v = t + 'view'
s.execute("CREATE TABLE %s.%s (k text PRIMARY KEY, v int)" % (ks, t))
s.execute(
"CREATE MATERIALIZED VIEW %s.%s AS SELECT * FROM %s.%s "
"WHERE v IS NOT NULL AND k IS NOT NULL PRIMARY KEY (v, k)" % (ks, v, ks, t)
)
table_meta = ks_meta.tables[t]
view_meta = table_meta.views[v]
self.assertFalse(table_meta.extensions)
self.assertFalse(view_meta.extensions)
original_table_cql = table_meta.export_as_string()
original_view_cql = view_meta.export_as_string()
# extensions registered, not present
# --------------------------------------
class Ext0(RegisteredTableExtension):
name = t
@classmethod
def after_table_cql(cls, table_meta, ext_key, ext_blob):
return "%s %s %s %s" % (cls.name, table_meta.name, ext_key, ext_blob)
class Ext1(Ext0):
name = t + '##'
self.assertFalse(table_meta.extensions)
self.assertFalse(view_meta.extensions)
self.assertIn(Ext0.name, _RegisteredExtensionType._extension_registry)
self.assertIn(Ext1.name, _RegisteredExtensionType._extension_registry)
# There will bee the RLAC extension here.
self.assertEqual(len(_RegisteredExtensionType._extension_registry), 3)
self.cluster.refresh_table_metadata(ks, t)
table_meta = ks_meta.tables[t]
view_meta = table_meta.views[v]
self.assertEqual(table_meta.export_as_string(), original_table_cql)
self.assertEqual(view_meta.export_as_string(), original_view_cql)
update_t = s.prepare('UPDATE system_schema.tables SET extensions=? WHERE keyspace_name=? AND table_name=?') # for blob type coercing
update_v = s.prepare('UPDATE system_schema.views SET extensions=? WHERE keyspace_name=? AND view_name=?')
# extensions registered, one present
# --------------------------------------
ext_map = {Ext0.name: six.b("THA VALUE")}
[(s.execute(update_t, (ext_map, ks, t)), s.execute(update_v, (ext_map, ks, v)))
for _ in self.cluster.metadata.all_hosts()] # we're manipulating metadata - do it on all hosts
self.cluster.refresh_table_metadata(ks, t)
self.cluster.refresh_materialized_view_metadata(ks, v)
table_meta = ks_meta.tables[t]
view_meta = table_meta.views[v]
self.assertIn(Ext0.name, table_meta.extensions)
new_cql = table_meta.export_as_string()
self.assertNotEqual(new_cql, original_table_cql)
self.assertIn(Ext0.after_table_cql(table_meta, Ext0.name, ext_map[Ext0.name]), new_cql)
self.assertNotIn(Ext1.name, new_cql)
self.assertIn(Ext0.name, view_meta.extensions)
new_cql = view_meta.export_as_string()
self.assertNotEqual(new_cql, original_view_cql)
self.assertIn(Ext0.after_table_cql(view_meta, Ext0.name, ext_map[Ext0.name]), new_cql)
self.assertNotIn(Ext1.name, new_cql)
# extensions registered, one present
# --------------------------------------
ext_map = {Ext0.name: six.b("THA VALUE"),
Ext1.name: six.b("OTHA VALUE")}
[(s.execute(update_t, (ext_map, ks, t)), s.execute(update_v, (ext_map, ks, v)))
for _ in self.cluster.metadata.all_hosts()] # we're manipulating metadata - do it on all hosts
self.cluster.refresh_table_metadata(ks, t)
self.cluster.refresh_materialized_view_metadata(ks, v)
table_meta = ks_meta.tables[t]
view_meta = table_meta.views[v]
self.assertIn(Ext0.name, table_meta.extensions)
self.assertIn(Ext1.name, table_meta.extensions)
new_cql = table_meta.export_as_string()
self.assertNotEqual(new_cql, original_table_cql)
self.assertIn(Ext0.after_table_cql(table_meta, Ext0.name, ext_map[Ext0.name]), new_cql)
self.assertIn(Ext1.after_table_cql(table_meta, Ext1.name, ext_map[Ext1.name]), new_cql)
self.assertIn(Ext0.name, view_meta.extensions)
self.assertIn(Ext1.name, view_meta.extensions)
new_cql = view_meta.export_as_string()
self.assertNotEqual(new_cql, original_view_cql)
self.assertIn(Ext0.after_table_cql(view_meta, Ext0.name, ext_map[Ext0.name]), new_cql)
self.assertIn(Ext1.after_table_cql(view_meta, Ext1.name, ext_map[Ext1.name]), new_cql)
class TestCodeCoverage(unittest.TestCase):
def test_export_schema(self):
"""
Test export schema functionality
"""
cluster = TestCluster()
cluster.connect()
self.assertIsInstance(cluster.metadata.export_schema_as_string(), six.string_types)
cluster.shutdown()
def test_export_keyspace_schema(self):
"""
Test export keyspace schema functionality
"""
cluster = TestCluster()
cluster.connect()
for keyspace in cluster.metadata.keyspaces:
keyspace_metadata = cluster.metadata.keyspaces[keyspace]
self.assertIsInstance(keyspace_metadata.export_as_string(), six.string_types)
self.assertIsInstance(keyspace_metadata.as_cql_query(), six.string_types)
cluster.shutdown()
def assert_equal_diff(self, received, expected):
if received != expected:
diff_string = '\n'.join(difflib.unified_diff(expected.split('\n'),
received.split('\n'),
'EXPECTED', 'RECEIVED',
lineterm=''))
self.fail(diff_string)
def assert_startswith_diff(self, received, prefix):
if not received.startswith(prefix):
prefix_lines = prefix.split('\n')
diff_string = '\n'.join(difflib.unified_diff(prefix_lines,
received.split('\n')[:len(prefix_lines)],
'EXPECTED', 'RECEIVED',
lineterm=''))
self.fail(diff_string)
@greaterthancass20
def test_export_keyspace_schema_udts(self):
"""
Test udt exports
"""
if PROTOCOL_VERSION < 3:
raise unittest.SkipTest(
"Protocol 3.0+ is required for UDT change events, currently testing against %r"
% (PROTOCOL_VERSION,))
if sys.version_info[0:2] != (2, 7):
raise unittest.SkipTest('This test compares static strings generated from dict items, which may change orders. Test with 2.7.')
cluster = TestCluster()
session = cluster.connect()
session.execute("""
CREATE KEYSPACE export_udts
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
AND durable_writes = true;
""")
session.execute("""
CREATE TYPE export_udts.street (
street_number int,
street_name text)
""")
session.execute("""
CREATE TYPE export_udts.zip (
zipcode int,
zip_plus_4 int)
""")
session.execute("""
CREATE TYPE export_udts.address (
street_address frozen<street>,
zip_code frozen<zip>)
""")
session.execute("""
CREATE TABLE export_udts.users (
user text PRIMARY KEY,
addresses map<text, frozen<address>>)
""")
expected_prefix = """CREATE KEYSPACE export_udts WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true;
CREATE TYPE export_udts.street (
street_number int,
street_name text
);
CREATE TYPE export_udts.zip (
zipcode int,
zip_plus_4 int
);
CREATE TYPE export_udts.address (
street_address frozen<street>,
zip_code frozen<zip>
);
CREATE TABLE export_udts.users (
user text PRIMARY KEY,
addresses map<text, frozen<address>>"""
self.assert_startswith_diff(cluster.metadata.keyspaces['export_udts'].export_as_string(), expected_prefix)
table_meta = cluster.metadata.keyspaces['export_udts'].tables['users']
expected_prefix = """CREATE TABLE export_udts.users (
user text PRIMARY KEY,
addresses map<text, frozen<address>>"""
self.assert_startswith_diff(table_meta.export_as_string(), expected_prefix)
cluster.shutdown()
@greaterthancass21
def test_case_sensitivity(self):
"""
Test that names that need to be escaped in CREATE statements are
"""
cluster = TestCluster()
session = cluster.connect()
ksname = 'AnInterestingKeyspace'
cfname = 'AnInterestingTable'
session.execute("DROP KEYSPACE IF EXISTS {0}".format(ksname))
session.execute("""
CREATE KEYSPACE "%s"
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
""" % (ksname,))
session.execute("""
CREATE TABLE "%s"."%s" (
k int,
"A" int,
"B" int,
"MyColumn" int,
PRIMARY KEY (k, "A"))
WITH CLUSTERING ORDER BY ("A" DESC)
""" % (ksname, cfname))
session.execute("""
CREATE INDEX myindex ON "%s"."%s" ("MyColumn")
""" % (ksname, cfname))
session.execute("""
CREATE INDEX "AnotherIndex" ON "%s"."%s" ("B")
""" % (ksname, cfname))
ksmeta = cluster.metadata.keyspaces[ksname]
schema = ksmeta.export_as_string()
self.assertIn('CREATE KEYSPACE "AnInterestingKeyspace"', schema)
self.assertIn('CREATE TABLE "AnInterestingKeyspace"."AnInterestingTable"', schema)
self.assertIn('"A" int', schema)
self.assertIn('"B" int', schema)
self.assertIn('"MyColumn" int', schema)
self.assertIn('PRIMARY KEY (k, "A")', schema)
self.assertIn('WITH CLUSTERING ORDER BY ("A" DESC)', schema)
self.assertIn('CREATE INDEX myindex ON "AnInterestingKeyspace"."AnInterestingTable" ("MyColumn")', schema)
self.assertIn('CREATE INDEX "AnotherIndex" ON "AnInterestingKeyspace"."AnInterestingTable" ("B")', schema)
cluster.shutdown()
def test_already_exists_exceptions(self):
"""
Ensure AlreadyExists exception is thrown when hit
"""
cluster = TestCluster()
session = cluster.connect()
ksname = 'test3rf'
cfname = 'test'
ddl = '''
CREATE KEYSPACE %s
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'}'''
self.assertRaises(AlreadyExists, session.execute, ddl % ksname)
ddl = '''
CREATE TABLE %s.%s (
k int PRIMARY KEY,
v int )'''
self.assertRaises(AlreadyExists, session.execute, ddl % (ksname, cfname))
cluster.shutdown()
@local
def test_replicas(self):
"""
Ensure cluster.metadata.get_replicas return correctly when not attached to keyspace
"""
if murmur3 is None:
raise unittest.SkipTest('the murmur3 extension is not available')
cluster = TestCluster()
self.assertEqual(cluster.metadata.get_replicas('test3rf', 'key'), [])
cluster.connect('test3rf')
self.assertNotEqual(list(cluster.metadata.get_replicas('test3rf', six.b('key'))), [])
host = list(cluster.metadata.get_replicas('test3rf', six.b('key')))[0]
self.assertEqual(host.datacenter, 'dc1')
self.assertEqual(host.rack, 'r1')
cluster.shutdown()
def test_token_map(self):
"""
Test token mappings
"""
cluster = TestCluster()
cluster.connect('test3rf')
ring = cluster.metadata.token_map.ring
owners = list(cluster.metadata.token_map.token_to_host_owner[token] for token in ring)
get_replicas = cluster.metadata.token_map.get_replicas
for ksname in ('test1rf', 'test2rf', 'test3rf'):
self.assertNotEqual(list(get_replicas(ksname, ring[0])), [])
for i, token in enumerate(ring):
self.assertEqual(set(get_replicas('test3rf', token)), set(owners))
self.assertEqual(set(get_replicas('test2rf', token)), set([owners[i], owners[(i + 1) % 3]]))
self.assertEqual(set(get_replicas('test1rf', token)), set([owners[i]]))
cluster.shutdown()
class TokenMetadataTest(unittest.TestCase):
"""
Test of TokenMap creation and other behavior.
"""
@local
def test_token(self):
expected_node_count = len(get_cluster().nodes)
cluster = TestCluster()
cluster.connect()
tmap = cluster.metadata.token_map
self.assertTrue(issubclass(tmap.token_class, Token))
self.assertEqual(expected_node_count, len(tmap.ring))
cluster.shutdown()
class KeyspaceAlterMetadata(unittest.TestCase):
"""
Test verifies that table metadata is preserved on keyspace alter
"""
def setUp(self):
self.cluster = TestCluster()
self.session = self.cluster.connect()
name = self._testMethodName.lower()
crt_ks = '''
CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1} AND durable_writes = true''' % name
self.session.execute(crt_ks)
def tearDown(self):
name = self._testMethodName.lower()
self.session.execute('DROP KEYSPACE %s' % name)
self.cluster.shutdown()
def test_keyspace_alter(self):
"""
Table info is preserved upon keyspace alter:
Create table
Verify schema
Alter ks
Verify that table metadata is still present
PYTHON-173
"""
name = self._testMethodName.lower()
self.session.execute('CREATE TABLE %s.d (d INT PRIMARY KEY)' % name)
original_keyspace_meta = self.cluster.metadata.keyspaces[name]
self.assertEqual(original_keyspace_meta.durable_writes, True)
self.assertEqual(len(original_keyspace_meta.tables), 1)
self.session.execute('ALTER KEYSPACE %s WITH durable_writes = false' % name)
new_keyspace_meta = self.cluster.metadata.keyspaces[name]
self.assertNotEqual(original_keyspace_meta, new_keyspace_meta)
self.assertEqual(new_keyspace_meta.durable_writes, False)
class IndexMapTests(unittest.TestCase):
keyspace_name = 'index_map_tests'
@property
def table_name(self):
return self._testMethodName.lower()
@classmethod
def setup_class(cls):
cls.cluster = TestCluster()
cls.session = cls.cluster.connect()
try:
if cls.keyspace_name in cls.cluster.metadata.keyspaces:
cls.session.execute("DROP KEYSPACE %s" % cls.keyspace_name)
cls.session.execute(
"""
CREATE KEYSPACE %s
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};
""" % cls.keyspace_name)
cls.session.set_keyspace(cls.keyspace_name)
except Exception:
cls.cluster.shutdown()
raise
@classmethod
def teardown_class(cls):
try:
cls.session.execute("DROP KEYSPACE %s" % cls.keyspace_name)
finally:
cls.cluster.shutdown()
def create_basic_table(self):
self.session.execute("CREATE TABLE %s (k int PRIMARY KEY, a int)" % self.table_name)
def drop_basic_table(self):
self.session.execute("DROP TABLE %s" % self.table_name)
def test_index_updates(self):
self.create_basic_table()
ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
table_meta = ks_meta.tables[self.table_name]
self.assertNotIn('a_idx', ks_meta.indexes)
self.assertNotIn('b_idx', ks_meta.indexes)
self.assertNotIn('a_idx', table_meta.indexes)
self.assertNotIn('b_idx', table_meta.indexes)
self.session.execute("CREATE INDEX a_idx ON %s (a)" % self.table_name)
self.session.execute("ALTER TABLE %s ADD b int" % self.table_name)
self.session.execute("CREATE INDEX b_idx ON %s (b)" % self.table_name)
ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
table_meta = ks_meta.tables[self.table_name]
self.assertIsInstance(ks_meta.indexes['a_idx'], IndexMetadata)
self.assertIsInstance(ks_meta.indexes['b_idx'], IndexMetadata)
self.assertIsInstance(table_meta.indexes['a_idx'], IndexMetadata)
self.assertIsInstance(table_meta.indexes['b_idx'], IndexMetadata)
# both indexes updated when index dropped
self.session.execute("DROP INDEX a_idx")
# temporarily synchronously refresh the schema metadata, until CASSANDRA-9391 is merged in
self.cluster.refresh_table_metadata(self.keyspace_name, self.table_name)
ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
table_meta = ks_meta.tables[self.table_name]
self.assertNotIn('a_idx', ks_meta.indexes)
self.assertIsInstance(ks_meta.indexes['b_idx'], IndexMetadata)
self.assertNotIn('a_idx', table_meta.indexes)
self.assertIsInstance(table_meta.indexes['b_idx'], IndexMetadata)
# keyspace index updated when table dropped
self.drop_basic_table()
ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
self.assertNotIn(self.table_name, ks_meta.tables)
self.assertNotIn('a_idx', ks_meta.indexes)
self.assertNotIn('b_idx', ks_meta.indexes)
def test_index_follows_alter(self):
self.create_basic_table()
idx = self.table_name + '_idx'
self.session.execute("CREATE INDEX %s ON %s (a)" % (idx, self.table_name))
ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
table_meta = ks_meta.tables[self.table_name]
self.assertIsInstance(ks_meta.indexes[idx], IndexMetadata)
self.assertIsInstance(table_meta.indexes[idx], IndexMetadata)
self.session.execute('ALTER KEYSPACE %s WITH durable_writes = false' % self.keyspace_name)
old_meta = ks_meta
ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
self.assertIsNot(ks_meta, old_meta)
table_meta = ks_meta.tables[self.table_name]
self.assertIsInstance(ks_meta.indexes[idx], IndexMetadata)
self.assertIsInstance(table_meta.indexes[idx], IndexMetadata)
self.drop_basic_table()
class FunctionTest(unittest.TestCase):
"""
Base functionality for Function and Aggregate metadata test classes
"""
def setUp(self):
"""
Tests are skipped if run with native protocol version < 4
"""
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest("Function metadata requires native protocol version 4+")
@property
def function_name(self):
return self._testMethodName.lower()
@classmethod
def setup_class(cls):
if PROTOCOL_VERSION >= 4:
cls.cluster = TestCluster()
cls.keyspace_name = cls.__name__.lower()
cls.session = cls.cluster.connect()
cls.session.execute("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}" % cls.keyspace_name)
cls.session.set_keyspace(cls.keyspace_name)
cls.keyspace_function_meta = cls.cluster.metadata.keyspaces[cls.keyspace_name].functions
cls.keyspace_aggregate_meta = cls.cluster.metadata.keyspaces[cls.keyspace_name].aggregates
@classmethod
def teardown_class(cls):
if PROTOCOL_VERSION >= 4:
cls.session.execute("DROP KEYSPACE IF EXISTS %s" % cls.keyspace_name)
cls.cluster.shutdown()
class Verified(object):
def __init__(self, test_case, meta_class, element_meta, **function_kwargs):
self.test_case = test_case
self.function_kwargs = dict(function_kwargs)
self.meta_class = meta_class
self.element_meta = element_meta
def __enter__(self):
tc = self.test_case
expected_meta = self.meta_class(**self.function_kwargs)
tc.assertNotIn(expected_meta.signature, self.element_meta)
tc.session.execute(expected_meta.as_cql_query())
tc.assertIn(expected_meta.signature, self.element_meta)
generated_meta = self.element_meta[expected_meta.signature]
self.test_case.assertEqual(generated_meta.as_cql_query(), expected_meta.as_cql_query())
return self
def __exit__(self, exc_type, exc_val, exc_tb):
tc = self.test_case
tc.session.execute("DROP %s %s.%s" % (self.meta_class.__name__, tc.keyspace_name, self.signature))
tc.assertNotIn(self.signature, self.element_meta)
@property
def signature(self):
return SignatureDescriptor.format_signature(self.function_kwargs['name'],
self.function_kwargs['argument_types'])
class VerifiedFunction(Verified):
def __init__(self, test_case, **kwargs):
super(FunctionTest.VerifiedFunction, self).__init__(test_case, Function, test_case.keyspace_function_meta, **kwargs)
class VerifiedAggregate(Verified):
def __init__(self, test_case, **kwargs):
super(FunctionTest.VerifiedAggregate, self).__init__(test_case, Aggregate, test_case.keyspace_aggregate_meta, **kwargs)
class FunctionMetadata(FunctionTest):
def make_function_kwargs(self, called_on_null=True):
return {'keyspace': self.keyspace_name,
'name': self.function_name,
'argument_types': ['double', 'int'],
'argument_names': ['d', 'i'],
'return_type': 'double',
'language': 'java',
'body': 'return new Double(0.0);',
'called_on_null_input': called_on_null,
'deterministic': False,
'monotonic': False,
'monotonic_on': []}
def test_functions_after_udt(self):
"""
Test to to ensure functions come after UDTs in in keyspace dump
test_functions_after_udt creates a basic function. Then queries that function and make sure that in the results
that UDT's are listed before any corresponding functions, when we dump the keyspace
Ideally we would make a function that takes a udt type, but this presently fails because C* c059a56 requires
udt to be frozen to create, but does not store meta indicating frozen
SEE https://issues.apache.org/jira/browse/CASSANDRA-9186
Maybe update this after release
kwargs = self.make_function_kwargs()
kwargs['argument_types'][0] = "frozen<%s>" % udt_name
expected_meta = Function(**kwargs)
with self.VerifiedFunction(self, **kwargs):
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result UDT's should come before any functions
@test_category function
"""
self.assertNotIn(self.function_name, self.keyspace_function_meta)
udt_name = 'udtx'
self.session.execute("CREATE TYPE %s (x int)" % udt_name)
with self.VerifiedFunction(self, **self.make_function_kwargs()):
# udts must come before functions in keyspace dump
keyspace_cql = self.cluster.metadata.keyspaces[self.keyspace_name].export_as_string()
type_idx = keyspace_cql.rfind("CREATE TYPE")
func_idx = keyspace_cql.find("CREATE FUNCTION")
self.assertNotIn(-1, (type_idx, func_idx), "TYPE or FUNCTION not found in keyspace_cql: " + keyspace_cql)
self.assertGreater(func_idx, type_idx)
def test_function_same_name_diff_types(self):
"""
Test to verify to that functions with different signatures are differentiated in metadata
test_function_same_name_diff_types Creates two functions. One with the same name but a slightly different
signature. Then ensures that both are surfaced separately in our metadata.
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result function with the same name but different signatures should be surfaced separately
@test_category function
"""
# Create a function
kwargs = self.make_function_kwargs()
with self.VerifiedFunction(self, **kwargs):
# another function: same name, different type sig.
self.assertGreater(len(kwargs['argument_types']), 1)
self.assertGreater(len(kwargs['argument_names']), 1)
kwargs['argument_types'] = kwargs['argument_types'][:1]
kwargs['argument_names'] = kwargs['argument_names'][:1]
# Ensure they are surfaced separately
with self.VerifiedFunction(self, **kwargs):
functions = [f for f in self.keyspace_function_meta.values() if f.name == self.function_name]
self.assertEqual(len(functions), 2)
self.assertNotEqual(functions[0].argument_types, functions[1].argument_types)
def test_function_no_parameters(self):
"""
Test to verify CQL output for functions with zero parameters
Creates a function with no input parameters, verify that CQL output is correct.
@since 2.7.1
@jira_ticket PYTHON-392
@expected_result function with no parameters should generate proper CQL
@test_category function
"""
kwargs = self.make_function_kwargs()
kwargs['argument_types'] = []
kwargs['argument_names'] = []
kwargs['return_type'] = 'bigint'
kwargs['body'] = 'return System.currentTimeMillis() / 1000L;'
with self.VerifiedFunction(self, **kwargs) as vf:
fn_meta = self.keyspace_function_meta[vf.signature]
self.assertRegexpMatches(fn_meta.as_cql_query(), "CREATE FUNCTION.*%s\(\) .*" % kwargs['name'])
def test_functions_follow_keyspace_alter(self):
"""
Test to verify to that functions maintain equality after a keyspace is altered
test_functions_follow_keyspace_alter creates a function then alters a the keyspace associated with that function.
After the alter we validate that the function maintains the same metadata
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result functions are the same after parent keyspace is altered
@test_category function
"""
# Create function
with self.VerifiedFunction(self, **self.make_function_kwargs()):
original_keyspace_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
self.session.execute('ALTER KEYSPACE %s WITH durable_writes = false' % self.keyspace_name)
# After keyspace alter ensure that we maintain function equality.
try:
new_keyspace_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
self.assertNotEqual(original_keyspace_meta, new_keyspace_meta)
self.assertIs(original_keyspace_meta.functions, new_keyspace_meta.functions)
finally:
self.session.execute('ALTER KEYSPACE %s WITH durable_writes = true' % self.keyspace_name)
def test_function_cql_called_on_null(self):
"""
Test to verify to that that called on null argument is honored on function creation.
test_functions_follow_keyspace_alter create two functions. One with the called_on_null_input set to true,
the other with it set to false. We then verify that the metadata constructed from those function is correctly
reflected
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result functions metadata correctly reflects called_on_null_input flag.
@test_category function
"""
kwargs = self.make_function_kwargs()
kwargs['called_on_null_input'] = True
with self.VerifiedFunction(self, **kwargs) as vf:
fn_meta = self.keyspace_function_meta[vf.signature]
self.assertRegexpMatches(fn_meta.as_cql_query(), "CREATE FUNCTION.*\) CALLED ON NULL INPUT RETURNS .*")
kwargs['called_on_null_input'] = False
with self.VerifiedFunction(self, **kwargs) as vf:
fn_meta = self.keyspace_function_meta[vf.signature]
self.assertRegexpMatches(fn_meta.as_cql_query(), "CREATE FUNCTION.*\) RETURNS NULL ON NULL INPUT RETURNS .*")
class AggregateMetadata(FunctionTest):
@classmethod
def setup_class(cls):
if PROTOCOL_VERSION >= 4:
super(AggregateMetadata, cls).setup_class()
cls.session.execute("""CREATE OR REPLACE FUNCTION sum_int(s int, i int)
RETURNS NULL ON NULL INPUT
RETURNS int
LANGUAGE java AS 'return s + i;';""")
cls.session.execute("""CREATE OR REPLACE FUNCTION sum_int_two(s int, i int, j int)
RETURNS NULL ON NULL INPUT
RETURNS int
LANGUAGE java AS 'return s + i + j;';""")
cls.session.execute("""CREATE OR REPLACE FUNCTION "List_As_String"(l list<text>)
RETURNS NULL ON NULL INPUT
RETURNS int
LANGUAGE java AS 'return l.size();';""")
cls.session.execute("""CREATE OR REPLACE FUNCTION extend_list(s list<text>, i int)
CALLED ON NULL INPUT
RETURNS list<text>
LANGUAGE java AS 'if (i != null) s.add(i.toString()); return s;';""")
cls.session.execute("""CREATE OR REPLACE FUNCTION update_map(s map<int, int>, i int)
RETURNS NULL ON NULL INPUT
RETURNS map<int, int>
LANGUAGE java AS 's.put(new Integer(i), new Integer(i)); return s;';""")
cls.session.execute("""CREATE TABLE IF NOT EXISTS t
(k int PRIMARY KEY, v int)""")
for x in range(4):
cls.session.execute("INSERT INTO t (k,v) VALUES (%s, %s)", (x, x))
cls.session.execute("INSERT INTO t (k) VALUES (%s)", (4,))
def make_aggregate_kwargs(self, state_func, state_type, final_func=None, init_cond=None):
return {'keyspace': self.keyspace_name,
'name': self.function_name + '_aggregate',
'argument_types': ['int'],
'state_func': state_func,
'state_type': state_type,
'final_func': final_func,
'initial_condition': init_cond,
'return_type': "does not matter for creation",
'deterministic': False}
def test_return_type_meta(self):
"""
Test to verify to that the return type of a an aggregate is honored in the metadata
test_return_type_meta creates an aggregate then ensures the return type of the created
aggregate is correctly surfaced in the metadata
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result aggregate has the correct return typ in the metadata
@test_category aggregate
"""
with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('sum_int', 'int', init_cond='1')) as va:
self.assertEqual(self.keyspace_aggregate_meta[va.signature].return_type, 'int')
def test_init_cond(self):
"""
Test to verify that various initial conditions are correctly surfaced in various aggregate functions
test_init_cond creates several different types of aggregates, and given various initial conditions it verifies that
they correctly impact the aggregate's execution
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result initial conditions are correctly evaluated as part of the aggregates
@test_category aggregate
"""
# This is required until the java driver bundled with C* is updated to support v4
c = TestCluster(protocol_version=3)
s = c.connect(self.keyspace_name)
encoder = Encoder()
expected_values = range(4)
# int32
for init_cond in (-1, 0, 1):
cql_init = encoder.cql_encode_all_types(init_cond)
with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('sum_int', 'int', init_cond=cql_init)) as va:
sum_res = s.execute("SELECT %s(v) AS sum FROM t" % va.function_kwargs['name'])[0].sum
self.assertEqual(sum_res, int(init_cond) + sum(expected_values))
# list<text>
for init_cond in ([], ['1', '2']):
cql_init = encoder.cql_encode_all_types(init_cond)
with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('extend_list', 'list<text>', init_cond=cql_init)) as va:
list_res = s.execute("SELECT %s(v) AS list_res FROM t" % va.function_kwargs['name'])[0].list_res
self.assertListEqual(list_res[:len(init_cond)], init_cond)
self.assertEqual(set(i for i in list_res[len(init_cond):]),
set(str(i) for i in expected_values))
# map<int,int>
expected_map_values = dict((i, i) for i in expected_values)
expected_key_set = set(expected_values)
for init_cond in ({}, {1: 2, 3: 4}, {5: 5}):
cql_init = encoder.cql_encode_all_types(init_cond)
with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('update_map', 'map<int, int>', init_cond=cql_init)) as va:
map_res = s.execute("SELECT %s(v) AS map_res FROM t" % va.function_kwargs['name'])[0].map_res
self.assertDictContainsSubset(expected_map_values, map_res)
init_not_updated = dict((k, init_cond[k]) for k in set(init_cond) - expected_key_set)
self.assertDictContainsSubset(init_not_updated, map_res)
c.shutdown()
def test_aggregates_after_functions(self):
"""
Test to verify that aggregates are listed after function in metadata
test_aggregates_after_functions creates an aggregate, and then verifies that they are listed
after any function creations when the keypspace dump is preformed
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result aggregates are declared after any functions
@test_category aggregate
"""
# functions must come before functions in keyspace dump
with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('extend_list', 'list<text>')):
keyspace_cql = self.cluster.metadata.keyspaces[self.keyspace_name].export_as_string()
func_idx = keyspace_cql.find("CREATE FUNCTION")
aggregate_idx = keyspace_cql.rfind("CREATE AGGREGATE")
self.assertNotIn(-1, (aggregate_idx, func_idx), "AGGREGATE or FUNCTION not found in keyspace_cql: " + keyspace_cql)
self.assertGreater(aggregate_idx, func_idx)
def test_same_name_diff_types(self):
"""
Test to verify to that aggregates with different signatures are differentiated in metadata
test_same_name_diff_types Creates two Aggregates. One with the same name but a slightly different
signature. Then ensures that both are surfaced separately in our metadata.
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result aggregates with the same name but different signatures should be surfaced separately
@test_category function
"""
kwargs = self.make_aggregate_kwargs('sum_int', 'int', init_cond='0')
with self.VerifiedAggregate(self, **kwargs):
kwargs['state_func'] = 'sum_int_two'
kwargs['argument_types'] = ['int', 'int']
with self.VerifiedAggregate(self, **kwargs):
aggregates = [a for a in self.keyspace_aggregate_meta.values() if a.name == kwargs['name']]
self.assertEqual(len(aggregates), 2)
self.assertNotEqual(aggregates[0].argument_types, aggregates[1].argument_types)
def test_aggregates_follow_keyspace_alter(self):
"""
Test to verify to that aggregates maintain equality after a keyspace is altered
test_aggregates_follow_keyspace_alter creates a function then alters a the keyspace associated with that
function. After the alter we validate that the function maintains the same metadata
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result aggregates are the same after parent keyspace is altered
@test_category function
"""
with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('sum_int', 'int', init_cond='0')):
original_keyspace_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
self.session.execute('ALTER KEYSPACE %s WITH durable_writes = false' % self.keyspace_name)
try:
new_keyspace_meta = self.cluster.metadata.keyspaces[self.keyspace_name]
self.assertNotEqual(original_keyspace_meta, new_keyspace_meta)
self.assertIs(original_keyspace_meta.aggregates, new_keyspace_meta.aggregates)
finally:
self.session.execute('ALTER KEYSPACE %s WITH durable_writes = true' % self.keyspace_name)
def test_cql_optional_params(self):
"""
Test to verify that the initial_cond and final_func parameters are correctly honored
test_cql_optional_params creates various aggregates with different combinations of initial_condition,
and final_func parameters set. It then ensures they are correctly honored.
@since 2.6.0
@jira_ticket PYTHON-211
@expected_result initial_condition and final_func parameters are honored correctly
@test_category function
"""
kwargs = self.make_aggregate_kwargs('extend_list', 'list<text>')
encoder = Encoder()
# no initial condition, final func
self.assertIsNone(kwargs['initial_condition'])
self.assertIsNone(kwargs['final_func'])
with self.VerifiedAggregate(self, **kwargs) as va:
meta = self.keyspace_aggregate_meta[va.signature]
self.assertIsNone(meta.initial_condition)
self.assertIsNone(meta.final_func)
cql = meta.as_cql_query()
self.assertEqual(cql.find('INITCOND'), -1)
self.assertEqual(cql.find('FINALFUNC'), -1)
# initial condition, no final func
kwargs['initial_condition'] = encoder.cql_encode_all_types(['init', 'cond'])
with self.VerifiedAggregate(self, **kwargs) as va:
meta = self.keyspace_aggregate_meta[va.signature]
self.assertEqual(meta.initial_condition, kwargs['initial_condition'])
self.assertIsNone(meta.final_func)
cql = meta.as_cql_query()
search_string = "INITCOND %s" % kwargs['initial_condition']
self.assertGreater(cql.find(search_string), 0, '"%s" search string not found in cql:\n%s' % (search_string, cql))
self.assertEqual(cql.find('FINALFUNC'), -1)
# no initial condition, final func
kwargs['initial_condition'] = None
kwargs['final_func'] = 'List_As_String'
with self.VerifiedAggregate(self, **kwargs) as va:
meta = self.keyspace_aggregate_meta[va.signature]
self.assertIsNone(meta.initial_condition)
self.assertEqual(meta.final_func, kwargs['final_func'])
cql = meta.as_cql_query()
self.assertEqual(cql.find('INITCOND'), -1)
search_string = 'FINALFUNC "%s"' % kwargs['final_func']
self.assertGreater(cql.find(search_string), 0, '"%s" search string not found in cql:\n%s' % (search_string, cql))
# both
kwargs['initial_condition'] = encoder.cql_encode_all_types(['init', 'cond'])
kwargs['final_func'] = 'List_As_String'
with self.VerifiedAggregate(self, **kwargs) as va:
meta = self.keyspace_aggregate_meta[va.signature]
self.assertEqual(meta.initial_condition, kwargs['initial_condition'])
self.assertEqual(meta.final_func, kwargs['final_func'])
cql = meta.as_cql_query()
init_cond_idx = cql.find("INITCOND %s" % kwargs['initial_condition'])
final_func_idx = cql.find('FINALFUNC "%s"' % kwargs['final_func'])
self.assertNotIn(-1, (init_cond_idx, final_func_idx))
self.assertGreater(init_cond_idx, final_func_idx)
class BadMetaTest(unittest.TestCase):
"""
Test behavior when metadata has unexpected form
Verify that new cluster/session can still connect, and the CQL output indicates the exception with a warning.
PYTHON-370
"""
class BadMetaException(Exception):
pass
@property
def function_name(self):
return self._testMethodName.lower()
@classmethod
def setup_class(cls):
cls.cluster = TestCluster()
cls.keyspace_name = cls.__name__.lower()
cls.session = cls.cluster.connect()
cls.session.execute("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}" % cls.keyspace_name)
cls.session.set_keyspace(cls.keyspace_name)
connection = cls.cluster.control_connection._connection
cls.parser_class = get_schema_parser(
connection,
cls.cluster.metadata.get_host(connection.host).release_version,
cls.cluster.metadata.get_host(connection.host).dse_version,
timeout=20
).__class__
cls.cluster.control_connection.reconnect = Mock()
@classmethod
def teardown_class(cls):
drop_keyspace_shutdown_cluster(cls.keyspace_name, cls.session, cls.cluster)
def test_bad_keyspace(self):
with patch.object(self.parser_class, '_build_keyspace_metadata_internal', side_effect=self.BadMetaException):
self.cluster.refresh_keyspace_metadata(self.keyspace_name)
m = self.cluster.metadata.keyspaces[self.keyspace_name]
self.assertIs(m._exc_info[0], self.BadMetaException)
self.assertIn("/*\nWarning:", m.export_as_string())
def test_bad_table(self):
self.session.execute('CREATE TABLE %s (k int PRIMARY KEY, v int)' % self.function_name)
with patch.object(self.parser_class, '_build_column_metadata', side_effect=self.BadMetaException):
self.cluster.refresh_table_metadata(self.keyspace_name, self.function_name)
m = self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_name]
self.assertIs(m._exc_info[0], self.BadMetaException)
self.assertIn("/*\nWarning:", m.export_as_string())
def test_bad_index(self):
self.session.execute('CREATE TABLE %s (k int PRIMARY KEY, v int)' % self.function_name)
self.session.execute('CREATE INDEX ON %s(v)' % self.function_name)
with patch.object(self.parser_class, '_build_index_metadata', side_effect=self.BadMetaException):
self.cluster.refresh_table_metadata(self.keyspace_name, self.function_name)
m = self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_name]
self.assertIs(m._exc_info[0], self.BadMetaException)
self.assertIn("/*\nWarning:", m.export_as_string())
@greaterthancass20
def test_bad_user_type(self):
self.session.execute('CREATE TYPE %s (i int, d double)' % self.function_name)
with patch.object(self.parser_class, '_build_user_type', side_effect=self.BadMetaException):
self.cluster.refresh_schema_metadata() # presently do not capture these errors on udt direct refresh -- make sure it's contained during full refresh
m = self.cluster.metadata.keyspaces[self.keyspace_name]
self.assertIs(m._exc_info[0], self.BadMetaException)
self.assertIn("/*\nWarning:", m.export_as_string())
@greaterthancass21
def test_bad_user_function(self):
self.session.execute("""CREATE FUNCTION IF NOT EXISTS %s (key int, val int)
RETURNS NULL ON NULL INPUT
RETURNS int
LANGUAGE java AS 'return key + val;';""" % self.function_name)
#We need to patch as well the reconnect function because after patching the _build_function
#there will an Error refreshing schema which will trigger a reconnection. If this happened
#in a timely manner in the call self.cluster.refresh_schema_metadata() it would return an exception
#due to that a connection would be closed
with patch.object(self.cluster.control_connection, 'reconnect'):
with patch.object(self.parser_class, '_build_function', side_effect=self.BadMetaException):
self.cluster.refresh_schema_metadata() # presently do not capture these errors on udt direct refresh -- make sure it's contained during full refresh
m = self.cluster.metadata.keyspaces[self.keyspace_name]
self.assertIs(m._exc_info[0], self.BadMetaException)
self.assertIn("/*\nWarning:", m.export_as_string())
@greaterthancass21
def test_bad_user_aggregate(self):
self.session.execute("""CREATE FUNCTION IF NOT EXISTS sum_int (key int, val int)
RETURNS NULL ON NULL INPUT
RETURNS int
LANGUAGE java AS 'return key + val;';""")
self.session.execute("""CREATE AGGREGATE %s(int)
SFUNC sum_int
STYPE int
INITCOND 0""" % self.function_name)
#We have the same issue here as in test_bad_user_function
with patch.object(self.cluster.control_connection, 'reconnect'):
with patch.object(self.parser_class, '_build_aggregate', side_effect=self.BadMetaException):
self.cluster.refresh_schema_metadata() # presently do not capture these errors on udt direct refresh -- make sure it's contained during full refresh
m = self.cluster.metadata.keyspaces[self.keyspace_name]
self.assertIs(m._exc_info[0], self.BadMetaException)
self.assertIn("/*\nWarning:", m.export_as_string())
class DynamicCompositeTypeTest(BasicSharedKeyspaceUnitTestCase):
def test_dct_alias(self):
"""
Tests to make sure DCT's have correct string formatting
Constructs a DCT and check the format as generated. To insure it matches what is expected
@since 3.6.0
@jira_ticket PYTHON-579
@expected_result DCT subtypes should always have fully qualified names
@test_category metadata
"""
self.session.execute("CREATE TABLE {0}.{1} ("
"k int PRIMARY KEY,"
"c1 'DynamicCompositeType(s => UTF8Type, i => Int32Type)',"
"c2 Text)".format(self.ks_name, self.function_table_name))
dct_table = self.cluster.metadata.keyspaces.get(self.ks_name).tables.get(self.function_table_name)
# Format can very slightly between versions, strip out whitespace for consistency sake
table_text = dct_table.as_cql_query().replace(" ", "")
dynamic_type_text = "c1'org.apache.cassandra.db.marshal.DynamicCompositeType("
self.assertIn("c1'org.apache.cassandra.db.marshal.DynamicCompositeType(", table_text)
# Types within in the composite can come out in random order, so grab the type definition and find each one
type_definition_start = table_text.index("(", table_text.find(dynamic_type_text))
type_definition_end = table_text.index(")")
type_definition_text = table_text[type_definition_start:type_definition_end]
self.assertIn("s=>org.apache.cassandra.db.marshal.UTF8Type", type_definition_text)
self.assertIn("i=>org.apache.cassandra.db.marshal.Int32Type", type_definition_text)
@greaterthanorequalcass30
class MaterializedViewMetadataTestSimple(BasicSharedKeyspaceUnitTestCase):
def setUp(self):
self.session.execute("CREATE TABLE {0}.{1} (pk int PRIMARY KEY, c int)".format(self.keyspace_name, self.function_table_name))
self.session.execute(
"CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT pk, c FROM {0}.{1} "
"WHERE pk IS NOT NULL AND c IS NOT NULL PRIMARY KEY (pk, c)".format(
self.keyspace_name, self.function_table_name)
)
def tearDown(self):
self.session.execute("DROP MATERIALIZED VIEW {0}.mv1".format(self.keyspace_name))
self.session.execute("DROP TABLE {0}.{1}".format(self.keyspace_name, self.function_table_name))
def test_materialized_view_metadata_creation(self):
"""
test for materialized view metadata creation
test_materialized_view_metadata_creation tests that materialized view metadata properly created implicitly in
both keyspace and table metadata under "views". It creates a simple base table and then creates a view based
on that table. It then checks that the materialized view metadata is contained in the keyspace and table
metadata. Finally, it checks that the keyspace_name and the base_table_name in the view metadata is properly set.
@since 3.0.0
@jira_ticket PYTHON-371
@expected_result Materialized view metadata in both the ks and table should be created with a new view is created.
@test_category metadata
"""
self.assertIn("mv1", self.cluster.metadata.keyspaces[self.keyspace_name].views)
self.assertIn("mv1", self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
self.assertEqual(self.keyspace_name, self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views["mv1"].keyspace_name)
self.assertEqual(self.function_table_name, self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views["mv1"].base_table_name)
def test_materialized_view_metadata_alter(self):
"""
test for materialized view metadata alteration
test_materialized_view_metadata_alter tests that materialized view metadata is properly updated implicitly in the
table metadata once that view is updated. It creates a simple base table and then creates a view based
on that table. It then alters that materalized view and checks that the materialized view metadata is altered in
the table metadata.
@since 3.0.0
@jira_ticket PYTHON-371
@expected_result Materialized view metadata should be updated with the view is altered.
@test_category metadata
"""
self.assertIn("SizeTieredCompactionStrategy", self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views["mv1"].options["compaction"]["class"])
self.session.execute("ALTER MATERIALIZED VIEW {0}.mv1 WITH compaction = {{ 'class' : 'LeveledCompactionStrategy' }}".format(self.keyspace_name))
self.assertIn("LeveledCompactionStrategy", self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views["mv1"].options["compaction"]["class"])
def test_materialized_view_metadata_drop(self):
"""
test for materialized view metadata dropping
test_materialized_view_metadata_drop tests that materialized view metadata is properly removed implicitly in
both keyspace and table metadata once that view is dropped. It creates a simple base table and then creates a view
based on that table. It then drops that materalized view and checks that the materialized view metadata is removed
from the keyspace and table metadata.
@since 3.0.0
@jira_ticket PYTHON-371
@expected_result Materialized view metadata in both the ks and table should be removed with the view is dropped.
@test_category metadata
"""
self.session.execute("DROP MATERIALIZED VIEW {0}.mv1".format(self.keyspace_name))
self.assertNotIn("mv1", self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
self.assertNotIn("mv1", self.cluster.metadata.keyspaces[self.keyspace_name].views)
self.assertDictEqual({}, self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views)
self.assertDictEqual({}, self.cluster.metadata.keyspaces[self.keyspace_name].views)
self.session.execute(
"CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT pk, c FROM {0}.{1} "
"WHERE pk IS NOT NULL AND c IS NOT NULL PRIMARY KEY (pk, c)".format(
self.keyspace_name, self.function_table_name)
)
@greaterthanorequalcass30
class MaterializedViewMetadataTestComplex(BasicSegregatedKeyspaceUnitTestCase):
def test_create_view_metadata(self):
"""
test to ensure that materialized view metadata is properly constructed
test_create_view_metadata tests that materialized views metadata is properly constructed. It runs a simple
query to construct a materialized view, then proceeds to inspect the metadata associated with that MV.
Columns are inspected to insure that all are of the proper type, and in the proper type.
@since 3.0.0
@jira_ticket PYTHON-371
@expected_result Materialized view metadata should be constructed appropriately.
@test_category metadata
"""
create_table = """CREATE TABLE {0}.scores(
user TEXT,
game TEXT,
year INT,
month INT,
day INT,
score INT,
PRIMARY KEY (user, game, year, month, day)
)""".format(self.keyspace_name)
self.session.execute(create_table)
create_mv = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS
SELECT game, year, month, score, user, day FROM {0}.scores
WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL
PRIMARY KEY ((game, year, month), score, user, day)
WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)""".format(self.keyspace_name)
self.session.execute(create_mv)
score_table = self.cluster.metadata.keyspaces[self.keyspace_name].tables['scores']
mv = self.cluster.metadata.keyspaces[self.keyspace_name].views['monthlyhigh']
self.assertIsNotNone(score_table.views["monthlyhigh"])
self.assertIsNotNone(len(score_table.views), 1)
# Make sure user is a partition key, and not null
self.assertEqual(len(score_table.partition_key), 1)
self.assertIsNotNone(score_table.columns['user'])
self.assertTrue(score_table.columns['user'], score_table.partition_key[0])
# Validate clustering keys
self.assertEqual(len(score_table.clustering_key), 4)
self.assertIsNotNone(score_table.columns['game'])
self.assertTrue(score_table.columns['game'], score_table.clustering_key[0])
self.assertIsNotNone(score_table.columns['year'])
self.assertTrue(score_table.columns['year'], score_table.clustering_key[1])
self.assertIsNotNone(score_table.columns['month'])
self.assertTrue(score_table.columns['month'], score_table.clustering_key[2])
self.assertIsNotNone(score_table.columns['day'])
self.assertTrue(score_table.columns['day'], score_table.clustering_key[3])
self.assertIsNotNone(score_table.columns['score'])
# Validate basic mv information
self.assertEqual(mv.keyspace_name, self.keyspace_name)
self.assertEqual(mv.name, "monthlyhigh")
self.assertEqual(mv.base_table_name, "scores")
self.assertFalse(mv.include_all_columns)
# Validate that all columns are preset and correct
mv_columns = list(mv.columns.values())
self.assertEqual(len(mv_columns), 6)
game_column = mv_columns[0]
self.assertIsNotNone(game_column)
self.assertEqual(game_column.name, 'game')
self.assertEqual(game_column, mv.partition_key[0])
year_column = mv_columns[1]
self.assertIsNotNone(year_column)
self.assertEqual(year_column.name, 'year')
self.assertEqual(year_column, mv.partition_key[1])
month_column = mv_columns[2]
self.assertIsNotNone(month_column)
self.assertEqual(month_column.name, 'month')
self.assertEqual(month_column, mv.partition_key[2])
def compare_columns(a, b, name):
self.assertEqual(a.name, name)
self.assertEqual(a.name, b.name)
self.assertEqual(a.table, b.table)
self.assertEqual(a.cql_type, b.cql_type)
self.assertEqual(a.is_static, b.is_static)
self.assertEqual(a.is_reversed, b.is_reversed)
score_column = mv_columns[3]
compare_columns(score_column, mv.clustering_key[0], 'score')
user_column = mv_columns[4]
compare_columns(user_column, mv.clustering_key[1], 'user')
day_column = mv_columns[5]
compare_columns(day_column, mv.clustering_key[2], 'day')
def test_base_table_column_addition_mv(self):
"""
test to ensure that materialized view metadata is properly updated with base columns are added
test_create_view_metadata tests that materialized views metadata is properly updated when columns are added to
the base table.
@since 3.0.0
@jira_ticket PYTHON-419
@expected_result Materialized view metadata should be updated correctly
@test_category metadata
"""
create_table = """CREATE TABLE {0}.scores(
user TEXT,
game TEXT,
year INT,
month INT,
day INT,
score TEXT,
PRIMARY KEY (user, game, year, month, day)
)""".format(self.keyspace_name)
self.session.execute(create_table)
create_mv = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS
SELECT game, year, month, score, user, day FROM {0}.scores
WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL
PRIMARY KEY ((game, year, month), score, user, day)
WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)""".format(self.keyspace_name)
create_mv_alltime = """CREATE MATERIALIZED VIEW {0}.alltimehigh AS
SELECT * FROM {0}.scores
WHERE game IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL
PRIMARY KEY (game, score, user, year, month, day)
WITH CLUSTERING ORDER BY (score DESC, user ASC, year ASC, month ASC, day ASC)""".format(self.keyspace_name)
self.session.execute(create_mv)
self.session.execute(create_mv_alltime)
score_table = self.cluster.metadata.keyspaces[self.keyspace_name].tables['scores']
self.assertIsNotNone(score_table.views["monthlyhigh"])
self.assertIsNotNone(score_table.views["alltimehigh"])
self.assertEqual(len(self.cluster.metadata.keyspaces[self.keyspace_name].views), 2)
insert_fouls = """ALTER TABLE {0}.scores ADD fouls INT""".format((self.keyspace_name))
self.session.execute(insert_fouls)
self.assertEqual(len(self.cluster.metadata.keyspaces[self.keyspace_name].views), 2)
score_table = self.cluster.metadata.keyspaces[self.keyspace_name].tables['scores']
self.assertIn("fouls", score_table.columns)
# This is a workaround for mv notifications being separate from base table schema responses.
# This maybe fixed with future protocol changes
for i in range(10):
mv_alltime = self.cluster.metadata.keyspaces[self.keyspace_name].views["alltimehigh"]
if("fouls" in mv_alltime.columns):
break
time.sleep(.2)
self.assertIn("fouls", mv_alltime.columns)
mv_alltime_fouls_comumn = self.cluster.metadata.keyspaces[self.keyspace_name].views["alltimehigh"].columns['fouls']
self.assertEqual(mv_alltime_fouls_comumn.cql_type, 'int')
@lessthancass30
def test_base_table_type_alter_mv(self):
"""
test to ensure that materialized view metadata is properly updated when a type in the base table
is updated.
test_create_view_metadata tests that materialized views metadata is properly updated when the type of base table
column is changed.
Support for alter type was removed in CASSANDRA-12443
@since 3.0.0
@jira_ticket CASSANDRA-10424
@expected_result Materialized view metadata should be updated correctly
@test_category metadata
"""
create_table = """CREATE TABLE {0}.scores(
user TEXT,
game TEXT,
year INT,
month INT,
day INT,
score TEXT,
PRIMARY KEY (user, game, year, month, day)
)""".format(self.keyspace_name)
self.session.execute(create_table)
create_mv = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS
SELECT game, year, month, score, user, day FROM {0}.scores
WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL
PRIMARY KEY ((game, year, month), score, user, day)
WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)""".format(self.keyspace_name)
self.session.execute(create_mv)
self.assertEqual(len(self.cluster.metadata.keyspaces[self.keyspace_name].views), 1)
alter_scores = """ALTER TABLE {0}.scores ALTER score TYPE blob""".format((self.keyspace_name))
self.session.execute(alter_scores)
self.assertEqual(len(self.cluster.metadata.keyspaces[self.keyspace_name].views), 1)
score_column = self.cluster.metadata.keyspaces[self.keyspace_name].tables['scores'].columns['score']
self.assertEqual(score_column.cql_type, 'blob')
# until CASSANDRA-9920+CASSANDRA-10500 MV updates are only available later with an async event
for i in range(10):
score_mv_column = self.cluster.metadata.keyspaces[self.keyspace_name].views["monthlyhigh"].columns['score']
if "blob" == score_mv_column.cql_type:
break
time.sleep(.2)
self.assertEqual(score_mv_column.cql_type, 'blob')
def test_metadata_with_quoted_identifiers(self):
"""
test to ensure that materialized view metadata is properly constructed when quoted identifiers are used
test_metadata_with_quoted_identifiers tests that materialized views metadata is properly constructed.
It runs a simple query to construct a materialized view, then proceeds to inspect the metadata associated with
that MV. The caveat here is that the tables and the materialized view both have quoted identifiers
Columns are inspected to insure that all are of the proper type, and in the proper type.
@since 3.0.0
@jira_ticket PYTHON-371
@expected_result Materialized view metadata should be constructed appropriately even with quoted identifiers.
@test_category metadata
"""
create_table = """CREATE TABLE {0}.t1 (
"theKey" int,
"the;Clustering" int,
"the Value" int,
PRIMARY KEY ("theKey", "the;Clustering"))""".format(self.keyspace_name)
self.session.execute(create_table)
create_mv = """CREATE MATERIALIZED VIEW {0}.mv1 AS
SELECT "theKey", "the;Clustering", "the Value"
FROM {0}.t1
WHERE "theKey" IS NOT NULL AND "the;Clustering" IS NOT NULL AND "the Value" IS NOT NULL
PRIMARY KEY ("theKey", "the;Clustering")""".format(self.keyspace_name)
self.session.execute(create_mv)
t1_table = self.cluster.metadata.keyspaces[self.keyspace_name].tables['t1']
mv = self.cluster.metadata.keyspaces[self.keyspace_name].views['mv1']
self.assertIsNotNone(t1_table.views["mv1"])
self.assertIsNotNone(len(t1_table.views), 1)
# Validate partition key, and not null
self.assertEqual(len(t1_table.partition_key), 1)
self.assertIsNotNone(t1_table.columns['theKey'])
self.assertTrue(t1_table.columns['theKey'], t1_table.partition_key[0])
# Validate clustering key column
self.assertEqual(len(t1_table.clustering_key), 1)
self.assertIsNotNone(t1_table.columns['the;Clustering'])
self.assertTrue(t1_table.columns['the;Clustering'], t1_table.clustering_key[0])
# Validate regular column
self.assertIsNotNone(t1_table.columns['the Value'])
# Validate basic mv information
self.assertEqual(mv.keyspace_name, self.keyspace_name)
self.assertEqual(mv.name, "mv1")
self.assertEqual(mv.base_table_name, "t1")
self.assertFalse(mv.include_all_columns)
# Validate that all columns are preset and correct
mv_columns = list(mv.columns.values())
self.assertEqual(len(mv_columns), 3)
theKey_column = mv_columns[0]
self.assertIsNotNone(theKey_column)
self.assertEqual(theKey_column.name, 'theKey')
self.assertEqual(theKey_column, mv.partition_key[0])
cluster_column = mv_columns[1]
self.assertIsNotNone(cluster_column)
self.assertEqual(cluster_column.name, 'the;Clustering')
self.assertEqual(cluster_column.name, mv.clustering_key[0].name)
self.assertEqual(cluster_column.table, mv.clustering_key[0].table)
self.assertEqual(cluster_column.is_static, mv.clustering_key[0].is_static)
self.assertEqual(cluster_column.is_reversed, mv.clustering_key[0].is_reversed)
value_column = mv_columns[2]
self.assertIsNotNone(value_column)
self.assertEqual(value_column.name, 'the Value')
@greaterthanorequaldse51
def test_dse_workloads(self):
"""
Test to ensure dse_workloads is populated appropriately.
Field added in DSE 5.1
@jira_ticket PYTHON-667
@expected_result dse_workloads set is set on host model
@test_category metadata
"""
for host in self.cluster.metadata.all_hosts():
self.assertIsInstance(host.dse_workloads, SortedSet)
self.assertIn("Cassandra", host.dse_workloads)
class GroupPerHost(BasicSharedKeyspaceUnitTestCase):
@classmethod
def setUpClass(cls):
cls.common_setup(rf=1, create_class_table=True)
cls.table_two_pk = "table_with_two_pk"
cls.session.execute(
'''
CREATE TABLE {0}.{1} (
k_one int,
k_two int,
v int,
PRIMARY KEY ((k_one, k_two))
)'''.format(cls.ks_name, cls.table_two_pk)
)
def test_group_keys_by_host(self):
"""
Test to ensure group_keys_by_host functions as expected. It is tried
with a table with a single field for the partition key and a table
with two fields for the partition key
@since 3.13
@jira_ticket PYTHON-647
@expected_result group_keys_by_host return the expected value
@test_category metadata
"""
stmt = """SELECT * FROM {}.{}
WHERE k_one = ? AND k_two = ? """.format(self.ks_name, self.table_two_pk)
keys = ((1, 2), (2, 2), (2, 3), (3, 4))
self._assert_group_keys_by_host(keys, self.table_two_pk, stmt)
stmt = """SELECT * FROM {}.{}
WHERE k = ? """.format(self.ks_name, self.ks_name)
keys = ((1,), (2,), (2,), (3,))
self._assert_group_keys_by_host(keys, self.ks_name, stmt)
def _assert_group_keys_by_host(self, keys, table_name, stmt):
keys_per_host = group_keys_by_replica(self.session, self.ks_name, table_name, keys)
self.assertNotIn(NO_VALID_REPLICA, keys_per_host)
prepared_stmt = self.session.prepare(stmt)
for key in keys:
routing_key = prepared_stmt.bind(key).routing_key
hosts = self.cluster.metadata.get_replicas(self.ks_name, routing_key)
self.assertEqual(1, len(hosts)) # RF is 1 for this keyspace
self.assertIn(key, keys_per_host[hosts[0]])
class VirtualKeypaceTest(BasicSharedKeyspaceUnitTestCase):
virtual_ks_names = ('system_virtual_schema', 'system_views')
def test_existing_keyspaces_have_correct_virtual_tags(self):
for name, ks in self.cluster.metadata.keyspaces.items():
if name in self.virtual_ks_names:
self.assertTrue(
ks.virtual,
'incorrect .virtual value for {}'.format(name)
)
else:
self.assertFalse(
ks.virtual,
'incorrect .virtual value for {}'.format(name)
)
@greaterthanorequalcass40
@greaterthanorequaldse67
def test_expected_keyspaces_exist_and_are_virtual(self):
for name in self.virtual_ks_names:
self.assertTrue(
self.cluster.metadata.keyspaces[name].virtual,
'incorrect .virtual value for {}'.format(name)
)
@greaterthanorequalcass40
@greaterthanorequaldse67
def test_virtual_keyspaces_have_expected_schema_structure(self):
self.maxDiff = None
ingested_virtual_ks_structure = defaultdict(dict)
for ks_name, ks in self.cluster.metadata.keyspaces.items():
if not ks.virtual:
continue
for tab_name, tab in ks.tables.items():
ingested_virtual_ks_structure[ks_name][tab_name] = set(
tab.columns.keys()
)
# Identify a couple known values to verify we parsed the structure correctly
self.assertIn('table_name', ingested_virtual_ks_structure['system_virtual_schema']['tables'])
self.assertIn('type', ingested_virtual_ks_structure['system_virtual_schema']['columns'])
self.assertIn('total', ingested_virtual_ks_structure['system_views']['sstable_tasks'])
|
// https://www.codewars.com/kata/55c04b4cc56a697bb0000048/train/javascript
// function scramble(str1, str2) {
// let letterHolder = {};
// for (let letter of str1) {
// if (letterHolder[letter]) letterHolder[letter]++;
// else letterHolder[letter] = 1;
// }
// for (let letter of str2) {
// if (!letterHolder[letter]) return false;
// else letterHolder[letter]--;
// }
// return true;
// }
// ---------------------------------------------------------------------------------------------------
// function scramble(str1, str2) {
// var hashtab = [...new Array(256)].map((x) => 0);
// str2.split('').forEach((ele) => hashtab[ele.charCodeAt(0)]++);
// str1.split('').forEach((ele) => hashtab[ele.charCodeAt(0)]--);
// hashtab = hashtab.filter((x) => x > 0);
// return hashtab.length == 0;
// }
// ---------------------------------------------------------------------------------------------------
// function scramble(str1, str2) {
// let occurences = str1.split("").reduce((arr, cur) => { arr[cur] ? arr[cur]++ : arr[cur] = 1; return arr; }, {});
// return str2.split("").every((character) => --occurences[character] >= 0);
// }
// NOTE: spent almost 2 days because my code was too slow.
// above is what i found on the internet.
function scramble(param1, param2) {
const sortedOne = param1.split('').sort();
const map = {};
// build map will removed dups
for (let i = 0; i < sortedOne.length; i++) {
const element = sortedOne[i];
if (!map[element]) {
map[element] = element;
}
}
// console.log({ map: map });
let two = param2.split('').sort();
const exTwo = [];
// sort and remove duplicates
for (let i = 0; i < two.length; i++) {
const first = two[i];
const second = two[i + 1];
if (first != second) {
exTwo.push(first);
}
}
// console.log({ exTwo: exTwo });
let result = [];
// check inside map
for (let i = 0; i < exTwo.length; i++) {
const element = exTwo[i];
if (map[element]) {
result.push(element);
}
}
result = result.join('') === exTwo.join('');
return result;
}
module.exports = scramble;
|
import warnings
from collections import OrderedDict
from django.apps import apps
from django.core import serializers
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, router
class ProxyModelWarning(Warning):
pass
class Command(BaseCommand):
help = ("Output the contents of the database as a fixture of the given "
"format (using each model's default manager unless --all is "
"specified).")
def add_arguments(self, parser):
parser.add_argument('args', metavar='app_label[.ModelName]', nargs='*',
help='Restricts dumped data to the specified app_label or app_label.ModelName.')
parser.add_argument('--format', default='json', dest='format',
help='Specifies the output serialization format for fixtures.')
parser.add_argument('--indent', default=None, dest='indent', type=int,
help='Specifies the indent level to use when pretty-printing output.')
parser.add_argument('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS,
help='Nominates a specific database to dump fixtures from. '
'Defaults to the "default" database.')
parser.add_argument('-e', '--exclude', dest='exclude', action='append', default=[],
help='An app_label or app_label.ModelName to exclude '
'(use multiple --exclude to exclude multiple apps/models).')
parser.add_argument('--natural-foreign', action='store_true', dest='use_natural_foreign_keys', default=False,
help='Use natural foreign keys if they are available.')
parser.add_argument('--natural-primary', action='store_true', dest='use_natural_primary_keys', default=False,
help='Use natural primary keys if they are available.')
parser.add_argument('-a', '--all', action='store_true', dest='use_base_manager', default=False,
help="Use Django's base manager to dump all models stored in the database, "
"including those that would otherwise be filtered or modified by a custom manager.")
parser.add_argument('--pks', dest='primary_keys',
help="Only dump objects with given primary keys. "
"Accepts a comma separated list of keys. "
"This option will only work when you specify one model.")
parser.add_argument('-o', '--output', default=None, dest='output',
help='Specifies file to which the output is written.')
def handle(self, *app_labels, **options):
format = options['format']
indent = options['indent']
using = options['database']
excludes = options['exclude']
output = options['output']
show_traceback = options['traceback']
use_natural_foreign_keys = options['use_natural_foreign_keys']
use_natural_primary_keys = options['use_natural_primary_keys']
use_base_manager = options['use_base_manager']
pks = options['primary_keys']
if pks:
primary_keys = pks.split(',')
else:
primary_keys = []
excluded_apps = set()
excluded_models = set()
for exclude in excludes:
if '.' in exclude:
try:
model = apps.get_model(exclude)
except LookupError:
raise CommandError('Unknown model in excludes: %s' % exclude)
excluded_models.add(model)
else:
try:
app_config = apps.get_app_config(exclude)
except LookupError as e:
raise CommandError(str(e))
excluded_apps.add(app_config)
if len(app_labels) == 0:
if primary_keys:
raise CommandError("You can only use --pks option with one model")
app_list = OrderedDict((app_config, None)
for app_config in apps.get_app_configs()
if app_config.models_module is not None and app_config not in excluded_apps)
else:
if len(app_labels) > 1 and primary_keys:
raise CommandError("You can only use --pks option with one model")
app_list = OrderedDict()
for label in app_labels:
try:
app_label, model_label = label.split('.')
try:
app_config = apps.get_app_config(app_label)
except LookupError as e:
raise CommandError(str(e))
if app_config.models_module is None or app_config in excluded_apps:
continue
try:
model = app_config.get_model(model_label)
except LookupError:
raise CommandError("Unknown model: %s.%s" % (app_label, model_label))
app_list_value = app_list.setdefault(app_config, [])
# We may have previously seen a "all-models" request for
# this app (no model qualifier was given). In this case
# there is no need adding specific models to the list.
if app_list_value is not None:
if model not in app_list_value:
app_list_value.append(model)
except ValueError:
if primary_keys:
raise CommandError("You can only use --pks option with one model")
# This is just an app - no model qualifier
app_label = label
try:
app_config = apps.get_app_config(app_label)
except LookupError as e:
raise CommandError(str(e))
if app_config.models_module is None or app_config in excluded_apps:
continue
app_list[app_config] = None
# Check that the serialization format exists; this is a shortcut to
# avoid collating all the objects and _then_ failing.
if format not in serializers.get_public_serializer_formats():
try:
serializers.get_serializer(format)
except serializers.SerializerDoesNotExist:
pass
raise CommandError("Unknown serialization format: %s" % format)
def get_objects(count_only=False):
"""
Collate the objects to be serialized. If count_only is True, just
count the number of objects to be serialized.
"""
models = serializers.sort_dependencies(app_list.items())
for model in models:
if model in excluded_models:
continue
if model._meta.proxy and model._meta.proxy_for_model not in models:
warnings.warn(
"%s is a proxy model and won't be serialized." % model._meta.label,
category=ProxyModelWarning,
)
if not model._meta.proxy and router.allow_migrate_model(using, model):
if use_base_manager:
objects = model._base_manager
else:
objects = model._default_manager
queryset = objects.using(using).order_by(model._meta.pk.name)
if primary_keys:
queryset = queryset.filter(pk__in=primary_keys)
if count_only:
yield queryset.order_by().count()
else:
for obj in queryset.iterator():
yield obj
try:
self.stdout.ending = None
progress_output = None
object_count = 0
# If dumpdata is outputting to stdout, there is no way to display progress
if (output and self.stdout.isatty() and options['verbosity'] > 0):
progress_output = self.stdout
object_count = sum(get_objects(count_only=True))
stream = open(output, 'w') if output else None
try:
serializers.serialize(format, get_objects(), indent=indent,
use_natural_foreign_keys=use_natural_foreign_keys,
use_natural_primary_keys=use_natural_primary_keys,
stream=stream or self.stdout, progress_output=progress_output,
object_count=object_count)
finally:
if stream:
stream.close()
except Exception as e:
if show_traceback:
raise
raise CommandError("Unable to serialize database: %s" % e)
|
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
# PyPi upload Command
# rm -r dist ; python setup.py sdist ; python -m twine upload dist/*
setuptools.setup(
name="TikTokLive",
packages=setuptools.find_packages(),
version="0.8.9",
license="MIT",
description="TikTok Live Connection Client",
author="Isaac Kogan",
author_email="info@isaackogan.com",
url="https://github.com/isaackogan/TikTokLive",
long_description=long_description,
long_description_content_type="text/markdown",
download_url="https://github.com/isaackogan/TikTokLive/releases/tag/v0.8.9",
keywords=["tiktok", "tiktok live", "python3", "api", "unofficial"],
install_requires=[
"aiohttp>=3.8", # Make requests
"protobuf3-to-dict>=0.1.5", # Convert Protobuf to Dict
"protobuf>=3.19.4", # Decode Protobuf Messages
"pyee>=9.0.4", # Event Emitter
"dacite>=1.6.0" # Requests
],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Build Tools",
"License :: OSI Approved :: MIT License",
"Framework :: aiohttp",
"Natural Language :: English",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
]
)
|
import Rx from 'rxjs';
import configureStore from './configureStore';
import reducer$ from "../reducers";
import { getState, saveState } from "../services/storage";
const initialState = getState();
const store = configureStore(reducer$, initialState);
store.subscribe(saveState);
export default store;
|
# coding=utf-8
# Copyright 2021 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The Neural GPU model and its variants."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import range # pylint: disable=redefined-builtin
from tensor2tensor.layers import common_hparams
from tensor2tensor.layers import common_layers
from tensor2tensor.utils import registry
from tensor2tensor.utils import t2t_model
import tensorflow.compat.v1 as tf
def neural_gpu_body(inputs, hparams, name=None):
"""The core Neural GPU."""
with tf.variable_scope(name, "neural_gpu"):
def step(state, inp): # pylint: disable=missing-docstring
x = tf.nn.dropout(state, 1.0 - hparams.dropout)
for layer in range(hparams.num_hidden_layers):
x = common_layers.conv_gru(
x, (hparams.kernel_height, hparams.kernel_width),
hparams.hidden_size,
name="cgru_%d" % layer)
# Padding input is zeroed-out in the modality, we check this by summing.
padding_inp = tf.less(tf.reduce_sum(tf.abs(inp), axis=[1, 2]), 0.00001)
new_state = tf.where(padding_inp, state, x) # No-op where inp is padding.
return new_state
return tf.foldl(
step,
tf.transpose(inputs, [1, 0, 2, 3]),
initializer=inputs,
parallel_iterations=1,
swap_memory=True)
@registry.register_model
class NeuralGPU(t2t_model.T2TModel):
def body(self, features):
return neural_gpu_body(features["inputs"], self._hparams)
def diagonal_neural_gpu(inputs, hparams, name=None):
"""Improved Neural GPU as in https://arxiv.org/abs/1702.08727."""
with tf.variable_scope(name, "diagonal_neural_gpu"):
def step(state_tup, inp):
"""Single step of the improved Neural GPU."""
state, _ = state_tup
x = state
for layer in range(hparams.num_hidden_layers):
x, new_loss = common_layers.diagonal_conv_gru(
x, (hparams.kernel_height, hparams.kernel_width),
hparams.hidden_size,
dropout=hparams.dropout,
name="dcgru_%d" % layer)
# Padding input is zeroed-out in the modality, we check this by summing.
padding_inp = tf.less(tf.reduce_sum(tf.abs(inp), axis=[1, 2]), 0.00001)
new_state = tf.where(padding_inp, state, x) # No-op where inp is padding.
return new_state, new_loss
final_state, losses = tf.scan(
step,
tf.transpose(inputs, [1, 0, 2, 3]),
initializer=(inputs, tf.constant(0.0)),
parallel_iterations=1,
swap_memory=True)
return final_state[0, :, :, :, :], 2.0 * tf.reduce_mean(losses)
@registry.register_model
class DiagonalNeuralGPU(t2t_model.T2TModel):
def body(self, features):
return diagonal_neural_gpu(features["inputs"], self._hparams)
@registry.register_hparams
def neural_gpu():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.daisy_chain_variables = False
hparams.batch_size = 1024
hparams.num_hidden_layers = 1
hparams.hidden_size = 256
hparams.dropout = 0.1
hparams.label_smoothing = 0.0
hparams.clip_grad_norm = 10.0
hparams.num_hidden_layers = 1
hparams.kernel_height = 3
hparams.kernel_width = 1
hparams.learning_rate_decay_scheme = "exp"
hparams.learning_rate = 0.02
hparams.learning_rate_warmup_steps = 3000
hparams.initializer_gain = 1.0
hparams.weight_decay = 0.0
hparams.num_sampled_classes = 0
hparams.sampling_method = "argmax"
hparams.optimizer_adam_epsilon = 1e-6
hparams.optimizer_adam_beta1 = 0.85
hparams.optimizer_adam_beta2 = 0.997
return hparams
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.TimelineOverviewBase}
* @param {!WebInspector.TimelineModel} model
*/
WebInspector.TimelineEventOverview = function(model)
{
WebInspector.TimelineOverviewBase.call(this, model);
this.element.id = "timeline-overview-events";
this._fillStyles = {};
var categories = WebInspector.TimelineUIUtils.categories();
for (var category in categories) {
this._fillStyles[category] = categories[category].fillColorStop1;
categories[category].addEventListener(WebInspector.TimelineCategory.Events.VisibilityChanged, this._onCategoryVisibilityChanged, this);
}
this._disabledCategoryFillStyle = "hsl(0, 0%, 67%)";
}
/** @const */
WebInspector.TimelineEventOverview._mainStripHeight = 16;
/** @const */
WebInspector.TimelineEventOverview._smallStripHeight = 8;
WebInspector.TimelineEventOverview.prototype = {
/**
* @override
*/
dispose: function()
{
WebInspector.TimelineOverviewBase.prototype.dispose.call(this);
var categories = WebInspector.TimelineUIUtils.categories();
for (var category in categories)
categories[category].removeEventListener(WebInspector.TimelineCategory.Events.VisibilityChanged, this._onCategoryVisibilityChanged, this);
},
/**
* @override
*/
update: function()
{
this.resetCanvas();
var threads = this._model.virtualThreads();
var mainThreadEvents = this._model.mainThreadEvents();
var networkHeight = this._canvas.clientHeight
- WebInspector.TimelineEventOverview._mainStripHeight
- 2 * WebInspector.TimelineEventOverview._smallStripHeight;
var position = 0;
if (Runtime.experiments.isEnabled("inputEventsOnTimelineOverview")) {
var inputHeight = this._drawInputEvents(mainThreadEvents, position, WebInspector.TimelineEventOverview._smallStripHeight);
position += inputHeight;
networkHeight -= inputHeight;
}
position += this._drawNetwork(mainThreadEvents, position, networkHeight);
position += this._drawEvents(mainThreadEvents, position, WebInspector.TimelineEventOverview._mainStripHeight);
for (var thread of threads.filter(function(thread) { return !thread.isWorker(); }))
this._drawEvents(thread.events, position, WebInspector.TimelineEventOverview._smallStripHeight);
position += WebInspector.TimelineEventOverview._smallStripHeight;
for (var thread of threads.filter(function(thread) { return thread.isWorker(); }))
this._drawEvents(thread.events, position, WebInspector.TimelineEventOverview._smallStripHeight);
position += WebInspector.TimelineEventOverview._smallStripHeight;
console.assert(position === this._canvas.clientHeight);
},
/**
* @param {!Array.<!WebInspector.TracingModel.Event>} events
* @param {number} position
* @param {number} height
* @return {number}
*/
_drawInputEvents: function(events, position, height)
{
var /** @const */ padding = 1;
var descriptors = WebInspector.TimelineUIUtils.eventDispatchDesciptors();
/** @type {!Map.<string,!WebInspector.TimelineUIUtils.EventDispatchTypeDescriptor>} */
var descriptorsByType = new Map();
var maxPriority = -1;
for (var descriptor of descriptors) {
for (var type of descriptor.eventTypes)
descriptorsByType.set(type, descriptor);
maxPriority = Math.max(maxPriority, descriptor.priority);
}
var /** @const */ minWidth = 2 * window.devicePixelRatio;
var stripHeight = height - padding;
var timeOffset = this._model.minimumRecordTime();
var timeSpan = this._model.maximumRecordTime() - timeOffset;
var canvasWidth = this._canvas.width;
var scale = canvasWidth / timeSpan;
for (var priority = 0; priority <= maxPriority; ++priority) {
for (var i = 0; i < events.length; ++i) {
var event = events[i];
if (event.name !== WebInspector.TimelineModel.RecordType.EventDispatch)
continue;
var descriptor = descriptorsByType.get(event.args["data"]["type"]);
if (!descriptor || descriptor.priority !== priority)
continue;
var start = Number.constrain(Math.floor((event.startTime - timeOffset) * scale), 0, canvasWidth);
var end = Number.constrain(Math.ceil((event.endTime - timeOffset) * scale), 0, canvasWidth);
var width = Math.max(end - start, minWidth);
this._renderBar(start, start + width, position + padding, stripHeight, descriptor.color);
}
}
return height;
},
/**
* @param {!Array.<!WebInspector.TracingModel.Event>} events
* @param {number} position
* @param {number} height
* @return {number}
*/
_drawNetwork: function(events, position, height)
{
var /** @const */ padding = 1;
var /** @const */ maxBandHeight = 4;
position += padding;
var bandsCount = WebInspector.TimelineUIUtils.calculateNetworkBandsCount(events);
var bandInterval = Math.min(maxBandHeight, (height - padding) / (bandsCount || 1));
var bandHeight = Math.ceil(bandInterval);
var timeOffset = this._model.minimumRecordTime();
var timeSpan = this._model.maximumRecordTime() - timeOffset;
var canvasWidth = this._canvas.width;
var scale = canvasWidth / timeSpan;
var loadingCategory = WebInspector.TimelineUIUtils.categories()["loading"];
var waitingColor = loadingCategory.backgroundColor;
var processingColor = loadingCategory.fillColorStop1;
/**
* @param {number} band
* @param {number} startTime
* @param {number} endTime
* @param {?WebInspector.TracingModel.Event} event
* @this {WebInspector.TimelineEventOverview}
*/
function drawBar(band, startTime, endTime, event)
{
var start = Number.constrain((startTime - timeOffset) * scale, 0, canvasWidth);
var end = Number.constrain((endTime - timeOffset) * scale, 0, canvasWidth);
var color = !event ||
event.name === WebInspector.TimelineModel.RecordType.ResourceReceiveResponse ||
event.name === WebInspector.TimelineModel.RecordType.ResourceSendRequest ? waitingColor : processingColor;
this._renderBar(Math.floor(start), Math.ceil(end), Math.floor(position + band * bandInterval), bandHeight, color);
}
WebInspector.TimelineUIUtils.iterateNetworkRequestsInRoundRobin(events, bandsCount, drawBar.bind(this));
return height;
},
/**
* @param {!Array.<!WebInspector.TracingModel.Event>} events
* @param {number} position
* @param {number} stripHeight
* @return {number}
*/
_drawEvents: function(events, position, stripHeight)
{
var /** @const */ padding = 1;
var visualHeight = stripHeight - padding;
var timeOffset = this._model.minimumRecordTime();
var timeSpan = this._model.maximumRecordTime() - timeOffset;
var scale = this._canvas.width / timeSpan;
var ditherer = new WebInspector.Dithering();
var categoryStack = [];
var lastX = 0;
position += padding;
/**
* @param {!WebInspector.TimelineCategory} category
* @return {string}
* @this {WebInspector.TimelineEventOverview}
*/
function categoryColor(category)
{
return category.hidden ? this._disabledCategoryFillStyle : this._fillStyles[category.name];
}
/**
* @param {!WebInspector.TracingModel.Event} e
* @this {WebInspector.TimelineEventOverview}
*/
function onEventStart(e)
{
var pos = (e.startTime - timeOffset) * scale;
if (categoryStack.length) {
var category = categoryStack.peekLast();
var bar = ditherer.appendInterval(category, lastX, pos);
if (bar)
this._renderBar(bar.start, bar.end, position, visualHeight, categoryColor.call(this, category));
}
categoryStack.push(WebInspector.TimelineUIUtils.eventStyle(e).category);
lastX = pos;
}
/**
* @param {!WebInspector.TracingModel.Event} e
* @this {WebInspector.TimelineEventOverview}
*/
function onEventEnd(e)
{
var category = categoryStack.pop();
var pos = (e.endTime - timeOffset) * scale;
var bar = ditherer.appendInterval(category, lastX, pos);
if (bar)
this._renderBar(bar.start, bar.end, position, visualHeight, categoryColor.call(this, category));
lastX = pos;
}
WebInspector.TimelineModel.forEachEvent(events, onEventStart.bind(this), onEventEnd.bind(this));
return stripHeight;
},
_onCategoryVisibilityChanged: function()
{
this.update();
},
/**
* @param {number} begin
* @param {number} end
* @param {number} position
* @param {number} height
* @param {string} color
*/
_renderBar: function(begin, end, position, height, color)
{
var x = begin;
var y = position * window.devicePixelRatio;
var width = end - begin;
this._context.fillStyle = color;
this._context.fillRect(x, y, width, height * window.devicePixelRatio);
},
__proto__: WebInspector.TimelineOverviewBase.prototype
}
/**
* @constructor
* @template T
*/
WebInspector.Dithering = function()
{
/** @type {!Map.<?T,number>} */
this._groupError = new Map();
this._position = 0;
this._lastReportedPosition = 0;
}
WebInspector.Dithering.prototype = {
/**
* @param {!T} group
* @param {number} start
* @param {number} end
* @return {?{start: number, end: number}}
* @template T
*/
appendInterval: function(group, start, end)
{
this._innerAppend(null, start); // Append an empty space before.
return this._innerAppend(group, end); // Append the interval itself.
},
/**
* @param {?T} group
* @param {number} position
* @return {?{start: number, end: number}}
* @template T
*/
_innerAppend: function(group, position)
{
if (position < this._position)
return null;
var result = null;
var length = position - this._position;
length += this._groupError.get(group) || 0;
if (length >= 1) {
if (!group)
length -= this._distributeExtraAmount(length - 1);
var newReportedPosition = this._lastReportedPosition + Math.floor(length);
result = { start: this._lastReportedPosition, end: newReportedPosition };
this._lastReportedPosition = newReportedPosition;
length %= 1;
}
this._groupError.set(group, length);
this._position = position;
return result;
},
/**
* @param {number} amount
* @return {number}
*/
_distributeExtraAmount: function(amount)
{
var canConsume = 0;
for (var g of this._groupError.keys()) {
if (g)
canConsume += 1 - this._groupError.get(g);
}
var toDistribute = Math.min(amount, canConsume);
if (toDistribute <= 0)
return 0;
var ratio = toDistribute / canConsume;
for (var g of this._groupError.keys()) {
if (!g)
continue;
var value = this._groupError.get(g);
value += (1 - value) * ratio;
this._groupError.set(g, value);
}
return toDistribute;
}
}
|
"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FooterLinkText = void 0;
const classnames_1 = __importDefault(require("classnames"));
const react_1 = __importDefault(require("react"));
const FooterLinkText = (_a) => {
var divProps = __rest(_a, []);
return (react_1.default.createElement("div", Object.assign({}, divProps, { className: (0, classnames_1.default)(divProps.className), style: Object.assign({ color: '#0095f6', fontWeight: 600, padding: 16, fontFamily: 'Arial,sans-serif', fontSize: '14px', fontStyle: 'normal' }, divProps.style) }), divProps.children));
};
exports.FooterLinkText = FooterLinkText;
|
import pandas as pd
# Read in the data from the csv file using the full pathway
# Save it as pokemon_sample
# Only load in the first 100 rows and only load in columns name, total_bs, type
pokemon_sample = pd.read_csv('data/pokemon.csv',
nrows=100,
usecols=['name', 'total_bs', 'type'])
# Display the dataframe
pokemon_sample
|
import Vue from 'vue';
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);
new Vue({
el: "#salaryInfoDiv",
data: {
message: 'Hello Vue!',
salaryInfo:[],
info_name: '',
info_status: 0,
info_amount: '',
info_type: 'Allowance',
errorsHtml: '',
hdn_id: '',
edit_info_name: null,
edit_info_status: 0,
edit_info_amount: '',
edit_info_type: '',
edit_errorsHtml: '',
salaryInfoIndex: '',
testVal: [],
},
mounted(){
axios.get('/salaryInfo/getAllInfo').then(response => this.salaryInfo = response.data);
},
methods: {
saveSalaryInfo: function(event){
axios.post('/salaryInfo/add', {
info_name: this.info_name,
info_status: this.info_status,
info_amount: this.info_amount,
info_type: this.info_type,
})
.then((response) => {
this.salaryInfo.push(response.data.data);
document.getElementById("modal-close-btn").click();
new PNotify({
title: response.data.title+' Message',
text: response.data.message,
shadow: true,
addclass: 'stack_top_right',
type: response.data.title,
width: '290px',
delay: 1500
});
})
.catch((error) => {
if(error.response.status != 200){ //error 422
var errors = error.response.data;
var errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors , function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></di>';
$( '#create-form-errors' ).html( errorsHtml );
}
});
},
editSalaryInfo: function(id, index){
this.salaryInfoIndex = index;
axios.get("/salaryInfo/edit/"+id,{
})
.then((response) => {
this.hdn_id = response.data.id;
this.edit_info_name = response.data.salary_info_name;
this.edit_info_amount = response.data.salary_info_amount;
this.edit_info_status = response.data.salary_info_amount_status;
this.edit_info_type = response.data.salary_info_type;
})
.catch(function (error) {
swal('Error:','Edit function not working','error');
document.getElementById("modal-edit-close-btn").click();
});
},
updateSalaryInfo: function(){
axios.post('/salaryInfo/edit',{
hdn_id: this.hdn_id,
edit_info_name: this.edit_info_name,
edit_info_status: this.edit_info_status,
edit_info_amount: this.edit_info_amount,
edit_info_type: this.edit_info_type,
})
.then(response => {
document.getElementById("modal-edit-close-btn").click();
this.salaryInfo[this.salaryInfoIndex].salary_info_name = this.edit_info_name;
this.salaryInfo[this.salaryInfoIndex].salary_info_amount = this.edit_info_amount;
this.salaryInfo[this.salaryInfoIndex].salary_info_amount_status = this.edit_info_status;
this.salaryInfo[this.salaryInfoIndex].salary_info_type = this.edit_info_type;
new PNotify({
title: response.data.title+' Message',
text: response.data.message,
shadow: true,
addclass: 'stack_top_right',
type: response.data.title,
width: '290px',
delay: 1500
});
})
.catch( (error) => {
var errors = error.response.data;
var errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors , function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></di>';
$( '#edit-form-errors' ).html( errorsHtml );
});
},
deleteSalaryInfo: function(id, index){
var delSalaryInfo = this.salaryInfo;
swal({
title: "Are you sure?",
text: "You will not be able to recover this information!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function(){
swal("Deleted!", "Your imaginary file has been deleted.", "success");
axios.get("/salaryInfo/delete/"+id+"/"+index,{
})
.then((response) => {
new PNotify({
title: response.data.title+' Message',
text: response.data.message,
shadow: true,
addclass: 'stack_top_right',
type: response.data.title,
width: '290px',
delay: 1500
});
//console.log("--ok--"+response);
delSalaryInfo.splice(response.data.indexId, 1);
})
.catch(function (error) {
//console.log("--error--"+error);
swal('Error:','Delete function not working','error');
});
});
}
}
});
|
from rest_framework import status
from rest_framework.reverse import reverse
from tests.test_resource_tracker.test_api.base_test_api import BaseTestAPI
class TestResourceGroupUpdate(BaseTestAPI):
def setUp(self):
super(TestResourceGroupUpdate, self).setUp()
self.url = reverse('api_resource_group_details', args=[self.rg_physical_servers.id])
def test_update(self):
"""
Update is partial. attribute_definitions and text_attribute_definitions are not handled
"""
data = {
"name": "updated",
"tags": ["new_tag"]
}
response = self.client.put(self.url, data=data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.rg_physical_servers.refresh_from_db()
self.assertEqual(self.rg_physical_servers.name, "updated")
self.assertEqual(self.rg_physical_servers.tags.all().first().name, "new_tag")
|
'use strict';
// Libraries
const net = require('net');
// Config
const { APPLICATION_HOST, APPLICATION_PORT } = require('./config');
net
.createServer((socket) => {
console.log('A client connected');
socket.on('data', (data) => socket.write(data));
})
.listen(APPLICATION_PORT, APPLICATION_HOST, () =>
console.log(
`Server is listening on ${APPLICATION_HOST}:${APPLICATION_PORT}`,
),
);
|
# Imports:
import os
import logging
from sqlalchemy.ext.automap import automap_base
from flask import jsonify, current_app, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from QA_worker import run_script
import QA_db
from QA_db import Job, JobidBase, set_job_status
from QA_config import config
# seconds to sleep before re-querying the server:
retry_seconds = config.getint('frontend', 'retry_seconds', fallback=20)
db = SQLAlchemy()
jobs_logger = logging.getLogger('jobs')
################################################################################
# Check if a job with this (command & parameters) is running or queued.
#
# We output that job. If the job does not exist or is in a "DONE"/"ERROR"
# state, we return None.
def getUnfinishedJob(project_name, command, imageid):
# get the job:
project_id = QA_db.get_project_id(project_name)
current_app.logger.info(f'Checking if a job is free for project {project_id} ("{project_name}").')
job = Job.query.filter_by(
projId=project_id,
cmd=command,
imageId=imageid).filter(
Job.status != "DONE").filter(
Job.status != "ERROR").first()
return job
################################################################################
################################################################################
# Call this function to update a job's status in the database:
def update_completed_job_status(result):
retval, job_id = result
# non-zero integer return values indicate an error
status = "DONE"
if isinstance(retval, int) and retval != 0:
status = "ERROR"
jobs_logger.info(f'Setting job status to {status}')
set_job_status(job_id, status)
# If no callback has been assigned after an async job is run, call this function:
def worker_default_callback(result):
jobs_logger.info('Default callback upon job completion called.')
jobs_logger.info(f'Full result = {result}')
update_completed_job_status(result)
jobs_logger.info('Worker callback done.')
# This gets called once an async job is complete and updates the database status:
def error_default_callback(error): # TODO update!! This is very important!
jobs_logger.error(f'Worker ERROR callback upon job completion fail. {error}')
################################################################################
################################################################################
# Add this job to the database and start run it asynchronously.
#
# The whatToRun should be a function which takes in two arguments: arguments & jobId.
#
# project_id, command, and parameters define the job in the database.
#
# It will output the 202 html response code
# and a json request to check again in a few seconds.
def add_async_job(project_id, command, parameters, arguments, what_to_run, imageid=None, callback=None):
# log message:
current_app.logger.info(f"Adding {command} to thread pool.")
# create a new queued job:
new_job = Job(projId=project_id, imageId = imageid, cmd=command, status="QUEUE", params=str(arguments), retval="")
db.session.add(new_job)
db.session.commit()
# --- make job table now as well as an endpoint to the DB -- should go into a function so that the other function can use it as well
jobtablename = f"jobid_{new_job.id}"
meta = QA_db.db.metadata
newjobtable = JobidBase.__table__.tometadata(meta, name=jobtablename)
newjobtable.create(bind=QA_db.db.engine, checkfirst=True)
Base = automap_base()
Base.prepare(QA_db.db.engine, reflect=True)
newtableobj = Base.classes[jobtablename]
newtableobj.__tablename__ = jobtablename
current_app.apimanager.create_api(newtableobj,
methods=['GET', 'POST', 'DELETE', 'PUT'],
url_prefix='/api/db',
results_per_page=0, max_results_per_page=0)
# for the whatToRun function, we will pass in a tuple containing
# the arguments (which it must unpack itself), and the job id
arguments_and_job = (arguments, new_job.id)
# spin up a new thread and run the whatToRun function in that thread:
current_app.logger.info(f'Running {command} via {what_to_run}:')
QA_db._pool.apply_async(what_to_run, args=arguments_and_job,
callback=worker_default_callback if callback is None else callback,
error_callback=error_default_callback)
# output the 202 response code and a message to retry:
current_app.logger.info('Reporting to the browser that the job was submitted with HTML response code 202.')
return jsonify(job=new_job.as_dict(), retry=retry_seconds), 202
################################################################################
# Run an external script (cmd) asynchronously.
#
# command_name is non-functional and just for
# identifying this command in the database.
#
# full_command should be a list of an external command
# and its arguments
def pool_run_script(project_name, command_name, full_command, imageid=None, callback=None):
# check if the job is free:
parameters = project_name # <-- by convention for running scripts
job = getUnfinishedJob(project_name, command_name, imageid)
if job is None:
project_id = QA_db.get_project_id(project_name)
return add_async_job(project_id, command_name, parameters, full_command, run_script, imageid=imageid,
callback=callback)
else:
return jsonify(job=job.as_dict(), retry=retry_seconds), 409 # --job exists, return the job
################################################################################
################################################################################
# Output an image that will be calculated with function_name
# given a set of args and then stored at image_filename.
#
# parameters are used to help identify this job in the database.
#
# If the image exists, it will be output.
# If not, it will be calculated asynchronously.
def pool_get_image(project_name, command_name, full_command, image_filename, imageid=None, callback=None):
current_app.logger.info(f'Getting image {image_filename} from project {project_name}.')
# check if the image exists on disk:
if not os.path.isfile(image_filename):
current_app.logger.info(
f'Image does not exist. Running function {command_name} with parameters {full_command}.')
return pool_run_script(project_name, command_name, full_command, imageid=imageid, callback=callback)
else:
# This image exists and the job is done; output it to the frontend:
folder, filename = os.path.split(image_filename)
response = send_from_directory(folder, filename)
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
################################################################################
|
# Copyright 2021, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pytype: skip-file
# This modules disables the Pytype analyzer, see
# https://github.com/tensorflow/federated/blob/main/docs/pytype.md for more
# information.
"""Execution context for single-aggregation computations."""
import asyncio
import functools
import math
from typing import Any, Callable, List, Optional, Sequence, Union
import attr
from tensorflow_federated.python.common_libs import py_typecheck
from tensorflow_federated.python.common_libs import structure
from tensorflow_federated.python.core.api import computation_base
from tensorflow_federated.python.core.impl.compiler import building_blocks
from tensorflow_federated.python.core.impl.compiler import compiler_pipeline
from tensorflow_federated.python.core.impl.compiler import tree_analysis
from tensorflow_federated.python.core.impl.context_stack import context_base
from tensorflow_federated.python.core.impl.execution_contexts import async_execution_context
from tensorflow_federated.python.core.impl.executors import cardinalities_utils
from tensorflow_federated.python.core.impl.executors import executor_factory
from tensorflow_federated.python.core.impl.types import computation_types
from tensorflow_federated.python.core.impl.types import placements
from tensorflow_federated.python.core.impl.types import type_analysis
from tensorflow_federated.python.core.impl.types import type_conversions
from tensorflow_federated.python.core.impl.types import typed_object
class MergeTypeNotAssignableError(TypeError):
pass
class UpToMergeTypeError(TypeError):
pass
class AfterMergeStructureError(ValueError):
pass
class MergeableCompForm:
"""A data class for computations containing a single logical aggregation.
`MergeableCompForm` contains three member computations, `up_to_merge`
and `merge`, and `after_merge`. A computation in `MergeableCompForm` is
defined to be equivalent to invoking `up_to_merge` on subsets of
`CLIENTS`-placed arguments in sequence, invoking `merge` on the stream of
these results, and passing the resulting value (placed at `tff.SERVER`) to
`after_merge`, in addition to the original argument to `up_to_merge`.
In the case of a no-arg `up_to_merge` computation, `after_merge` should accept
only the result of `merge`. `up_to_merge` should return a single
`tff.SERVER`-placed value.
We require that computations in `MergeableCompForm` contain *no* AST
nodes with signatures taking arguments at `tff.CLIENTS` and producing results
at `tff.SERVER`.
`MergeableCompForm` computations are often generated by aligning a computation
containing a single logical aggregation on this aggregation, and splitting it
along its merge boundary. That is, since `merge` can be invoked repeatedly
without changing the results of the computation, a computation of the form:
```
@tff.federated_computation(...)
def single_aggregation(arg):
result_at_clients = work(arg)
agg_result = tff.federated_aggregate(
result_at_clients, zero, accumulate, merge, report)
return postprocess(arg, agg_result)
```
can be represented as the `MergeableCompForm` triplet:
```
@tff.federated_computation(tff.AbstractType('T'))
def up_to_merge(arg):
result_at_clients = work(arg)
agg_result = tff.federated_aggregate(
result_at_clients, accumulate_zero, accumulate, merge, identity_report)
return agg_result
@tff.federated_computation([up_to_merge.type_signature.result.member,
up_to_merge.type_signature.result.member])
def merge(arg):
return merge(arg[0], arg[1])
@tff.federated_computation(
tff.AbstractType('T'), tff.type_at_server(merge.type_signature.result))
def after_merge(original_arg, merged_result):
return postprocess(original_arg, merged_result)
```
A fair amount of complexity can be hidden in `postprocess`; it could, for
example, compute some value on clients based on the result of the aggregation.
But the restriction that `after_merge` can contain no aggregations ensures
that `after_merge` can also be executed in a subround fashion: a
`tff.CLIENTS`-placed result can only depend on its own local state and the
result of the aggregation, while a `tff.SERVER`-placed result can only depend
on the result of the single aggregation or a `tff.SERVER`-placed value.
"""
def __init__(self, *, up_to_merge: computation_base.Computation,
merge: computation_base.Computation,
after_merge: computation_base.Computation):
if not (up_to_merge.type_signature.result.is_federated() and
up_to_merge.type_signature.result.placement.is_server()):
raise UpToMergeTypeError(
'Expected `up_to_merge` to return a single `tff.SERVER`-placed '
f'value; found return type {up_to_merge.type_signature.result}.')
# TFF's StructType assignability relation ensures that an unnamed struct can
# be assigned to any struct with names.
expected_merge_param_type = computation_types.StructType([
(None, up_to_merge.type_signature.result.member),
(None, up_to_merge.type_signature.result.member)
])
if not merge.type_signature.parameter.is_assignable_from(
expected_merge_param_type):
raise MergeTypeNotAssignableError(
'Type mismatch checking `merge` type signature.\n' +
computation_types.type_mismatch_error_message(
merge.type_signature.parameter,
expected_merge_param_type,
computation_types.TypeRelation.ASSIGNABLE,
second_is_expected=True))
if not (merge.type_signature.parameter[0].is_assignable_from(
merge.type_signature.result) and
merge.type_signature.parameter[1].is_assignable_from(
merge.type_signature.result)):
raise MergeTypeNotAssignableError(
'Expected `merge` to have result which is assignable to '
'each element of its parameter tuple; found parameter '
f'of type: \n{merge.type_signature.parameter}\nAnd result of type: \n'
f'{merge.type_signature.result}')
if up_to_merge.type_signature.parameter is not None:
# TODO(b/147499373): If None arguments were uniformly represented as empty
# tuples, we could avoid this and related ugly if/else casing.
expected_after_merge_arg_type = computation_types.StructType([
(None, up_to_merge.type_signature.parameter),
(None, computation_types.at_server(merge.type_signature.result)),
])
else:
expected_after_merge_arg_type = computation_types.at_server(
merge.type_signature.result)
after_merge.type_signature.parameter.check_assignable_from(
expected_after_merge_arg_type)
def _federated_type_predicate(
type_signature: computation_types.Type,
placement: placements.PlacementLiteral) -> bool:
return (type_signature.is_federated() and
type_signature.placement == placement)
def _moves_clients_to_server_predicate(
intrinsic: building_blocks.Intrinsic):
parameter_contains_clients_placement = type_analysis.contains(
intrinsic.type_signature.parameter,
lambda x: _federated_type_predicate(x, placements.CLIENTS))
result_contains_server_placement = type_analysis.contains(
intrinsic.type_signature.result,
lambda x: _federated_type_predicate(x, placements.SERVER))
return (parameter_contains_clients_placement and
result_contains_server_placement)
aggregations = set()
def _aggregation_predicate(
comp: building_blocks.ComputationBuildingBlock) -> bool:
if not comp.is_intrinsic():
return False
if not comp.type_signature.is_function():
return False
if _moves_clients_to_server_predicate(comp):
aggregations.add((comp.uri, comp.type_signature))
return True
return False
# We only know how to statically analyze computations which are backed by
# computation.protos; to avoid opening up a visibility hole that isn't
# technically necessary here, we prefer to simply skip the static check here
# for computations which cannot convert themselves to building blocks.
if hasattr(after_merge, 'to_building_block') and tree_analysis.contains(
after_merge.to_building_block(), _aggregation_predicate):
formatted_aggregations = ', '.join(
'{}: {}'.format(elem[0], elem[1]) for elem in aggregations)
raise AfterMergeStructureError(
'Expected `after_merge` to contain no intrinsics '
'with signatures accepting values at clients and '
'returning values at server. Found the following '
f'aggregations: {formatted_aggregations}')
self.up_to_merge = up_to_merge
self.merge = merge
self.after_merge = after_merge
@attr.s
class _PartitioningValue:
"""Data class to hold info on traversal while partitioning into subrounds."""
payload = attr.ib()
num_remaining_clients = attr.ib()
num_remaining_partitions = attr.ib()
last_client_index = attr.ib()
def _partition_value(
val: _PartitioningValue,
type_signature: computation_types.Type) -> _PartitioningValue:
"""Partitions value as specified in _split_value_into_subrounds."""
if type_signature.is_struct():
struct_val = structure.from_container(val.payload)
result_container = []
for (_, val_elem), (name, type_elem) in zip(
structure.iter_elements(struct_val),
structure.iter_elements(type_signature)):
partitioning_val_elem = _PartitioningValue(val_elem,
val.num_remaining_clients,
val.num_remaining_partitions,
val.last_client_index)
partition_result = _partition_value(partitioning_val_elem, type_elem)
result_container.append((name, partition_result.payload))
return _PartitioningValue(
structure.Struct(result_container),
partition_result.num_remaining_clients,
partition_result.num_remaining_partitions,
partition_result.last_client_index)
elif (type_signature.is_federated() and
type_signature.placement.is_clients()):
if type_signature.all_equal:
# In this case we simply replicate the argument for every subround.
return val
py_typecheck.check_type(val.payload, (list, tuple))
num_clients_for_subround = math.ceil(val.num_remaining_clients /
val.num_remaining_partitions)
num_remaining_clients = val.num_remaining_clients - num_clients_for_subround
num_remaining_partitions = val.num_remaining_partitions - 1
values_to_return = val.payload[val.last_client_index:val.last_client_index +
num_clients_for_subround]
last_client_index = val.last_client_index + num_clients_for_subround
return _PartitioningValue(
payload=values_to_return,
num_remaining_clients=num_remaining_clients,
num_remaining_partitions=num_remaining_partitions,
last_client_index=last_client_index)
else:
return val
def _split_value_into_subrounds(value: Any, type_spec: computation_types.Type,
num_desired_subrounds: int) -> List[Any]:
"""Partitions clients-placed values to subrounds, replicating other values.
This function should be applied to an argument of a computation which is
intended to be executed in subrounds; the semantics of this use case drive
the implementation of this function.
This function will return a list of values representing the appropriate
arguments to subrounds. Any value which is not CLIENTS-placed of not-all-equal
type will be replicated in the return value of this function. The returned
list will be up to `num_desired_subrounds` elements in length, possibly
shorter if the cardinality of clients represented by `value` is less than
`num_desired_subrounds`, to avoid constructing empty clients-placed arguments.
Args:
value: The argument to a computation intended to be invoked in subrounds,
which will be partitioned. `value` can be any structure understood by
TFF's native execution contexts.
type_spec: The `computation_types.Type` corresponding to `value`.
num_desired_subrounds: Int specifying the desired number of subrounds to
run. Specifies the maximum length of the returned list.
Returns:
A list of partitioned values as described above.
"""
cardinalities = cardinalities_utils.infer_cardinalities(value, type_spec)
if cardinalities.get(placements.CLIENTS) is None:
# The argument contains no clients-placed values, but may still perform
# nontrivial clients-placed work.
return [value for _ in range(num_desired_subrounds)]
elif cardinalities[placements.CLIENTS] == 0:
# Here the argument contains an empty clients-placed value; therefore this
# computation should be run over an empty set of clients.
return [value]
partitioning_value = _PartitioningValue(
payload=value,
num_remaining_clients=cardinalities[placements.CLIENTS],
num_remaining_partitions=num_desired_subrounds,
last_client_index=0)
values_to_return = []
for _ in range(num_desired_subrounds):
if partitioning_value.num_remaining_clients > 0:
partitioned_value = _partition_value(partitioning_value, type_spec)
values_to_return.append(partitioned_value.payload)
partitioning_value = _PartitioningValue(
partitioning_value.payload,
num_remaining_clients=partitioned_value.num_remaining_clients,
num_remaining_partitions=partitioned_value.num_remaining_partitions,
last_client_index=partitioned_value.last_client_index)
else:
# Weve already partitioned all the clients we can. The underlying
# execution contexts will fail if we pass them empty clients-placed
# values.
break
return values_to_return
def _repackage_partitioned_values(after_merge_results,
result_type_spec: computation_types.Type):
"""Inverts `_split_value_into_subrounds` above."""
py_typecheck.check_type(after_merge_results, list)
if result_type_spec.is_struct():
after_merge_structs = [
structure.from_container(x) for x in after_merge_results
]
result_container = []
for idx, (name, elem_type) in enumerate(
structure.iter_elements(result_type_spec)):
result_container.append(
(name,
_repackage_partitioned_values([x[idx] for x in after_merge_structs],
elem_type)))
return structure.Struct(result_container)
elif result_type_spec.is_federated(
) and result_type_spec.placement.is_clients():
if result_type_spec.all_equal:
return after_merge_results[0]
for x in after_merge_results:
py_typecheck.check_type(x, (list, tuple))
# Merges all clients-placed values back together.
return functools.reduce(lambda x, y: x + y, after_merge_results)
else:
return after_merge_results[0]
class MergeableCompExecutionContextValue(typed_object.TypedObject):
"""Represents a value embedded in the `MergeableCompExecutionContext`."""
def __init__(self, value: Any, type_spec: computation_types.Type,
num_desired_subrounds: int):
py_typecheck.check_type(type_spec, computation_types.Type)
self._type_signature = type_spec
self._partitioned_value = _split_value_into_subrounds(
value,
self._type_signature,
num_desired_subrounds=num_desired_subrounds)
@property
def type_signature(self):
return self._type_signature
def value(self):
return self._partitioned_value
async def _ingest_arg_or_none(arg, context, type_signature):
if arg is not None:
return await context.ingest(arg, type_signature)
return None
async def _invoke_up_to_merge_and_return_context(
comp: MergeableCompForm, arg,
context: async_execution_context.AsyncExecutionContext):
ingested_arg = await _ingest_arg_or_none(
arg, context, comp.up_to_merge.type_signature.parameter)
return await context.invoke(comp.up_to_merge, ingested_arg), context
async def _merge_results(
comp: MergeableCompForm, merge_partial, value_to_merge,
context: async_execution_context.AsyncExecutionContext):
ingested_arg = await context.ingest((merge_partial, value_to_merge),
comp.merge.type_signature.parameter)
return await context.invoke(comp.merge, ingested_arg)
async def _compute_after_merged(
comp: MergeableCompForm, original_arg, merge_result,
context: async_execution_context.AsyncExecutionContext):
if original_arg is not None:
ingested_arg = await context.ingest(
(original_arg, merge_result), comp.after_merge.type_signature.parameter)
else:
ingested_arg = await context.ingest(
merge_result, comp.after_merge.type_signature.parameter)
return await context.invoke(comp.after_merge, ingested_arg)
async def _invoke_mergeable_comp_form(
comp: MergeableCompForm, arg: Optional[MergeableCompExecutionContextValue],
execution_contexts: Sequence[
async_execution_context.AsyncExecutionContext]):
"""Invokes `comp` on `arg`, repackaging the results to a single value."""
if arg is not None:
arg_list = arg.value()
else:
arg_list = [None for _ in range(len(execution_contexts))]
up_to_merge_futures = asyncio.as_completed([
_invoke_up_to_merge_and_return_context(comp, x, context)
for x, context in zip(arg_list, execution_contexts)
])
# We compute merge using the most-recently completed context.
# TODO(b/195349085): merge in a hierarchical fashion here rather than
# linearly.
merge_result, merge_context = await next(up_to_merge_futures)
for up_to_merge_result_future in up_to_merge_futures:
to_merge, merge_context = await up_to_merge_result_future
merge_result = await _merge_results(comp, merge_result, to_merge,
merge_context)
if type_analysis.contains_only(comp.after_merge.type_signature.result,
lambda x: not x.is_federated() or x.all_equal):
# In this case, all contexts must return the same result, which must
# therefore be independent of which element in the arg_list is passed--so we
# avoid the extra work.
top_level_arg_slice = arg_list[0]
return await _compute_after_merged(comp, top_level_arg_slice, merge_result,
merge_context)
after_merge_results = await asyncio.gather(*[
_compute_after_merged(comp, x, merge_result, context)
for x, context in zip(arg_list, execution_contexts)
])
repackaged_values = _repackage_partitioned_values(
after_merge_results,
result_type_spec=comp.after_merge.type_signature.result)
return repackaged_values
class MergeableCompExecutionContext(context_base.Context):
"""Context which executes mergeable computations in subrounds.
This context relies on retrying behavior of the underlying asynchronous
execution contexts to localize retries to these subrounds. That is, if a
subround fails, this subround is the only computation that is retried. This
allows `MergeableCompExecutionContext` to execute larger rounds than a
runtime which retries the entire round in the case of e.g. a worker failure.
"""
def __init__(self,
executor_factories: Sequence[executor_factory.ExecutorFactory],
compiler_fn: Optional[Callable[[computation_base.Computation],
MergeableCompForm]] = None):
self._async_execution_contexts = [
async_execution_context.AsyncExecutionContext(ex_factory)
for ex_factory in executor_factories
]
self._event_loop = asyncio.new_event_loop()
if compiler_fn is not None:
self._compiler_pipeline = compiler_pipeline.CompilerPipeline(compiler_fn)
else:
self._compiler_pipeline = None
def ingest(self, val: Any, type_spec: computation_types.Type) -> Any:
# Delay wrapping as MergeableCompExecutionContextValue to ensure we split
# values only once.
return val
def invoke(self,
comp: Union[MergeableCompForm, computation_base.Computation],
arg: Optional[Any] = None):
py_typecheck.check_type(comp,
(MergeableCompForm, computation_base.Computation))
if isinstance(comp, computation_base.Computation):
if self._compiler_pipeline is None:
raise ValueError('Without a compiler, mergeable comp execution context '
'can only invoke instances of MergeableCompForm. '
'Encountered a `tff.Computation`.')
comp = self._compiler_pipeline.compile(comp)
if not isinstance(comp, MergeableCompForm):
raise ValueError('Expected compilation in mergeable comp execution '
'context to produce an instance of MergeableCompForm; '
f'found instead {comp} of Python type {type(comp)}.')
if arg is not None:
arg = MergeableCompExecutionContextValue(
arg, comp.up_to_merge.type_signature.parameter,
len(self._async_execution_contexts))
return type_conversions.type_to_py_container(
self._event_loop.run_until_complete(
_invoke_mergeable_comp_form(comp, arg,
self._async_execution_contexts)),
comp.after_merge.type_signature.result)
|
from django.db import models
# Create your models here.
from django.urls import reverse #Used to generate urls by reversing the URL patterns
class Genre(models.Model):
"""
Model representing a book genre (e.g. Science Fiction, Non Fiction).
"""
name = models.CharField(max_length=200, help_text="Enter a book genre (e.g. Science Fiction, French Poetry etc.)")
def __str__(self):
"""
String for representing the Model object (in Admin site etc.)
"""
return self.name
class Book(models.Model):
"""
Model representing a book (but not a specific copy of a book).
"""
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
# Foreign Key used because book can only have one author, but authors can have multiple books
# Author as a string rather than object because it hasn't been declared yet in file.
summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
isbn = models.CharField('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
# ManyToManyField used because a genre can contain many books and a Book can cover many genres.
# Genre class has already been defined so we can specify the object above.
def display_genre(self):
"""
Creates a string for the Genre. This is required to display genre in Admin.
"""
return ', '.join([ genre.name for genre in self.genre.all()[:3] ])
display_genre.short_description = 'Genre'
def get_absolute_url(self):
"""
Returns the url to access a particular book instance.
"""
return reverse('book-detail', args=[str(self.id)])
def __str__(self):
"""
String for representing the Model object.
"""
return self.title
import uuid # Required for unique book instances
from datetime import date
from django.contrib.auth.models import User #Required to assign User as a borrower
class BookInstance(models.Model):
"""
Model representing a specific copy of a book (i.e. that can be borrowed from the library).
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library")
book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
imprint = models.CharField(max_length=200)
due_back = models.DateField(null=True, blank=True)
borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
@property
def is_overdue(self):
if self.due_back and date.today() > self.due_back:
return True
return False
LOAN_STATUS = (
('d', 'Maintenance'),
('o', 'On loan'),
('a', 'Available'),
('r', 'Reserved'),
)
status= models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='d', help_text='Book availability')
class Meta:
ordering = ["due_back"]
permissions = (("get_all_users_info", "Set book as returned"),)
def __str__(self):
"""
String for representing the Model object.
"""
#return '%s (%s)' % (self.id,self.book.title)
return '{0} ({1})'.format(self.id,self.book.title)
class Author(models.Model):
"""
Model representing an author.
"""
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
date_of_death = models.DateField('died', null=True, blank=True)
class Meta:
ordering = ["last_name","first_name"]
def get_absolute_url(self):
"""
Returns the url to access a particular author instance.
"""
return reverse('author-detail', args=[str(self.id)])
def __str__(self):
"""
String for representing the Model object.
"""
return '{0}, {1}'.format(self.last_name,self.first_name)
|
import xml.etree.ElementTree as ET
##
# Get text field text identified by pattern 'column' in xmltree 'tree'
def getvalue( tree, column ):
try:
val = tree.iterfind(column).next()
return val.text
except:
return ""
def parsecofig(config_file):
return ET.parse(config_file)
class Configuration():
__remoteAdresses = dict()
def __init__(self, config_file):
self.tree = ET.parse(config_file)
self.__readRemoteSesors()
def __getRemoteSensorAdresses(self):
return None
def iterfind(self, column):
return self.tree.iterfind(column)
def getvalue( self, column):
try:
val = self.tree.iterfind(column).next()
return val.text
except:
return ""
def __readRemoteSesors(self):
remote = self.tree.iterfind("RemoteSensors").next()
for sensor in list(remote):
s = dict()
s['adress'] = getvalue(sensor, "adress")
s['name'] = getvalue(sensor, "name")
s['id'] = getvalue(sensor, "id")
self.__remoteAdresses[s['adress']] = s
def getSesorByAdress(self, adress):
return self.__remoteAdresses.get(adress, None)
# return self.__remoteAdresses[adress]
# Configuration
#config_file = '../cfg/config.xml'
#cfg = parsecofig(config_file)
#for child in cfg.iterfind('sensors/sensor'):
# print child.iterfind('id').next().text
# print child.iterfind('name').next().text
# print child.iterfind('device').next().text
|
from tensorflow.keras import layers, models
def VGG16(include_top=True,
input_shape=(224, 224, 3),
pooling=None,
classes=1000):
img_input = layers.Input(shape=input_shape)
# Block 1
x = layers.Conv2D(64, (3, 3),
activation='relu',
padding='same',
name='block1_conv1')(img_input)
x = layers.Conv2D(64, (3, 3),
activation='relu',
padding='same',
name='block1_conv2')(x)
x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
# Block 2
x = layers.Conv2D(128, (3, 3),
activation='relu',
padding='same',
name='block2_conv1')(x)
x = layers.Conv2D(128, (3, 3),
activation='relu',
padding='same',
name='block2_conv2')(x)
x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)
# Block 3
x = layers.Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv1')(x)
x = layers.Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv2')(x)
x = layers.Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv3')(x)
x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)
# Block 4
x = layers.Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv1')(x)
x = layers.Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv2')(x)
x = layers.Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv3')(x)
x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)
# Block 5
x = layers.Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv1')(x)
x = layers.Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv2')(x)
x = layers.Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv3')(x)
x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)
if include_top:
# Classification block
x = layers.Flatten(name='flatten')(x)
x = layers.Dense(4096, activation='relu', name='fc1')(x)
x = layers.Dense(4096, activation='relu', name='fc2')(x)
x = layers.Dense(classes, activation='softmax', name='predictions')(x)
else:
if pooling == 'avg':
x = layers.GlobalAveragePooling2D()(x)
elif pooling == 'max':
x = layers.GlobalMaxPooling2D()(x)
# Create model.
model = models.Model(img_input, x, name='vgg16')
return model
if __name__ == '__main__':
mod = VGG16()
print(mod.summary())
|
import numpy as np
from src.data.DataBase import DataBase
from src.vectoring.VectorBuilderBase import VectorBuilderBase
class ImageVectorBuilder(VectorBuilderBase):
def __init__(self, extracted_data: DataBase):
extracted_data.assert_is_extracted()
self.__data__ = extracted_data
self.__labels_c__ = len(self.__data__.labels)
def build_img_vector(self, img_id):
vec = np.zeros(self.__labels_c__)
index = self.__data__.rows_img_id.index(img_id)
row_labels = self.__data__.rows_labels[index]
row_scores = self.__data__.rows_scores[index]
for label_i, label in enumerate(row_labels):
score = row_scores[label_i]
label_vec_ind = self.__data__.labels.index(label)
old_score = vec[label_vec_ind]
vec[label_vec_ind] = max(old_score, score)
return np.array(vec)
def build_vector(self, segment):
resulting_vector = np.zeros(self.__labels_c__)
for img_id in segment:
vec = self.build_img_vector(img_id)
resulting_vector = np.array([max(vec[i], resulting_vector[i]) for i in range(self.__labels_c__)])
return resulting_vector
|
const Counter = require('../../models/Counter');
module.exports = (app) => {
console.log('server get /api/counters');
app.get('/api/counters', (req, res, next) => {
Counter.find()
.exec()
.then((counter) => res.json(counter))
.catch((err) => next(err));
});
app.post('/api/counters', function (req, res, next) {
const counter = new Counter();
console.log(' server post /api/counters ')
counter.save()
.then(() => res.json(counter))
.catch((err) => next(err));
});
app.delete('/api/counters/:id', function (req, res, next) {
Counter.findOneAndRemove({ _id: req.params.id })
.exec()
.then((counter) => res.json())
.catch((err) => next(err));
});
app.put('/api/counters/:id/increment', (req, res, next) => {
console.log('server put increment ');
Counter.findById(req.params.id)
.exec()
.then((counter) => {
counter.count++;
counter.save()
.then(() => res.json(counter))
.catch((err) => next(err));
})
.catch((err) => next(err));
});
app.put('/api/counters/:id/decrement', (req, res, next) => {
Counter.findById(req.params.id)
.exec()
.then((counter) => {
counter.count--;
counter.save()
.then(() => res.json(counter))
.catch((err) => next(err));
})
.catch((err) => next(err));
});
};
|
import numpy
def gaussmf (x, params):
if not isinstance(params, list):
raise TypeError ("Params should be a list with two values.")
if len(params) != 2:
raise TypeError ("Number of parameters are incorrect. Expected 2 values in the list.")
if not (isinstance(params[0], float) and isinstance(params[1], float)):
raise TypeError ("Parameters should be in float.")
c = params[0]
sigma = params[1]
return numpy.exp(-((x-c)**2)/(2*sigma**2))
|
import astropy.io.fits as fits
import numpy as np
import pylab as pl
from astropy.table import Table, join, vstack
from scipy.ndimage.filters import gaussian_filter
from desitarget.cmx import cmx_targetmask
# Coma on petal 0 of 70510.
tiles = {'mws': 66003, 'bgs': 66003, 'elg': 67230, 'lrg': 68002, 'qso': 68002}
allids = []
petals = [9]
for tracer, band in zip(['mws'], ['B']):
for petal in petals:
zbest = Table.read('../../../andes/zbest-{}-{}-20200315.fits'.format(petal, tiles[tracer]))
coadd = fits.open('../../../andes/coadd-{}-{}-20200315.fits'.format(petal, tiles[tracer]))
assert np.all(coadd['FIBERMAP'].data['TARGETID'] == zbest['TARGETID'])
tinfo = Table(coadd['FIBERMAP'].data)
# tinfo = tinfo['TARGETID', 'FLUX_G', 'FLUX_R', 'FLUX_Z', 'CMX_TARGET', 'TARGET_RA', 'TARGET_DEC']
zbest = join(zbest, tinfo, join_type='left', keys='TARGETID')
zbest = zbest[(zbest['CMX_TARGET'] & cmx_targetmask.cmx_mask.mask('SV0_WD')) != 0]
zbest = zbest[(zbest['SPECTYPE'] == 'STAR')]
print(petal, len(zbest))
dChs = zbest['DELTACHI2']
# rank = np.argsort(dChs)
# lcut = np.percentile(dChs[rank], 60)
# hcut = np.percentile(dChs[rank], 95)
# cut = (dChs[rank] > lcut) & (dChs[rank] < hcut)
# zs = zbest[rank][cut]
# zs.sort('TARGETID')
# for x in ['NPIXELS', 'NUMEXP', 'NUMTILE', 'NCOEFF']:
# del zs[x]
zs = zbest
assert np.all(zs['ZWARN'] == 0)
# Limit number of rows.
zs = zs[:5]
print('\n\n')
print(zs)
zs.write('../student_andes/zbest-{}-{}-20200315-wd.fits'.format(tracer, tiles[tracer]), format='fits', overwrite=True)
tids = zs['TARGETID']
allids += tids.tolist()
isin = np.isin(coadd['FIBERMAP'].data['TARGETID'], tids)
assert np.all(coadd['FIBERMAP'].data['TARGETID'][isin] == tids)
wave = []
flux = []
for arm in ["B", "R", "Z"]:
wave += coadd['{:s}_WAVELENGTH'.format(arm)].data.tolist()
flux += coadd['{:s}_FLUX'.format(arm)].data[isin].T.tolist()
wave = np.array(wave)
rank = np.argsort(wave)
wave = wave[rank]
flux = np.array(flux)
flux = flux[rank, :]
for i, x in enumerate(flux.T):
flux[:,i] = gaussian_filter(x, 3)
pl.clf()
pl.plot(wave, flux, lw=1.0)
pl.show()
result = Table()
result['WAVELENGTH'] = wave
for i, x in enumerate(flux.T):
result['TARGET{:d}'.format(tids[i])] = flux[:,i]
# print(result)
result.write('../student_andes/coadd-{}-{}-20200315-wd.fits'.format(tracer, tiles[tracer]), format='fits', overwrite=True)
print(allids)
# Append by hand to all target ids in student andes.
print('\n\nDone.\n\n')
|
"""Common configure functions for bgp"""
# Python
import logging
import re
# Unicon
from unicon.core.errors import SubCommandFailure
log = logging.getLogger(__name__)
def configure_l2vpn_storm_control(
device, interface, service_instance_id, storm_control
):
""" Configures storm control under service instance
Args:
device('obj'): device to configure
interface('str'): interface name
service_instance_id:('int'): service instance id
storm_control('list'): list of storm control configurations
ex.)
[
{
'traffic_flow': 'unicast',
'name': 'cir',
'val': 8000
},
{
'traffic_flow': 'broadcast',
'name': 'cir',
'val': 8000
},
{
'traffic_flow': 'multicast',
'name': 'cir',
'val': 8000
}
]
Returns:
N/A
Raises:
SubCommandFailure
"""
log.info(
"Configuring storm control under service "
"instance: {} and interface: {}".format(service_instance_id, interface)
)
config = []
config.append("interface {}\n".format(interface))
config.append("service instance {} ethernet\n".format(service_instance_id))
for sc in storm_control:
traffic_flow = sc["traffic_flow"]
name = sc["name"]
val = sc["val"]
config.append(
"storm-control {} {} {}\n".format(traffic_flow, name, val)
)
try:
device.configure("".join(config))
except SubCommandFailure as e:
raise SubCommandFailure(
"Configuration failed for storm control under service "
"instance: {} and interface: {} with exception: {}".format(
service_instance_id, interface, str(e)
)
)
|
import debugModule from "debug";
const debug = debugModule("debugger:stacktrace:selectors");
import { createSelectorTree, createLeaf } from "reselect-tree";
import solidity from "lib/solidity/selectors";
import jsonpointer from "json-pointer";
import zipWith from "lodash.zipwith";
import { popNWhere } from "lib/helpers";
const identity = x => x;
function generateReport(rawStack, location, status) {
//step 1: process skipped frames
let callstack = [];
//we're doing a C-style loop here!
//because we want to skip some items <grin>
for (let i = 0; i < rawStack.length; i++) {
const frame = rawStack[i];
if (
frame.skippedInReports &&
i < rawStack.length - 1 &&
rawStack[i + 1].type === "internal"
) {
const combinedFrame = {
...rawStack[i + 1],
calledFromLocation: frame.calledFromLocation
};
callstack.push(combinedFrame);
i++; //!! SKIP THE NEXT FRAME!
} else {
//ordinary case: just push the frame
callstack.push(frame);
}
}
debug("callstack: %O", callstack);
//step 2: shift everything over by 1 and recombine :)
let locations = callstack.map(frame => frame.calledFromLocation);
//remove initial null, add final location on end
locations.shift();
locations.push(location);
debug("locations: %O", locations);
const names = callstack.map(({ functionName, contractName }) => ({
functionName,
contractName
}));
debug("names: %O", names);
let report = zipWith(locations, names, (location, nameInfo) => ({
...nameInfo,
location
}));
//finally: set the status in the top frame
if (status !== null) {
report[report.length - 1].status = status;
}
return report;
}
function createMultistepSelectors(stepSelector) {
return {
/**
* .location
*/
location: {
/**
* .source
*/
source: createLeaf([stepSelector.source], identity),
/**
* .sourceRange
*/
sourceRange: createLeaf([stepSelector.sourceRange], identity),
/**
* .node
*/
node: createLeaf([stepSelector.node], identity),
/**
* .pointer
*/
pointer: createLeaf([stepSelector.pointer], identity)
},
/**
* .strippedLocation
*/
strippedLocation: createLeaf(
["./location/source", "./location/sourceRange"],
({ id, compilationId, sourcePath }, sourceRange) => ({
source: { id, compilationId, sourcePath },
sourceRange
})
),
/**
* .contractNode
* WARNING: ad-hoc selector only meant to be used
* when you're on a function node!
* should probably be replaced by something better;
* the data submodule handles these things a better way
*/
contractNode: createLeaf(
["./location/source", "./location/pointer"],
({ ast }, pointer) =>
pointer
? jsonpointer.get(
ast,
pointer.replace(/\/nodes\/\d+$/, "") //cut off end
)
: ast
)
};
}
let stacktrace = createSelectorTree({
/**
* stacktrace.state
*/
state: state => state.stacktrace,
/**
* stacktrace.transaction
*/
transaction: {
/**
* stacktrace.transaction.bottomFrameIsSkippedInReports
*/
bottomFrameIsSkippedInReports: createLeaf(
[solidity.transaction.bottomStackframeRequiresPhantomFrame],
identity
)
},
/**
* stacktrace.current
*/
current: {
/**
* stacktrace.current.callstack
*/
callstack: createLeaf(["/state"], state => state.proc.callstack),
/**
* stacktrace.current.returnCounter
*/
returnCounter: createLeaf(["/state"], state => state.proc.returnCounter),
/**
* stacktrace.current.lastPosition
*/
lastPosition: createLeaf(["/state"], state => state.proc.lastPosition),
/**
* stacktrace.current.innerReturnPosition
*/
innerReturnPosition: createLeaf(
["/state"],
state => state.proc.innerReturnPosition
),
/**
* stacktrace.current.innerReturnStatus
*/
innerReturnStatus: createLeaf(
["/state"],
state => state.proc.innerReturnStatus
),
...createMultistepSelectors(solidity.current),
/**
* stacktrace.current.willJumpIn
*/
willJumpIn: createLeaf(
[solidity.current.willJump, solidity.current.jumpDirection],
(willJump, jumpDirection) => willJump && jumpDirection === "i"
),
/**
* stacktrace.current.willJumpOut
*/
willJumpOut: createLeaf(
[solidity.current.willJump, solidity.current.jumpDirection],
(willJump, jumpDirection) => willJump && jumpDirection === "o"
),
/**
* stacktrace.current.willCall
* note: includes creations!
*/
willCall: createLeaf([solidity.current.willCall], identity),
/**
* stacktrace.current.nextFrameIsSkippedInReports
*/
nextFrameIsSkippedInReports: createLeaf(
[solidity.current.callRequiresPhantomFrame],
identity
),
/**
* stacktrace.current.willReturn
*/
willReturn: createLeaf([solidity.current.willReturn], identity),
/**
* stacktrace.current.willFail
*/
willFail: createLeaf([solidity.current.willFail], identity),
/**
* stacktrace.current.willReturnOrFail
*/
willReturnOrFail: createLeaf(
["./willReturn", "./willFail"],
(willReturn, willFail) => willReturn || willFail
),
/**
* stacktrace.current.returnStatus
*/
returnStatus: createLeaf(["./willReturn", "./willFail"], (returns, fails) =>
returns ? true : fails ? false : null
),
/**
* stacktrace.current.positionWillChange
*/
positionWillChange: createLeaf(
["/next/location", "/current/location", "./lastPosition"],
(nextLocation, currentLocation, lastLocation) => {
let oldLocation =
currentLocation.source.id !== undefined
? currentLocation
: lastLocation;
return (
Boolean(oldLocation) && //if there's no current or last position, we don't need this check
Boolean(nextLocation.source) &&
nextLocation.source.id !== undefined && //if next location is unmapped, we consider ourselves to have not moved
(nextLocation.source.compilationId !==
oldLocation.source.compilationId ||
nextLocation.source.id !== oldLocation.source.id ||
nextLocation.sourceRange.start !== oldLocation.sourceRange.start ||
nextLocation.sourceRange.length !== oldLocation.sourceRange.length)
);
}
),
/**
* stacktrace.current.finalReport
* Contains the report object for outside consumption.
* Still needs to be processed into a string, mind you.
*/
finalReport: createLeaf(
["./callstack", "./innerReturnPosition", "./innerReturnStatus"],
(callstack, finalLocation, status) =>
generateReport(callstack, finalLocation, status)
),
/**
* stacktrace.current.report
* Similar to stacktrace.current.report, but meant for use as at
* an intermediate point instead of at the end (it reflects how things
* actually currently are rather than taking into account exited
* stackframes that caused the revert)
*/
report: createLeaf(
[
"./callstack",
"./returnCounter",
"./lastPosition",
"/current/strippedLocation"
],
(callstack, returnCounter, lastPosition, currentLocation) =>
generateReport(
popNWhere(
callstack,
returnCounter,
frame => frame.type === "external"
),
currentLocation || lastPosition,
null
)
)
},
/**
* stacktrace.next
*/
next: {
...createMultistepSelectors(solidity.next)
}
});
export default stacktrace;
|
from gevent import monkey; monkey.patch_all()
import gevent
from socketio import socketio_manage
from socketio.server import SocketIOServer
from socketio.namespace import BaseNamespace
from socketio.mixins import RoomsMixin, BroadcastMixin
from twisted.internet import reactor, task, defer
from twisted.python import log
from peerlyDB.network import Server
import sys, signal
from p2p import P2PNamespace
log.startLogging(sys.stdout)
class Application(object):
def __init__(self, port=8469):
self.buffer = []
# Dummy request object to maintain state between Namespace
# initialization.
server = Server()
server.listen(port)
self.request = {
'queries': {},
'kadServer' : server,
'inserts' : {},
'port' : port,
'bootstraped' : False
}
gevent.spawn(self.startReactor)
def startReactor(self):
gevent.sleep(1)
reactor.run()
signal.signal(signal.SIGINT, signal.default_int_handler)
def __call__(self, environ, start_response):
path = environ['PATH_INFO'].strip('/')
if not path:
start_response('200 OK', [('Content-Type', 'text/html')])
return [open('peerlyApp/web/peerly.html').read()]
#return ['<h1>Welcome. '
# 'Try the <a href="/chat.html">chat</a> example.</h1>']
if path.startswith('static/') or path == 'peerly.html':
try:
data = open('peerlyApp/web/'+path).read()
except Exception:
return not_found(start_response)
if path.endswith(".js"):
content_type = "text/javascript"
elif path.endswith(".css"):
content_type = "text/css"
elif path.endswith(".swf"):
content_type = "application/x-shockwave-flash"
else:
content_type = "text/html"
start_response('200 OK', [('Content-Type', content_type)])
return [data]
if path.startswith("socket.io"):
socketio_manage(environ, {'': P2PNamespace}, self.request)
else:
return not_found(start_response)
def not_found(start_response):
start_response('404 Not Found', [])
return ['<h1>Not Found</h1>']
|
const express = require('express')
const router = express.Router()
const User = require('../../models/user')
const Chapter = require('../../models/chapter')
const Book = require('../../models/book')
const CurrentlyReading = require('../../models/currentlyReading')
const Badge = require('../../models/badge')
const UserBadge = require('../../models/userBadge')
const ReadingHistory = require('../../models/readingHistory')
const requireAuth = require('passport').authenticate('jwt', {session: false})
/**
* @swagger
* definitions:
* CurrentlyReading:
* properties:
* book:
* type: "string"
* chapterTrail:
* type: "array"
* items:
* type: "string"
*/
/**
* @swagger
* definitions:
* User:
* properties:
* fullName:
* type: "string"
* email:
* type: "string"
* password:
* type: "string"
* created:
* type: "Date"
* role:
* type: "string"
* resetPasswordToken:
* type: "string"
* resetPasswordExpires:
* type: "Date"
*/
/**
* @swagger
* definitions:
* PasswordUser:
* properties:
* oldPassword:
* type: string
* newPassword:
* type: string
*/
/**
* @swagger
* definitions:
* Count:
* properties:
* wordCount:
* type: number
*/
/**
* @swagger
* definitions:
* ReadingHistory:
* properties:
* bookId:
* type: "string"
* edgeIds:
* type: "array"
* items:
* type: string
* userId:
* type: string
*/
/**
* @swagger
* /users/{id}/wordcount:
* get:
* tags:
* - wordcount chapters user
* description:
* - returns the total number of words the user has written
* produces:
* - application/json
* parameters:
* -
* name: "id"
* in: "path"
* description: "User Id"
* required: true
* type: "string"
* responses:
* 200:
* description: A wordcount object
* schema:
* $ref: '#/definitions/Count'
*/
router.get('/:id/wordcount', (req, res) => {
const userId = req.params['id']
Chapter
.aggregate([
{$match: {author: userId}},
{
$group: {
_id: null,
total: {
$sum: '$wordCount'
}
}
}
], (err, wordCount) => {
if (err) {
res.status(500).send({})
} else if (wordCount && wordCount.length) {
res.send({count: wordCount[0].total})
} else {
res.status(500).send({})
}
})
})
/**
* @swagger
* /users/self/currentlyreading/{bookId}:
* get:
* tags:
* - currentlyreading user
* description:
* - Returns the currently-reading object from the logged in user
* with the specified bookid
* produces:
* - application/json
* parameters:
* -
* name: "bookId"
* in: "path"
* description: "Book Id"
* required: true
* type: "string"
* responses:
* 200:
* description: A currently-reading object
* schema:
* $ref: '#/definitions/CurrentlyReading'
*
*/
router.get('/self/currentlyreading/:bookId', requireAuth, (req, res) => {
User.findOne(
{
'_id': req.user._id, 'currentlyReading.book': req.params.bookId,
},
{
currentlyReading: {$elemMatch: {book: req.params.bookId}},
},
(err, user) => {
if (err) {
res.sendStatus(500)
} else {
if (user && user.currentlyReading.length) {
res.send(user.currentlyReading[0])
} else {
res.sendStatus(204)
}
}
})
})
/**
* @swagger
* /users/self/currentlyreading:
* get:
* tags:
* - currentlyreading
* description:
* - Returns all the currently-reading objects from the logged in user
* produces:
* - application/json
* responses:
* 200:
* description: An array of currently-reading objects
* schema:
* $ref: '#/definitions/CurrentlyReading'
*
*/
router.get('/self/currentlyreading', requireAuth, (req, res) => {
User.findOne(
{
_id: req.user._id,
},
(err, user) => {
if (err) {
res.status(500).send({})
} else {
if (user) {
res.send(user.currentlyReading)
} else {
res.send([])
}
}
})
})
/**
* @swagger
* /users/self/readinghistory:
* get:
* tags:
* - readinghistory
* description:
* - Returns all the readinghistory objects from the logged in user
* produces:
* - application/json
* responses:
* 200:
* description: An array of readinghistory objects
* schema:
* $ref: '#/definitions/ReadingHistory'
*
*/
router.get('/self/readinghistory', requireAuth, (req, res) => {
const userId = req.user._id
ReadingHistory.find({'userId': userId}, (err, history) => {
if (err) {
res.status(500).send({})
} else {
res.send(history)
}
}
)
})
/**
* @swagger
* /users/self/readinghistory/{bookId}:
* get:
* tags:
* - readinghistory
* description:
* - Returns the readinghistory object belonging to book with id bookId from the logged in user
* produces:
* - application/json
* parameters:
* -
* name: "bookId"
* in: "path"
* description: "Book Id"
* required: true
* type: "string"
* responses:
* 200:
* description: A readinghistory objects
* schema:
* $ref: '#/definitions/ReadingHistory'
*
*/
router.get('/self/readinghistory/:bookId', requireAuth, (req, res) => {
const userId = req.user._id
const bookId = req.params['bookId']
ReadingHistory.findOne({'userId': userId, 'bookId': bookId}, (err, history) => {
if (err) {
res.status.send({})
} else if(!history) {
res.send({})
} else {
res.send(history)
}
}
)
})
/**
* @swagger
* /users/self/readinghistory:
* put:
* tags:
* - CurrentlyReading
* description:
* - "Receives a ReadingHistory object and adds
* it to the currently reading array of the user logged in. If it already
* exists it gets updated"
* produces:
* - application/json
* responses:
* 200:
* description: "200 when successfully updated"
* 500:
* description: "500 when there was an error"
*/
router.put('/self/readinghistory', requireAuth, (req, res) => {
let readingHistory = new ReadingHistory(req.body)
let userId = req.user._id
readingHistory.userId = userId
ReadingHistory.findOneAndUpdate(
{
'userId': userId,
'bookId': readingHistory.bookId,
},
{
chapterIds: readingHistory.chapterIds
},
{
upsert: true,
new: true
},
(err, readinghistory) => {
if (err) {
console.log(err)
res.status(500).send({})
} else {
res.status(201).send(readinghistory)
}
})
})
/**
* @swagger
* /users/{id}:
* get:
* tags:
* - user
* description:
* - Returns the user with the specified ID
* produces:
* - application/json
* parameters:
* -
* name: "id"
* in: "path"
* description: "User Id"
* required: true
* type: "string"
* responses:
* 200:
* description: A user object
* schema:
* $ref: '#/definitions/User'
*
*/
router.get('/:id', (req, res) => {
User.findOne(
{
_id: req.params['id'],
},
['-currentlyReading', '-password', '-created'],
(err, user) => {
if (err) {
res.status(500).send({})
} else {
res.send(user)
}
})
})
/**
* @swagger
* /users/{id}/chapters:
* get:
* tags:
* - user chapters
* description:
* - Returns the chapters written by the user with the given id
* produces:
* - application/json
* parameters:
* -
* name: "id"
* in: "path"
* description: "User Id"
* required: true
* type: "string"
* responses:
* 200:
* description: An array of chapter objects
* schema:
* $ref: '#/definitions/Chapter'
*
*/
router.get('/:id/chapters', (req, res) => {
let userId = req.params['id']
Chapter.find(
{
deleted: false,
author: userId,
published: true
},
(err, chapters) => {
if (err) {
res.status(500).send([])
} else {
res.send(chapters)
}
}
)
})
/**
* @swagger
* /users/{id}/chapters:
* get:
* tags:
* - user chapters count
* description:
* - Returns the number of chapters a user has written
* produces:
* - application/json
* parameters:
* -
* name: "id"
* in: "path"
* description: "User Id"
* required: true
* type: "string"
* responses:
* 200:
* description: The chapter count
* schema:
* $ref: '#/definitions/Count'
*
*/
router.get('/:id/chapters/count', (req, res) => {
let userId = req.params['id']
Chapter.count(
{
deleted: false,
author: userId,
published: true
},
(err, count) => {
if (err) {
res.status(500).send([])
} else {
res.send({count: count})
}
}
)
})
/**
* @swagger
* /users/{id}/books:
* get:
* tags:
* - user books
* description:
* - Returns the books written by the user with the given id
* produces:
* - application/json
* parameters:
* -
* name: "id"
* in: "path"
* description: "User Id"
* required: true
* type: "string"
* responses:
* 200:
* description: An array of book objects
* schema:
* $ref: '#/definitions/Book'
*
*/
router.get('/:id/books', (req, res) => {
let userId = req.params['id']
Book.find({
$or: [{
'creator': userId,
'deleted': false,
},
{
'author.id': userId,
'deleted': false
}]
},
(err, books) => {
if (err) {
res.status(500).send([])
} else {
res.send(books)
}
}
)
})
/**
* @swagger
* /users/{id}/books/count:
* get:
* tags:
* - user books
* description:
* - Returns the number of books a user has created
* produces:
* - application/json
* parameters:
* -
* name: "id"
* in: "path"
* description: "User Id"
* required: true
* type: "string"
* responses:
* 200:
* description: The bookcount
* schema:
* $ref: '#/definitions/Count'
*
*/
router.get('/:id/books/count', (req, res) => {
let userId = req.params['id']
Book.count({
$or: [{
'creator': userId,
'deleted': false,
},
{
'author.id': userId,
'deleted': false
}]
},
(err, count) => {
if (err) {
res.status(500).send([])
} else {
res.send({count: count})
}
}
)
})
/**
* @swagger
* /users/{id}/badges:
* get:
* tags:
* - user badges
* description:
* - Returns the badges gotten by the user
* produces:
* - application/json
* parameters:
* -
* name: "id"
* in: "path"
* description: "User Id"
* required: true
* type: "string"
* responses:
* 200:
* description: An array of badge objects
* schema:
* $ref: '#/definitions/Badge'
*
*/
router.get('/:id/badges', (req, res) => {
let userId = req.params['id']
UserBadge.find({
user_id: userId
},
(err, userBadges) => {
if (!err) {
let badgeIds = userBadges.map(ub => ub.badge_id)
Badge.find({
_id: {$in: badgeIds}
}, (err, badges) => {
if (err) {
res.status(500).send({})
} else {
res.send(badges)
}
})
}
}
)
})
/**
* @swagger
* /users/self/currentlyreading:
* put:
* tags:
* - CurrentlyReading
* description:
* - "Receives a currently reading object and adds
* it to the currently reading array of the user logged in. If it already
* exists it gets updated"
* produces:
* - application/json
* responses:
* 200:
* description: "20 when successfully updated"
* 500:
* description: "500 when there was an error"
*/
router.put('/self/currentlyreading', requireAuth, (req, res) => {
let currentlyReading = new CurrentlyReading(req.body)
User.findOneAndUpdate(
{
'_id': req.user._id,
'currentlyReading.book': currentlyReading.book,
},
{
'$set': {
'currentlyReading.$': currentlyReading,
},
},
{
upsert: true,
},
(err, user) => {
if (err) {
User.findOne({_id: req.user._id}, (err, user) => {
if (err) {
res.status(500).send({})
} else {
user.currentlyReading.push(currentlyReading)
user.save()
res.status(200).send({})
}
})
} else {
res.status(200).send({})
}
})
})
/**
* @swagger
* /users:
* put:
* tags:
* - users
* description: "Modifies the logged in user"
* produces:
* - application/json
* responses:
* 200:
* description: "The old user object"
* schema:
* $ref: '#/definitions/User'
* 500:
* description: "500 when there was an error"
*/
router.put('/', requireAuth, (req, res) => {
let loggedInUser = req.user
let updatedUser = new User(req.body)
if (loggedInUser._id != updatedUser._id) {
res.status(403).send({})
} else {
User.findOneAndUpdate(
{_id: loggedInUser._id},
{
bio: updatedUser.bio,
fullName: updatedUser.fullName,
penName: updatedUser.penName
}, (err, oldUser) => {
if (err) {
res.status(500).send({})
} else {
let penName = updatedUser.penName || updatedUser.fullName
Book.update({'author.id': loggedInUser._id}, {'author.penName': penName}, {multi: true}, (err, books) => {
res.send(oldUser)
}
)
}
}
)
}
})
/**
* @swagger
* /users/changepass:
* put:
* tags:
* - users
* description: Creates a new password for the logged in user
* produces:
* - application/json
* responses:
* 200:
* description: "The updated user"
* schema:
* $ref: '#/definitions/PasswordUser'
* 500:
* description: "500 when there was an error"
*/
router.put('/changepass', requireAuth, (req, res) => {
//if oldPassword field is correct then update
let oldPassword = req.body.oldPassword
let newPassword = req.body.newPassword
console.log(oldPassword)
User.findOne({_id: req.user._id}, (err, user) => {
if (err) {
console.log('fusste error')
res.status(500).send({})
} else {
user.comparePassword(oldPassword, function (err, isMatch) {
if (err) {
console.log('andre error')
console.log(err)
res.status(403).send({})
}
else if (!isMatch) {
return res.status(403).send({})
} else {
if (newPassword.length < 3) {
console.log('ikke langt nok')
res.status(500).send({})
} else {
user.password = newPassword
user.save((err, user) => {
if (err) {
console.log('saving error')
res.status(500).send({})
} else {
res.send(user)
}
})
}
}
})
}
})
})
module.exports = router
|
/*
* Copyright 2017-2021 EPAM Systems, Inc. (https://www.epam.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import {
Button,
Modal,
Form,
Input,
Row,
Spin
} from 'antd';
import PropTypes from 'prop-types';
@Form.create()
class RevertCommitForm extends React.Component {
formItemLayout = {
labelCol: {
xs: {span: 24},
sm: {span: 6}
},
wrapperCol: {
xs: {span: 24},
sm: {span: 18}
}
};
handleSubmit = (e) => {
const {onRevert, form} = this.props;
e.preventDefault();
form.validateFieldsAndScroll((err, values) => {
if (!err) {
onRevert && onRevert(values);
}
});
};
render () {
const {
path,
commit,
form,
pending,
onCancel,
visible
} = this.props;
const {getFieldDecorator, resetFields} = form;
const modalFooter = pending ? false : (
<Row>
<Button onClick={onCancel}>Cancel</Button>
<Button type="primary" htmlType="submit" onClick={this.handleSubmit}>Revert</Button>
</Row>
);
const onClose = () => resetFields();
const objectName = (path || '').split(/[\\/]/).pop();
return (
<Modal
maskClosable={!pending}
afterClose={() => onClose()}
closable={!pending}
visible={visible}
title={
objectName
? (<span>Revert <b>{objectName}</b> to revision <b>{commit}</b></span>)
: undefined
}
onCancel={onCancel}
footer={objectName ? modalFooter : undefined}
>
<Spin spinning={pending}>
<Form>
<Form.Item
{...this.formItemLayout}
label="Comment"
>
{getFieldDecorator('comment')(
<Input
ref={this.initializeCommentInput}
disabled={pending}
onPressEnter={this.handleSubmit}
type="textarea"
/>
)}
</Form.Item>
</Form>
</Spin>
</Modal>
);
}
initializeCommentInput = (input) => {
if (input && input.refs && input.refs.input) {
this.commentInput = input.refs.input;
this.commentInput.onfocus = function () {
setTimeout(() => {
this.selectionStart = (this.value || '').length;
this.selectionEnd = (this.value || '').length;
}, 0);
};
}
};
focusCommentInput = () => {
if (this.props.visible && this.commentInput) {
setTimeout(() => {
this.commentInput.focus();
}, 0);
}
};
componentDidUpdate (prevProps) {
if (prevProps.visible !== this.props.visible) {
this.focusCommentInput();
}
}
}
RevertCommitForm.propTypes = {
onCancel: PropTypes.func,
onRevert: PropTypes.func,
pending: PropTypes.bool,
visible: PropTypes.bool,
path: PropTypes.string,
commit: PropTypes.string,
};
export default RevertCommitForm;
|
/*
django-inline-formset.js
@author Benjamin W Stookey
https://github.com/jamstooks/jquery-django-inline-form
*/
!function($) {
$.fn.djangoInlineFormAdd = function(options) {
if(options.prefix != undefined) {
this.prefix = options.prefix;
this.containerId = '#' + this.prefix + '-container';
this.templateId = '#' + this.prefix + '-template';
this.totalFormsId = '#id_' + this.prefix + '-TOTAL_FORMS';
this.maxFormsId = '#id_' + this.prefix + '-MAX_NUM_FORMS';
this.deleteButtonId = '#' + this.prefix + '-delete';
}
else {
if( options.containerId == undefined ||
options.templateId == undefined ||
options.totalFormsId == undefined ||
options.maxFormsId == undefined
){
console.error("[djangoInlineForm] if prefix is not provided in options, containerId, templateId, totalFormsId, and maxFormsId must be");
return;
}
}
// even if a prefix is defined, ids may change
this.containerId = options.containerId != undefined ? options.containerId : this.containerId;
this.templateId = options.templateId != undefined ? options.templateId : this.templateId;
this.totalFormsId = options.totalFormsId != undefined ? options.totalFormsId : this.totalFormsId;
this.maxFormsId = options.maxFormsId != undefined ? options.maxFormsId : this.maxFormsId;
this.deleteButtonId = options.deleteButtonId != undefined ? options.deleteButtonId : this.deleteButtonId;
this.postClick = options.postClick != undefined ? options.postClick : null;
this.formHeight = options.formHeight != undefined ? options.formHeight : null;
var max = $(this.maxFormsId).attr('value');
var self = this;
this.addForm = function(ev) {
ev.preventDefault();
var count = $(self.containerId).children().length;
if (count >= max) {
console.log('exceeded max inline forms'); // should maybe have a callback option
return;
}
var tmplMarkup = $(self.templateId).html();
var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
$(self.containerId).append(compiledTmpl);
// run postClick method
if (self.postClick != null) { self.postClick(); }
// animate it
$(self.containerId).children().last().show('slow');
// update form count
$(self.totalFormsId).attr('value', count+1);
// some animate to scroll to view our new form
if(self.formHeight != null) {
$('html, body').animate({
scrollTop: $(window).scrollTop() + self.formHeight
}, 800);
}
};
this.removeForm = function(ev) {
$(self.containerId).children().last().hide('slow', function(){
$(self.containerId).children().last().remove();
$(self.totalFormsId).attr('value', $(self.containerId).children().length);
});
// some animate to scroll up
if(self.formHeight != null) {
$('html, body').animate({
scrollTop: $(window).scrollTop() - self.formHeight
}, 800);
}
}
this.click(this.addForm);
if(this.deleteButtonId != null) {
$(this.deleteButtonId).click(this.removeForm);
}
}
}(window.jQuery);
|
import React, { Component } from 'react'
import styled from 'styled-components'
const SearchCatContainer = styled.div`
position: absolute;
overflow-x: hidden;
width: 100%;
height: 35px;
z-index: 100;
top: 45px;
left: 0;
`
const SearchCatRow = styled.div.attrs(props => ({
style: {
transform: `translate(${props.xOffset}px)`,
}
}))`
position: absolute;
display: flex;
flex-direction: row;
height: 35px;
left: 0;
`
// written externally because is also used for horizontal slider
const marginRightPX = 20
const SearchOffer = styled.div`
position: relative;
background: white;
height: 35px;
width: max-content;
color: red;
padding: 5px 10px;
margin-right: ${marginRightPX}px;
border: 1px solid #FCEF5C;
border-radius: 10px;
`
export class SearchCategories extends Component {
constructor(props) {
super(props)
this.state = {
xOffset: 0,
trackSlide: false,
clientX: null,
maxXOffset: Infinity,
}
this.rowRef = React.createRef()
this.containerRef = React.createRef()
}
componentDidMount() {
const containerWidth = this.containerRef.current.offsetWidth
const maxOffset = this.rowRef.current.offsetWidth
this.setState({
maxXOffset: containerWidth - maxOffset + marginRightPX,
})
}
handleTouchStart = (e) => {
e.stopPropagation()
this.setState({
trackSlide: true
})
}
handleTouchMove = (e) => {
e.stopPropagation()
const { clientX: currClientX } = e.changedTouches[0]
const {
clientX: formerClientX,
xOffset,
maxXOffset,
containerWidth,
} = this.state
if (!formerClientX) {
this.setState({
clientX: currClientX,
})
} else if (currClientX > formerClientX) { // slide right
const newXOffset = xOffset + currClientX - formerClientX
if (newXOffset < 0) {
this.setState({
clientX: currClientX,
xOffset: newXOffset,
})
} else {
this.setState({
clientX: currClientX,
xOffset: 0,
})
}
} else if (currClientX < formerClientX) { // slide left
const newXOffset = xOffset - formerClientX + currClientX
if (newXOffset > maxXOffset) {
this.setState({
clientX: currClientX,
xOffset: newXOffset,
})
} else {
this.setState({
clientX: currClientX,
xOffset: maxXOffset,
})
}
}
}
handleTouchEnd = () => {
this.setState({
clientX: null,
})
}
render() {
const { xOffset } = this.state
const {
categories,
categorySelected,
} = this.props
return (
<SearchCatContainer ref={this.containerRef}>
<SearchCatRow
xOffset={xOffset}
ref={this.rowRef}
onTouchStart={this.handleTouchStart}
onTouchMove={this.handleTouchMove}
onTouchEnd={this.handleTouchEnd}
>
{
categories.map((item) => (
<SearchOffer onClick={() => categorySelected(item)}>
{item.name}
</SearchOffer>
))
}
</SearchCatRow>
</SearchCatContainer>
)
}
}
|
import os
import numpy as np
import torch
import nibabel as nib
from scipy import stats
import torchvision
import datasets
import paths
image_transforms = torchvision.transforms.Compose([
torchvision.transforms.CenterCrop(350),
torchvision.transforms.Resize((64, 64)),
torchvision.transforms.ToTensor(),
])
def loadModel(path, model):
checkpoint = torch.load(path)
model.load_state_dict(checkpoint['model_state_dict'])
def loadModelWithOpt(path, model, optimizer):
checkpoint = torch.load(path)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
def loadFeatures(model, run, responseLen, save_name='', debug=False):
features = torch.load(Paths.encoded_features(model, run, save_name=save_name))
features = features[:responseLen]
features = stats.zscore(features.detach(), axis=0)
if debug:
print('Movie Run Frames: {}'.format(features.shape[0]))
return features
def loadFMRI(sub, run, debug=False):
anat_data = nib.load(Paths.func_path(sub, run)).get_fdata()
mask_data = nib.load(Paths.ffa_mask_path(sub)).get_fdata()
if debug:
print('FMRI Frames: {}'.format(anat_data.shape[3]))
return anat_data, mask_data
def loadPixelFeatures(snapshotsPath, run, responseLen, debug=False):
dataset = datasets.SingleDirDataset(snapshotsPath, image_transforms)
featuresLen = torch.flatten(dataset.__getitem__(0)[0]).shape[0]
features = np.empty(shape=(len(dataset), featuresLen))
for i in range(len(dataset)):
sample = torch.flatten(dataset.__getitem__(i)[0])
sample = sample.numpy()
features[i] = sample
features = features[:responseLen]
features = stats.zscore(features, axis=0)
if debug:
print('Movie Run Frames: {}'.format(features.shape[0]))
return features
def load_encoded_run_datasets(modelName, sub, save_name='', debug=False):
all_run_datasets = []
for i in range(8):
[anat_data, mask_data] = loadFMRI(sub, i, debug=debug)
features = loadFeatures(modelName, i, responseLen=anat_data.shape[3], save_name=features_save_name, debug=debug)
features_conv = convolveFeatures(features, 2)
featureData = FeatureDataset(torch.tensor(features_conv).float(), torch.tensor(anat_data), torch.tensor(mask_data).bool())
all_run_datasets.append(featureData)
return all_run_datasets
def load_pixel_run_datasets(sub, debug=False):
all_run_datasets = []
for i in range(8):
[anat_data, mask_data] = loadFMRI(sub, i, debug=debug)
features = loadPixelFeatures(Paths.movie_run_snapshots_path(i), i, responseLen=anat_data.shape[3], debug=debug)
features_conv = convolveFeatures(features, 2)
featureData = FeatureDataset(torch.tensor(features_conv).float(), torch.tensor(anat_data), torch.tensor(mask_data).bool())
all_run_datasets.append(featureData)
return all_run_datasets
|
(function(e){const t=e["ne"]=e["ne"]||{};t.dictionary=Object.assign(t.dictionary||{},{"%0 of %1":"०% मध्ये १%","Align cell text to the bottom":"","Align cell text to the center":"","Align cell text to the left":"","Align cell text to the middle":"","Align cell text to the right":"","Align cell text to the top":"","Align center":"केन्द्र पङ्क्तिबद्ध गर्नुहोस्","Align left":"बायाँ पङ्क्तिबद्ध गर्नुहोस्","Align right":"दायाँ पङ्क्तिबद्ध गर्नुहोस्","Align table to the left":"","Align table to the right":"",Alignment:"",Aquamarine:"अव्कवामरिन",Background:"",Big:"ठूलो",Black:"कालो","Block quote":"ब्लक उद्धरण",Blue:"निलो","Blue marker":"नीलो मार्कर",Bold:"बोल्ड",Border:"","Bulleted List":"गोली चिन्ह अङ्कित सूची","Bulleted list styles toolbar":"",Cancel:"रद्द गर्नुहोस्","Cell properties":"","Center table":"","Centered image":"केन्द्रित तस्वीर","Change image text alternative":"तस्वीर पाठ विकल्प परिवर्तन गर्नुहोस्","Choose heading":"शीर्षक छनौट गर्नुहोस्",Circle:"",Code:"कोड",Color:"","Color picker":"",Column:"स्तम्भ",Dashed:"",Decimal:"","Decimal with leading zero":"","Decrease indent":"इन्डेन्ट घटाउन",Default:"पूर्वनिर्धारित","Delete column":"स्तम्भ मेटाउनुहोस्","Delete row":"पङ्क्ति मेटाउनुहोस्","Dim grey":"धमिलो खैरो",Dimensions:"",Disc:"","Document colors":"कागजात रंग",Dotted:"",Double:"",Downloadable:"डाउनलोड योग्य","Dropdown toolbar":"","Edit link":"लिङ्क सम्पादन गर्नुहोस्","Editor toolbar":"","Enter image caption":"तस्वीर क्याप्शन प्रविष्ट गर्नुहोस्","Font Background Color":"पृष्ठभूमिको फन्ट रंग","Font Color":"फन्ट रंग","Font Family":"फन्ट परिवार","Font Size":"फन्ट आकार","Full size image":"पूर्ण आकार तस्वीर",Green:"हरियो","Green marker":"हरियो मार्कर","Green pen":"हरियो कलम",Grey:"खैरो",Groove:"","Header column":"हेडर स्तम्भ","Header row":"हेडर पङ्क्ति",Heading:"शीर्षक","Heading 1":"शीर्षक-एक","Heading 2":"शीर्षक २","Heading 3":"शीर्षक ३","Heading 4":"शीर्षक ४","Heading 5":"शीर्षक ५","Heading 6":"शीर्षक ६",Height:"",Highlight:"हाइलाइट","Horizontal text alignment toolbar":"",Huge:"विशाल","Image resize list":"","Image toolbar":"","image widget":"तस्वीर विजेट","Increase indent":"इन्डेन्ट बढाउन",Insert:"","Insert column left":"बायाँ स्तम्भ सम्मिलित गर्न","Insert column right":"दायाँ स्तम्भ सम्मिलित गर्न","Insert image":"तस्वीर सम्मिलित गर्नुहोस्","Insert image via URL":"","Insert media":"मिडिया सम्मिलित गर्नुहोस्।","Insert row above":"माथि पंक्ति सम्मिलित गर्नुहोस्","Insert row below":"तल पंक्ति सम्मिलित गर्नुहोस्","Insert table":"तालिका सम्मिलित गर्नुहोस्",Inset:"",Italic:"इटालिक",Justify:"जस्टिफाइ गर्नुहोस्","Justify cell text":"","Left aligned image":"बायाँ पङ्क्ति तस्वीर","Light blue":"हल्का निलो","Light green":"हल्का हरियो","Light grey":"हल्का खैरो",Link:"लिङ्क","Link URL":"लिङ्क यूआरएल","Lower-latin":"","Lower–roman":"","Media toolbar":"","Media URL":"मिडिया यूआरएल","media widget":"मिडिया विजेट","Merge cell down":"कक्ष तल मर्ज गर्नुहोस्","Merge cell left":"सेल बायाँ मर्ज गर्नुहोस्","Merge cell right":"दायाँ कक्ष मर्ज गर्नुहोस्","Merge cell up":"कक्ष माथि मर्ज गर्नुहोस्","Merge cells":"कक्ष मर्ज गर्नुहोस्",Next:"अर्को",None:"","Numbered List":"सूचीबद्ध सूची","Numbered list styles toolbar":"","Open in a new tab":"नयाँ ट्याबमा खोल्न","Open link in new tab":"नयाँ ट्याबमा लिङ्क खोल्नुहोस्",Orange:"सुन्तला रंग",Original:"",Outset:"",Padding:"",Paragraph:"अनुच्छेद","Paste the media URL in the input.":"इनपुटमा मिडिया यूआरएल पेस्ट गर्नुहोस्।","Pink marker":"गुलाबी मार्कर",Previous:"अघिल्लो",Purple:"बैंगनी रंग",Red:"रातो","Red pen":"रातो कलम",Redo:"रिडु","Remove color":"रंग हटाउन","Remove highlight":"हाइलाइट हटाउनुहोस्","Resize image":"","Resize image to %0":"","Resize image to the original size":"","Rich Text Editor":"धनी पाठ सम्पादक","Rich Text Editor, %0":"धनी पाठ सम्पादक, %0",Ridge:"","Right aligned image":"दायाँ पङ्क्तिबद्ध तस्वीर",Row:"पङ्क्ति",Save:"सुरक्षित गर्नुहोस्","Saving changes":"परिवर्तनहरू बचत हुदैछ","Select column":"","Select row":"","Show more items":"","Side image":"साइड तस्वीर",Small:"सानो",Solid:"","Split cell horizontally":"क्षैतिज कक्ष विभाजित गर्नुहोस्","Split cell vertically":"ठाडो कक्ष विभाजित गर्नुहोस्",Square:"",Style:"","Table alignment toolbar":"","Table cell text alignment":"","Table properties":"","Table toolbar":"","Text alignment":"पाठ संरेखण","Text alignment toolbar":"","Text alternative":"पाठ विकल्प","Text highlight toolbar":"",'The color is invalid. Try "#FF0000" or "rgb(255,0,0)" or "red".':"","The URL must not be empty.":"यूआरएल खाली हुनु हुँदैन।",'The value is invalid. Try "10px" or "2em" or simply "2".':"","This link has no URL":"यो लिङ्कसँग यूआरएल छैन","This media URL is not supported.":"यो मिडिया यूआरएल समर्थित छैन।",Tiny:"सानो","Tip: Paste the URL into the content to embed faster.":"सुझाव:छिटो इम्बेड गर्न यूआरएल सामग्रीमा पेस्ट गर्नुहोस्।","To-do List":"","Toggle the circle list style":"","Toggle the decimal list style":"","Toggle the decimal with leading zero list style":"","Toggle the disc list style":"","Toggle the lower–latin list style":"","Toggle the lower–roman list style":"","Toggle the square list style":"","Toggle the upper–latin list style":"","Toggle the upper–roman list style":"",Turquoise:"त्रकोइस",Underline:"रेखांकन",Undo:"पूर्ववत",Unlink:"अनलिङ्क गर्नुहोस्",Update:"","Update image URL":"","Upload failed":"अपलोड असफल भयो","Upload in progress":"अपलोड हुदैछ","Upper-latin":"","Upper-roman":"","Vertical text alignment toolbar":"",White:"सेतो",Width:"",Yellow:"पहेंलो","Yellow marker":"पहेंलो मार्कर"});t.getPluralForm=function(e){return e!=1}})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
|
"""
This file offers the methods to automatically retrieve the graph Trec4.
The graph is automatically retrieved from the NetworkRepository repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-06 08:01:51.533166
The undirected graph Trec4 has 3 nodes and 3 weighted edges, of which 1
are self-loops. The graph is extremely dense as it has a density of 0.83333
and is connected, as it has a single component. The graph median node degree
is 1, the mean node degree is 1.67, and the node degree mode is 1. The
top 3 most central nodes are 2 (degree 3), 3 (degree 1) and 1 (degree 1).
References
---------------------
Please cite the following if you use the data:
@inproceedings{nr,
title = {The Network Data Repository with Interactive Graph Analytics and Visualization},
author={Ryan A. Rossi and Nesreen K. Ahmed},
booktitle = {AAAI},
url={http://networkrepository.com},
year={2015}
}
Usage example
----------------------
The usage of this graph is relatively straightforward:
.. code:: python
# First import the function to retrieve the graph from the datasets
from ensmallen_graph.datasets.networkrepository import Trec4
# Then load the graph
graph = Trec4()
# Finally, you can do anything with it, for instance, compute its report:
print(graph)
# If you need to run a link prediction task with validation,
# you can split the graph using a connected holdout as follows:
train_graph, validation_graph = graph.connected_holdout(
# You can use an 80/20 split the holdout, for example.
train_size=0.8,
# The random state is used to reproduce the holdout.
random_state=42,
# Wether to show a loading bar.
verbose=True
)
# Remember that, if you need, you can enable the memory-time trade-offs:
train_graph.enable(
vector_sources=True,
vector_destinations=True,
vector_outbounds=True
)
# Consider using the methods made available in the Embiggen package
# to run graph embedding or link prediction tasks.
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen_graph import EnsmallenGraph # pylint: disable=import-error
def Trec4(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/networkrepository",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
"""Return new instance of the Trec4 graph.
The graph is automatically retrieved from the NetworkRepository repository.
Parameters
-------------------
directed: bool = False,
Wether to load the graph as directed or undirected.
By default false.
verbose: int = 2,
Wether to show loading bars during the retrieval and building
of the graph.
cache_path: str = "graphs",
Where to store the downloaded graphs.
additional_graph_kwargs: Dict,
Additional graph kwargs.
Returns
-----------------------
Instace of Trec4 graph.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-06 08:01:51.533166
The undirected graph Trec4 has 3 nodes and 3 weighted edges, of which 1
are self-loops. The graph is extremely dense as it has a density of 0.83333
and is connected, as it has a single component. The graph median node degree
is 1, the mean node degree is 1.67, and the node degree mode is 1. The
top 3 most central nodes are 2 (degree 3), 3 (degree 1) and 1 (degree 1).
References
---------------------
Please cite the following if you use the data:
@inproceedings{nr,
title = {The Network Data Repository with Interactive Graph Analytics and Visualization},
author={Ryan A. Rossi and Nesreen K. Ahmed},
booktitle = {AAAI},
url={http://networkrepository.com},
year={2015}
}
Usage example
----------------------
The usage of this graph is relatively straightforward:
.. code:: python
# First import the function to retrieve the graph from the datasets
from ensmallen_graph.datasets.networkrepository import Trec4
# Then load the graph
graph = Trec4()
# Finally, you can do anything with it, for instance, compute its report:
print(graph)
# If you need to run a link prediction task with validation,
# you can split the graph using a connected holdout as follows:
train_graph, validation_graph = graph.connected_holdout(
# You can use an 80/20 split the holdout, for example.
train_size=0.8,
# The random state is used to reproduce the holdout.
random_state=42,
# Wether to show a loading bar.
verbose=True
)
# Remember that, if you need, you can enable the memory-time trade-offs:
train_graph.enable(
vector_sources=True,
vector_destinations=True,
vector_outbounds=True
)
# Consider using the methods made available in the Embiggen package
# to run graph embedding or link prediction tasks.
"""
return AutomaticallyRetrievedGraph(
graph_name="Trec4",
dataset="networkrepository",
directed=directed,
verbose=verbose,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
|
const fetch = require('node-fetch')
const FormData = require('form-data')
const fs = require('fs')
const fromBuffer = require('file-type')
const resizeImage = require('./imageProcessing')
const fetchBase64 = (url, mimetype) => {
return new Promise((resolve, reject) => {
console.log('Get base64 from:', url)
return fetch(url)
.then((res) => {
const _mimetype = mimetype || res.headers.get('content-type')
res.buffer()
.then((result) => resolve(`data:${_mimetype};base64,` + result.toString('base64')))
})
.catch((err) => {
console.error(err)
reject(err)
})
})
}
const fetchJson = (url, options) =>
new Promise((resolve, reject) =>
fetch(url, options)
.then(response => response.json())
.then(json => resolve(json))
.catch(err => {
console.error(err)
reject(err)
})
)
const uploadImages = (buffData, type) => {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
const { ext } = await fromBuffer(buffData)
const filePath = './temp/tmp.' + ext
const _buffData = type ? await resizeImage(buffData, false) : buffData
fs.writeFile(filePath, _buffData, { encoding: 'base64' }, (err) => {
if (err) return reject(err)
console.log('Uploading image to telegra.ph server...')
const fileData = fs.readFileSync(filePath)
const form = new FormData()
form.append('file', fileData, 'tmp.' + ext)
fetch('https://telegra.ph/upload', {
method: 'POST',
body: form
})
.then(res => res.json())
.then(res => {
if (res.error) return reject(res.error)
resolve('https://telegra.ph' + res[0].src)
})
.then(() => fs.unlinkSync(filePath))
.catch(err => reject(err))
})
})
}
module.exports = {
fetchBase64,
fetchJson,
uploadImages
}
|
from typing import Optional
from pydantic import BaseModel
class Location(BaseModel):
city:str
state: Optional[str] = None
country:str = 'us'
|
(window["webpackJsonpGUI"] = window["webpackJsonpGUI"] || []).push([[10],{
/***/ 1592:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/22e1fb45c852ab96fc6eb36c510ab498.gif";
/***/ }),
/***/ 1604:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/b8e9e92550d13ba932f978cb32d48c25.gif";
/***/ }),
/***/ 2127:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/f3141e783e3d0ee5bbdb3ec7d1fba24c.gif";
/***/ }),
/***/ 2128:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/9432084226baf93e8b19ba4663dd1d98.gif";
/***/ }),
/***/ 2129:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/061d7919139982a9ee5541ac498d4828.gif";
/***/ }),
/***/ 2130:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/1a375f587f65a466438a7e60100a8750.png";
/***/ }),
/***/ 2131:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/15168879152e149b709100995242e833.png";
/***/ }),
/***/ 2132:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/b642bc962f488f800c054da650a62428.png";
/***/ }),
/***/ 2133:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/e115c935d344a357cee1b0ba440638b0.png";
/***/ }),
/***/ 2134:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/bd7f87fab548492fc7bb81e2a1fe5681.png";
/***/ }),
/***/ 2135:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/a2bf4b67c31465785acd31bbdadbcc9c.png";
/***/ }),
/***/ 2136:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/5d21b51a41ba85b7852eb879dcc0ee30.png";
/***/ }),
/***/ 2137:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/2ab79ba84edfbe96e42aeef5611f4d83.png";
/***/ }),
/***/ 2138:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/25cd71063469498df7cab179156d87b2.png";
/***/ }),
/***/ 2139:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/445e1cd3c7bdfcf00df69be73de214b5.png";
/***/ }),
/***/ 2140:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/9c047823333671f288e92ea69c6ae417.png";
/***/ }),
/***/ 2141:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/aaf46bc6028bf524feb99328641419dd.png";
/***/ }),
/***/ 2142:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/76f05fc6c6d5bd694d13a4da81ee10bd.png";
/***/ }),
/***/ 2143:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/0729deeeab0ba3942fba6f70ed338969.png";
/***/ }),
/***/ 2144:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/87c98d386b3f4423fc82ecec23ca4f16.png";
/***/ }),
/***/ 2145:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/ab94bce18038d46772c4c013b18c50d8.png";
/***/ }),
/***/ 2146:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/ffca1ed0934b9b2ece7dd36f3a0f4fb0.png";
/***/ }),
/***/ 2147:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/0cc8cff23987f4d8d8813ec795205b6c.png";
/***/ }),
/***/ 2148:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/6ef72eb649e5b52e25bb2c1f92aa5334.png";
/***/ }),
/***/ 2149:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/35c338ca60869c6e4d21ac52cfce8e69.png";
/***/ }),
/***/ 2150:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/59d4bb932f52f637d8cb0228e85c44f0.png";
/***/ }),
/***/ 2151:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/a9021579cc12bc591ea0e2085374bee2.png";
/***/ }),
/***/ 2152:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/2598837e0a24e0d170ed53318b9b797a.png";
/***/ }),
/***/ 2153:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/92c49e9013cb1c9fba9b5fe3a99b011f.png";
/***/ }),
/***/ 2154:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/d3e3ad82daf219e08aae233ec9fef7cf.png";
/***/ }),
/***/ 2155:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/8a56a3bbb96757eedd16ec77f7870130.png";
/***/ }),
/***/ 2156:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/48ed62bb2875adc2cf9739588bb16c4b.png";
/***/ }),
/***/ 2157:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/04e830c035b8a5b18064e65bc8603e67.png";
/***/ }),
/***/ 2158:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/e6a07a5b0c214c0545a02d4b42269378.png";
/***/ }),
/***/ 2159:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/98e078544198e1135c324f1b6d215820.png";
/***/ }),
/***/ 2160:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/eba0ee63102b369f93c59a681cd2f5bf.png";
/***/ }),
/***/ 2161:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/5c540cafeb35fab1d8381f5f3f029536.png";
/***/ }),
/***/ 2162:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/cfb9384b0c3ec1f02641f37b34764e84.png";
/***/ }),
/***/ 2163:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/f436ec45fe94644c3cfa43bc76c1ae12.png";
/***/ }),
/***/ 2164:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/08ec0a98517212b26bd0c4109cb5b08c.png";
/***/ }),
/***/ 2165:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/2081fa78ed270568e998a3a568b38dc4.png";
/***/ }),
/***/ 2166:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/2e13cc4e6bf302ef51a8eece44ee0b91.png";
/***/ }),
/***/ 2167:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/95ae02512eb2280da0b1eb0711ec948c.gif";
/***/ }),
/***/ 2168:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/66a613e869e2913719f14338b88ef84d.png";
/***/ }),
/***/ 2169:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/fa0038ea1a10da378c83e4f6ebe839ea.png";
/***/ }),
/***/ 2170:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/f889cdd86f37f932db0f7a72dff7039c.png";
/***/ }),
/***/ 2171:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/0e370ab3cadb27d9b1271cb732ec5fc5.png";
/***/ }),
/***/ 2172:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/f803a18aad32338b02b679c8de283825.gif";
/***/ }),
/***/ 2173:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/12fffb88cc245027ce8ab2c020be8318.png";
/***/ }),
/***/ 2174:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/60d46902ec6c55f7896dee4cb2e0ef32.png";
/***/ }),
/***/ 2175:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/6b2189582da05ce371706002b31ae3d5.png";
/***/ }),
/***/ 2176:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/dd575f1b468f022f6e32fec5576d5832.png";
/***/ }),
/***/ 2177:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/f83649a6f99757d24102449927a44929.png";
/***/ }),
/***/ 2178:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/f9f80a46c79989ec217b139a9faa11c7.png";
/***/ }),
/***/ 2179:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/b63266e50eebc5ce414d484d2f7cc70c.png";
/***/ }),
/***/ 2180:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/cd77be4ebde61bded8556897c1f7e11f.png";
/***/ }),
/***/ 2181:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/9149d98c7ab70877c624bf7c72952848.png";
/***/ }),
/***/ 2182:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/80273036af50141f12d92825bda428cb.png";
/***/ }),
/***/ 2183:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/13f7d9eda10cb6bb16b313ec8d90b3a8.png";
/***/ }),
/***/ 2184:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/d760eb306b9e48d2c9791790dec0b5a2.png";
/***/ }),
/***/ 2185:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/aa3c3a337c60549f94f812e28b16b91b.png";
/***/ }),
/***/ 2186:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/72005810d7b58a20712589fa026ca2c6.png";
/***/ }),
/***/ 2187:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/0c99f9ea906ff38c8d007ab9f7607bc6.png";
/***/ }),
/***/ 2188:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/01be678cc22033db268c55584b4b1145.png";
/***/ }),
/***/ 2189:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/75dfdd77f40989c76f8be89442c48f57.png";
/***/ }),
/***/ 2190:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/d7dd1b18c09f179f5a20859d1d88a7c5.png";
/***/ }),
/***/ 2191:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/d71f8d3c085db74f2418d62915e6977a.png";
/***/ }),
/***/ 2192:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/03bd480912e01b6328db7bebe2ddc598.png";
/***/ }),
/***/ 2193:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/009d2bdb612e58522ac2847ed3be2ad9.png";
/***/ }),
/***/ 2194:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/651275fc77d16a2586317749c28bb799.png";
/***/ }),
/***/ 2195:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/6ea9a9d8b467f46cb1744f87b263a355.png";
/***/ }),
/***/ 2196:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/681994a7b229e8390f9ae5e94312ea1a.png";
/***/ }),
/***/ 2197:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/d087f19974a4c1d3d2a080189e719387.png";
/***/ }),
/***/ 2198:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/807382b3f60d8eeebb10875a243c6bf8.gif";
/***/ }),
/***/ 2199:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/a2287c8fce6d430522b550e223678c6a.png";
/***/ }),
/***/ 2200:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/a42f3e375714dfc9e240ad5d695ea4f5.png";
/***/ }),
/***/ 2201:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/bb1ded49c939297ed7425c8534f537d8.png";
/***/ }),
/***/ 2202:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/74e1794c7821c00890a69825d7526c5e.png";
/***/ }),
/***/ 2203:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/60c7cb13fa42e621eaa9dba9ab94dc47.png";
/***/ }),
/***/ 2204:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/e9fd9649a5e891c8811243c4543e986e.png";
/***/ }),
/***/ 2205:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/8bce2aa48a3393eb61cc3af660946d67.png";
/***/ }),
/***/ 2206:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/0ace6d0c800d1275dc415b967ff1dcc4.png";
/***/ }),
/***/ 2207:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/d2d3ca006dd41ad8f0dd3d2e69eedf73.png";
/***/ }),
/***/ 2208:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/6761e4cfe7ec1e634d85eb1bb88e8955.png";
/***/ }),
/***/ 2209:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/357955e0e5c857b3400dc6baf539b05d.png";
/***/ }),
/***/ 2210:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/ef1ded7e12c22605ba70f95382a96a13.png";
/***/ }),
/***/ 2211:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/a07784032e83fe500c81b64d0585c3b9.png";
/***/ }),
/***/ 2212:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/eef2db022a11a91cf48257e10f01ee05.png";
/***/ }),
/***/ 2213:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/9b72c9b4439a7f1c690add6b45c51360.png";
/***/ }),
/***/ 2214:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/d275d18e306a6c36ccfa827bed3f4d45.png";
/***/ }),
/***/ 2215:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/cf8f0e51849e00182a45b5bfd3a3e95a.png";
/***/ }),
/***/ 2216:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/eca17c99b2f66a20a4f0c25048bfc108.png";
/***/ }),
/***/ 2217:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/7ab00ab8daefd87e10f305514cb6a253.png";
/***/ }),
/***/ 2218:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/78cd8e2c774b858b4e49077d0b1b391d.png";
/***/ }),
/***/ 2219:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/86c0614a225dd4e26ccd51cd06e3b2af.png";
/***/ }),
/***/ 2220:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/c61d0fa03b645b88b1e0e972bb11effd.png";
/***/ }),
/***/ 2221:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/07f06a48fbba576dfce5d79e6d0c3523.png";
/***/ }),
/***/ 2222:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/64390a79871b775efaf2daa11e30dc84.png";
/***/ }),
/***/ 2223:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/6700bbb3ddff3f5bd94ab24020f739da.png";
/***/ }),
/***/ 2224:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/8ee269975ec5e64f6e18f8d757797cbd.png";
/***/ }),
/***/ 2225:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/ca4e1d756a09cf9e75b48df72cc558ce.png";
/***/ }),
/***/ 2226:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/babaffcbf18924e42abcd841cfe05724.png";
/***/ }),
/***/ 2227:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/d3cdd105293785bafc302d53039d5001.gif";
/***/ }),
/***/ 2228:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/8e6e65fc01177b14d8bc730e91adfad6.png";
/***/ }),
/***/ 2229:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/assets/94e94c7fb012e2c6669d19d2f33f3885.png";
/***/ }),
/***/ 2891:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ptBrImages", function() { return ptBrImages; });
/* harmony import */ var _steps_intro_1_move_pt_BR_gif__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2127);
/* harmony import */ var _steps_intro_1_move_pt_BR_gif__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_steps_intro_1_move_pt_BR_gif__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _steps_intro_2_say_pt_BR_gif__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2128);
/* harmony import */ var _steps_intro_2_say_pt_BR_gif__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_steps_intro_2_say_pt_BR_gif__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _steps_intro_3_green_flag_pt_BR_gif__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2129);
/* harmony import */ var _steps_intro_3_green_flag_pt_BR_gif__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_steps_intro_3_green_flag_pt_BR_gif__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _steps_speech_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1604);
/* harmony import */ var _steps_speech_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _steps_speech_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2130);
/* harmony import */ var _steps_speech_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _steps_speech_set_voice_pt_BR_png__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2131);
/* harmony import */ var _steps_speech_set_voice_pt_BR_png__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_set_voice_pt_BR_png__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _steps_speech_move_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(2132);
/* harmony import */ var _steps_speech_move_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_move_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _steps_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(234);
/* harmony import */ var _steps_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_steps_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _steps_speech_add_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(385);
/* harmony import */ var _steps_speech_add_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_add_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _steps_speech_song_pt_BR_png__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(2133);
/* harmony import */ var _steps_speech_song_pt_BR_png__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_song_pt_BR_png__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _steps_speech_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(2134);
/* harmony import */ var _steps_speech_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _steps_speech_spin_pt_BR_png__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(2135);
/* harmony import */ var _steps_speech_spin_pt_BR_png__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_spin_pt_BR_png__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _steps_speech_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(2136);
/* harmony import */ var _steps_speech_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_steps_speech_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _steps_cn_show_character_LTR_gif__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(384);
/* harmony import */ var _steps_cn_show_character_LTR_gif__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_steps_cn_show_character_LTR_gif__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _steps_cn_say_pt_BR_png__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(2137);
/* harmony import */ var _steps_cn_say_pt_BR_png__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_steps_cn_say_pt_BR_png__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _steps_cn_glide_pt_BR_png__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(2138);
/* harmony import */ var _steps_cn_glide_pt_BR_png__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_steps_cn_glide_pt_BR_png__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _steps_cn_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(386);
/* harmony import */ var _steps_cn_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_steps_cn_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _steps_cn_collect_pt_BR_png__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(2139);
/* harmony import */ var _steps_cn_collect_pt_BR_png__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_steps_cn_collect_pt_BR_png__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _steps_add_variable_pt_BR_gif__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(1592);
/* harmony import */ var _steps_add_variable_pt_BR_gif__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_steps_add_variable_pt_BR_gif__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _steps_cn_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(2140);
/* harmony import */ var _steps_cn_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_steps_cn_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _steps_cn_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(2141);
/* harmony import */ var _steps_cn_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_steps_cn_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _steps_add_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(387);
/* harmony import */ var _steps_add_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_steps_add_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _steps_name_pick_letter_LTR_gif__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(388);
/* harmony import */ var _steps_name_pick_letter_LTR_gif__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_steps_name_pick_letter_LTR_gif__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _steps_name_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(2142);
/* harmony import */ var _steps_name_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_steps_name_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _steps_name_pick_letter2_LTR_gif__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(389);
/* harmony import */ var _steps_name_pick_letter2_LTR_gif__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_steps_name_pick_letter2_LTR_gif__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var _steps_name_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(2143);
/* harmony import */ var _steps_name_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_steps_name_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _steps_name_spin_pt_BR_png__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(2144);
/* harmony import */ var _steps_name_spin_pt_BR_png__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_steps_name_spin_pt_BR_png__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _steps_name_grow_pt_BR_png__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(2145);
/* harmony import */ var _steps_name_grow_pt_BR_png__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_steps_name_grow_pt_BR_png__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _steps_music_pick_instrument_LTR_gif__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(390);
/* harmony import */ var _steps_music_pick_instrument_LTR_gif__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_steps_music_pick_instrument_LTR_gif__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _steps_music_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(2146);
/* harmony import */ var _steps_music_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_steps_music_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _steps_music_make_song_pt_BR_png__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(2147);
/* harmony import */ var _steps_music_make_song_pt_BR_png__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_steps_music_make_song_pt_BR_png__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var _steps_music_make_beat_pt_BR_png__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(2148);
/* harmony import */ var _steps_music_make_beat_pt_BR_png__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_steps_music_make_beat_pt_BR_png__WEBPACK_IMPORTED_MODULE_31__);
/* harmony import */ var _steps_music_make_beatbox_pt_BR_png__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(2149);
/* harmony import */ var _steps_music_make_beatbox_pt_BR_png__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_steps_music_make_beatbox_pt_BR_png__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var _steps_chase_game_add_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(391);
/* harmony import */ var _steps_chase_game_add_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_steps_chase_game_add_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_33__);
/* harmony import */ var _steps_chase_game_add_sprite1_LTR_gif__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(392);
/* harmony import */ var _steps_chase_game_add_sprite1_LTR_gif__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_steps_chase_game_add_sprite1_LTR_gif__WEBPACK_IMPORTED_MODULE_34__);
/* harmony import */ var _steps_chase_game_right_left_pt_BR_png__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(2150);
/* harmony import */ var _steps_chase_game_right_left_pt_BR_png__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_steps_chase_game_right_left_pt_BR_png__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var _steps_chase_game_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(2151);
/* harmony import */ var _steps_chase_game_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_steps_chase_game_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var _steps_chase_game_add_sprite2_LTR_gif__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(393);
/* harmony import */ var _steps_chase_game_add_sprite2_LTR_gif__WEBPACK_IMPORTED_MODULE_37___default = /*#__PURE__*/__webpack_require__.n(_steps_chase_game_add_sprite2_LTR_gif__WEBPACK_IMPORTED_MODULE_37__);
/* harmony import */ var _steps_chase_game_move_randomly_pt_BR_png__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(2152);
/* harmony import */ var _steps_chase_game_move_randomly_pt_BR_png__WEBPACK_IMPORTED_MODULE_38___default = /*#__PURE__*/__webpack_require__.n(_steps_chase_game_move_randomly_pt_BR_png__WEBPACK_IMPORTED_MODULE_38__);
/* harmony import */ var _steps_chase_game_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(2153);
/* harmony import */ var _steps_chase_game_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_steps_chase_game_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var _steps_chase_game_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(2154);
/* harmony import */ var _steps_chase_game_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_40___default = /*#__PURE__*/__webpack_require__.n(_steps_chase_game_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_40__);
/* harmony import */ var _steps_pop_game_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(394);
/* harmony import */ var _steps_pop_game_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_41___default = /*#__PURE__*/__webpack_require__.n(_steps_pop_game_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_41__);
/* harmony import */ var _steps_pop_game_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(2155);
/* harmony import */ var _steps_pop_game_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_steps_pop_game_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_42__);
/* harmony import */ var _steps_pop_game_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(2156);
/* harmony import */ var _steps_pop_game_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(_steps_pop_game_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_43__);
/* harmony import */ var _steps_pop_game_random_position_pt_BR_png__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(2157);
/* harmony import */ var _steps_pop_game_random_position_pt_BR_png__WEBPACK_IMPORTED_MODULE_44___default = /*#__PURE__*/__webpack_require__.n(_steps_pop_game_random_position_pt_BR_png__WEBPACK_IMPORTED_MODULE_44__);
/* harmony import */ var _steps_pop_game_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(2158);
/* harmony import */ var _steps_pop_game_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(_steps_pop_game_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_45__);
/* harmony import */ var _steps_pop_game_reset_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(2159);
/* harmony import */ var _steps_pop_game_reset_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(_steps_pop_game_reset_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_46__);
/* harmony import */ var _steps_animate_char_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(395);
/* harmony import */ var _steps_animate_char_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_47___default = /*#__PURE__*/__webpack_require__.n(_steps_animate_char_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_47__);
/* harmony import */ var _steps_animate_char_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(2160);
/* harmony import */ var _steps_animate_char_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_steps_animate_char_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_48__);
/* harmony import */ var _steps_animate_char_add_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(2161);
/* harmony import */ var _steps_animate_char_add_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_49___default = /*#__PURE__*/__webpack_require__.n(_steps_animate_char_add_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_49__);
/* harmony import */ var _steps_animate_char_talk_pt_BR_png__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(2162);
/* harmony import */ var _steps_animate_char_talk_pt_BR_png__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(_steps_animate_char_talk_pt_BR_png__WEBPACK_IMPORTED_MODULE_50__);
/* harmony import */ var _steps_animate_char_move_pt_BR_png__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(2163);
/* harmony import */ var _steps_animate_char_move_pt_BR_png__WEBPACK_IMPORTED_MODULE_51___default = /*#__PURE__*/__webpack_require__.n(_steps_animate_char_move_pt_BR_png__WEBPACK_IMPORTED_MODULE_51__);
/* harmony import */ var _steps_animate_char_jump_pt_BR_png__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(2164);
/* harmony import */ var _steps_animate_char_jump_pt_BR_png__WEBPACK_IMPORTED_MODULE_52___default = /*#__PURE__*/__webpack_require__.n(_steps_animate_char_jump_pt_BR_png__WEBPACK_IMPORTED_MODULE_52__);
/* harmony import */ var _steps_animate_char_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(2165);
/* harmony import */ var _steps_animate_char_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_53___default = /*#__PURE__*/__webpack_require__.n(_steps_animate_char_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_53__);
/* harmony import */ var _steps_story_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(396);
/* harmony import */ var _steps_story_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_54___default = /*#__PURE__*/__webpack_require__.n(_steps_story_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_54__);
/* harmony import */ var _steps_story_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(397);
/* harmony import */ var _steps_story_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_55___default = /*#__PURE__*/__webpack_require__.n(_steps_story_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_55__);
/* harmony import */ var _steps_story_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(2166);
/* harmony import */ var _steps_story_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_56___default = /*#__PURE__*/__webpack_require__.n(_steps_story_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_56__);
/* harmony import */ var _steps_story_pick_sprite2_LTR_gif__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(398);
/* harmony import */ var _steps_story_pick_sprite2_LTR_gif__WEBPACK_IMPORTED_MODULE_57___default = /*#__PURE__*/__webpack_require__.n(_steps_story_pick_sprite2_LTR_gif__WEBPACK_IMPORTED_MODULE_57__);
/* harmony import */ var _steps_story_flip_pt_BR_gif__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(2167);
/* harmony import */ var _steps_story_flip_pt_BR_gif__WEBPACK_IMPORTED_MODULE_58___default = /*#__PURE__*/__webpack_require__.n(_steps_story_flip_pt_BR_gif__WEBPACK_IMPORTED_MODULE_58__);
/* harmony import */ var _steps_story_conversation_pt_BR_png__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(2168);
/* harmony import */ var _steps_story_conversation_pt_BR_png__WEBPACK_IMPORTED_MODULE_59___default = /*#__PURE__*/__webpack_require__.n(_steps_story_conversation_pt_BR_png__WEBPACK_IMPORTED_MODULE_59__);
/* harmony import */ var _steps_story_pick_backdrop2_LTR_gif__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(399);
/* harmony import */ var _steps_story_pick_backdrop2_LTR_gif__WEBPACK_IMPORTED_MODULE_60___default = /*#__PURE__*/__webpack_require__.n(_steps_story_pick_backdrop2_LTR_gif__WEBPACK_IMPORTED_MODULE_60__);
/* harmony import */ var _steps_story_switch_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(2169);
/* harmony import */ var _steps_story_switch_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_61___default = /*#__PURE__*/__webpack_require__.n(_steps_story_switch_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_61__);
/* harmony import */ var _steps_story_hide_character_pt_BR_png__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(2170);
/* harmony import */ var _steps_story_hide_character_pt_BR_png__WEBPACK_IMPORTED_MODULE_62___default = /*#__PURE__*/__webpack_require__.n(_steps_story_hide_character_pt_BR_png__WEBPACK_IMPORTED_MODULE_62__);
/* harmony import */ var _steps_story_show_character_pt_BR_png__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(2171);
/* harmony import */ var _steps_story_show_character_pt_BR_png__WEBPACK_IMPORTED_MODULE_63___default = /*#__PURE__*/__webpack_require__.n(_steps_story_show_character_pt_BR_png__WEBPACK_IMPORTED_MODULE_63__);
/* harmony import */ var _steps_video_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(2172);
/* harmony import */ var _steps_video_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_64___default = /*#__PURE__*/__webpack_require__.n(_steps_video_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_64__);
/* harmony import */ var _steps_video_pet_pt_BR_png__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(2173);
/* harmony import */ var _steps_video_pet_pt_BR_png__WEBPACK_IMPORTED_MODULE_65___default = /*#__PURE__*/__webpack_require__.n(_steps_video_pet_pt_BR_png__WEBPACK_IMPORTED_MODULE_65__);
/* harmony import */ var _steps_video_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(2174);
/* harmony import */ var _steps_video_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_66___default = /*#__PURE__*/__webpack_require__.n(_steps_video_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_66__);
/* harmony import */ var _steps_video_pop_pt_BR_png__WEBPACK_IMPORTED_MODULE_67__ = __webpack_require__(2175);
/* harmony import */ var _steps_video_pop_pt_BR_png__WEBPACK_IMPORTED_MODULE_67___default = /*#__PURE__*/__webpack_require__.n(_steps_video_pop_pt_BR_png__WEBPACK_IMPORTED_MODULE_67__);
/* harmony import */ var _steps_fly_choose_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_68__ = __webpack_require__(400);
/* harmony import */ var _steps_fly_choose_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_68___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_choose_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_68__);
/* harmony import */ var _steps_fly_choose_character_LTR_png__WEBPACK_IMPORTED_MODULE_69__ = __webpack_require__(401);
/* harmony import */ var _steps_fly_choose_character_LTR_png__WEBPACK_IMPORTED_MODULE_69___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_choose_character_LTR_png__WEBPACK_IMPORTED_MODULE_69__);
/* harmony import */ var _steps_fly_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_70__ = __webpack_require__(2176);
/* harmony import */ var _steps_fly_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_70___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_70__);
/* harmony import */ var _steps_fly_make_interactive_pt_BR_png__WEBPACK_IMPORTED_MODULE_71__ = __webpack_require__(2177);
/* harmony import */ var _steps_fly_make_interactive_pt_BR_png__WEBPACK_IMPORTED_MODULE_71___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_make_interactive_pt_BR_png__WEBPACK_IMPORTED_MODULE_71__);
/* harmony import */ var _steps_fly_object_to_collect_LTR_png__WEBPACK_IMPORTED_MODULE_72__ = __webpack_require__(402);
/* harmony import */ var _steps_fly_object_to_collect_LTR_png__WEBPACK_IMPORTED_MODULE_72___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_object_to_collect_LTR_png__WEBPACK_IMPORTED_MODULE_72__);
/* harmony import */ var _steps_fly_flying_heart_pt_BR_png__WEBPACK_IMPORTED_MODULE_73__ = __webpack_require__(2178);
/* harmony import */ var _steps_fly_flying_heart_pt_BR_png__WEBPACK_IMPORTED_MODULE_73___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_flying_heart_pt_BR_png__WEBPACK_IMPORTED_MODULE_73__);
/* harmony import */ var _steps_fly_select_flyer_LTR_png__WEBPACK_IMPORTED_MODULE_74__ = __webpack_require__(403);
/* harmony import */ var _steps_fly_select_flyer_LTR_png__WEBPACK_IMPORTED_MODULE_74___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_select_flyer_LTR_png__WEBPACK_IMPORTED_MODULE_74__);
/* harmony import */ var _steps_fly_keep_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_75__ = __webpack_require__(2179);
/* harmony import */ var _steps_fly_keep_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_75___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_keep_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_75__);
/* harmony import */ var _steps_fly_choose_scenery_LTR_gif__WEBPACK_IMPORTED_MODULE_76__ = __webpack_require__(404);
/* harmony import */ var _steps_fly_choose_scenery_LTR_gif__WEBPACK_IMPORTED_MODULE_76___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_choose_scenery_LTR_gif__WEBPACK_IMPORTED_MODULE_76__);
/* harmony import */ var _steps_fly_move_scenery_pt_BR_png__WEBPACK_IMPORTED_MODULE_77__ = __webpack_require__(2180);
/* harmony import */ var _steps_fly_move_scenery_pt_BR_png__WEBPACK_IMPORTED_MODULE_77___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_move_scenery_pt_BR_png__WEBPACK_IMPORTED_MODULE_77__);
/* harmony import */ var _steps_fly_switch_costume_pt_BR_png__WEBPACK_IMPORTED_MODULE_78__ = __webpack_require__(2181);
/* harmony import */ var _steps_fly_switch_costume_pt_BR_png__WEBPACK_IMPORTED_MODULE_78___default = /*#__PURE__*/__webpack_require__.n(_steps_fly_switch_costume_pt_BR_png__WEBPACK_IMPORTED_MODULE_78__);
/* harmony import */ var _steps_pong_add_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_79__ = __webpack_require__(405);
/* harmony import */ var _steps_pong_add_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_79___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_add_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_79__);
/* harmony import */ var _steps_pong_add_ball_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_80__ = __webpack_require__(406);
/* harmony import */ var _steps_pong_add_ball_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_80___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_add_ball_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_80__);
/* harmony import */ var _steps_pong_bounce_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_81__ = __webpack_require__(2182);
/* harmony import */ var _steps_pong_bounce_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_81___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_bounce_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_81__);
/* harmony import */ var _steps_pong_add_a_paddle_LTR_gif__WEBPACK_IMPORTED_MODULE_82__ = __webpack_require__(407);
/* harmony import */ var _steps_pong_add_a_paddle_LTR_gif__WEBPACK_IMPORTED_MODULE_82___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_add_a_paddle_LTR_gif__WEBPACK_IMPORTED_MODULE_82__);
/* harmony import */ var _steps_pong_move_the_paddle_pt_BR_png__WEBPACK_IMPORTED_MODULE_83__ = __webpack_require__(2183);
/* harmony import */ var _steps_pong_move_the_paddle_pt_BR_png__WEBPACK_IMPORTED_MODULE_83___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_move_the_paddle_pt_BR_png__WEBPACK_IMPORTED_MODULE_83__);
/* harmony import */ var _steps_pong_select_ball_LTR_png__WEBPACK_IMPORTED_MODULE_84__ = __webpack_require__(408);
/* harmony import */ var _steps_pong_select_ball_LTR_png__WEBPACK_IMPORTED_MODULE_84___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_select_ball_LTR_png__WEBPACK_IMPORTED_MODULE_84__);
/* harmony import */ var _steps_pong_add_code_to_ball_pt_BR_png__WEBPACK_IMPORTED_MODULE_85__ = __webpack_require__(2184);
/* harmony import */ var _steps_pong_add_code_to_ball_pt_BR_png__WEBPACK_IMPORTED_MODULE_85___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_add_code_to_ball_pt_BR_png__WEBPACK_IMPORTED_MODULE_85__);
/* harmony import */ var _steps_pong_choose_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_86__ = __webpack_require__(2185);
/* harmony import */ var _steps_pong_choose_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_86___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_choose_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_86__);
/* harmony import */ var _steps_pong_insert_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_87__ = __webpack_require__(2186);
/* harmony import */ var _steps_pong_insert_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_87___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_insert_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_87__);
/* harmony import */ var _steps_pong_reset_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_88__ = __webpack_require__(2187);
/* harmony import */ var _steps_pong_reset_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_88___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_reset_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_88__);
/* harmony import */ var _steps_pong_add_line_LTR_gif__WEBPACK_IMPORTED_MODULE_89__ = __webpack_require__(409);
/* harmony import */ var _steps_pong_add_line_LTR_gif__WEBPACK_IMPORTED_MODULE_89___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_add_line_LTR_gif__WEBPACK_IMPORTED_MODULE_89__);
/* harmony import */ var _steps_pong_game_over_pt_BR_png__WEBPACK_IMPORTED_MODULE_90__ = __webpack_require__(2188);
/* harmony import */ var _steps_pong_game_over_pt_BR_png__WEBPACK_IMPORTED_MODULE_90___default = /*#__PURE__*/__webpack_require__.n(_steps_pong_game_over_pt_BR_png__WEBPACK_IMPORTED_MODULE_90__);
/* harmony import */ var _steps_imagine_type_what_you_want_pt_BR_png__WEBPACK_IMPORTED_MODULE_91__ = __webpack_require__(2189);
/* harmony import */ var _steps_imagine_type_what_you_want_pt_BR_png__WEBPACK_IMPORTED_MODULE_91___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_type_what_you_want_pt_BR_png__WEBPACK_IMPORTED_MODULE_91__);
/* harmony import */ var _steps_imagine_click_green_flag_pt_BR_png__WEBPACK_IMPORTED_MODULE_92__ = __webpack_require__(2190);
/* harmony import */ var _steps_imagine_click_green_flag_pt_BR_png__WEBPACK_IMPORTED_MODULE_92___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_click_green_flag_pt_BR_png__WEBPACK_IMPORTED_MODULE_92__);
/* harmony import */ var _steps_imagine_choose_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_93__ = __webpack_require__(410);
/* harmony import */ var _steps_imagine_choose_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_93___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_choose_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_93__);
/* harmony import */ var _steps_imagine_choose_any_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_94__ = __webpack_require__(411);
/* harmony import */ var _steps_imagine_choose_any_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_94___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_choose_any_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_94__);
/* harmony import */ var _steps_imagine_fly_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_95__ = __webpack_require__(2191);
/* harmony import */ var _steps_imagine_fly_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_95___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_fly_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_95__);
/* harmony import */ var _steps_imagine_choose_another_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_96__ = __webpack_require__(412);
/* harmony import */ var _steps_imagine_choose_another_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_96___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_choose_another_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_96__);
/* harmony import */ var _steps_imagine_left_right_pt_BR_png__WEBPACK_IMPORTED_MODULE_97__ = __webpack_require__(2192);
/* harmony import */ var _steps_imagine_left_right_pt_BR_png__WEBPACK_IMPORTED_MODULE_97___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_left_right_pt_BR_png__WEBPACK_IMPORTED_MODULE_97__);
/* harmony import */ var _steps_imagine_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_98__ = __webpack_require__(2193);
/* harmony import */ var _steps_imagine_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_98___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_98__);
/* harmony import */ var _steps_imagine_change_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_99__ = __webpack_require__(2194);
/* harmony import */ var _steps_imagine_change_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_99___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_change_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_99__);
/* harmony import */ var _steps_imagine_glide_to_point_pt_BR_png__WEBPACK_IMPORTED_MODULE_100__ = __webpack_require__(2195);
/* harmony import */ var _steps_imagine_glide_to_point_pt_BR_png__WEBPACK_IMPORTED_MODULE_100___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_glide_to_point_pt_BR_png__WEBPACK_IMPORTED_MODULE_100__);
/* harmony import */ var _steps_imagine_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_101__ = __webpack_require__(2196);
/* harmony import */ var _steps_imagine_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_101___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_101__);
/* harmony import */ var _steps_imagine_choose_another_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_102__ = __webpack_require__(413);
/* harmony import */ var _steps_imagine_choose_another_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_102___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_choose_another_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_102__);
/* harmony import */ var _steps_imagine_switch_backdrops_pt_BR_png__WEBPACK_IMPORTED_MODULE_103__ = __webpack_require__(2197);
/* harmony import */ var _steps_imagine_switch_backdrops_pt_BR_png__WEBPACK_IMPORTED_MODULE_103___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_switch_backdrops_pt_BR_png__WEBPACK_IMPORTED_MODULE_103__);
/* harmony import */ var _steps_imagine_record_a_sound_pt_BR_gif__WEBPACK_IMPORTED_MODULE_104__ = __webpack_require__(2198);
/* harmony import */ var _steps_imagine_record_a_sound_pt_BR_gif__WEBPACK_IMPORTED_MODULE_104___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_record_a_sound_pt_BR_gif__WEBPACK_IMPORTED_MODULE_104__);
/* harmony import */ var _steps_imagine_choose_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_105__ = __webpack_require__(2199);
/* harmony import */ var _steps_imagine_choose_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_105___default = /*#__PURE__*/__webpack_require__.n(_steps_imagine_choose_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_105__);
/* harmony import */ var _steps_add_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_106__ = __webpack_require__(414);
/* harmony import */ var _steps_add_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_106___default = /*#__PURE__*/__webpack_require__.n(_steps_add_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_106__);
/* harmony import */ var _steps_add_effects_pt_BR_png__WEBPACK_IMPORTED_MODULE_107__ = __webpack_require__(2200);
/* harmony import */ var _steps_add_effects_pt_BR_png__WEBPACK_IMPORTED_MODULE_107___default = /*#__PURE__*/__webpack_require__.n(_steps_add_effects_pt_BR_png__WEBPACK_IMPORTED_MODULE_107__);
/* harmony import */ var _steps_hide_show_pt_BR_png__WEBPACK_IMPORTED_MODULE_108__ = __webpack_require__(2201);
/* harmony import */ var _steps_hide_show_pt_BR_png__WEBPACK_IMPORTED_MODULE_108___default = /*#__PURE__*/__webpack_require__.n(_steps_hide_show_pt_BR_png__WEBPACK_IMPORTED_MODULE_108__);
/* harmony import */ var _steps_switch_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_109__ = __webpack_require__(2202);
/* harmony import */ var _steps_switch_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_109___default = /*#__PURE__*/__webpack_require__.n(_steps_switch_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_109__);
/* harmony import */ var _steps_change_size_pt_BR_png__WEBPACK_IMPORTED_MODULE_110__ = __webpack_require__(2203);
/* harmony import */ var _steps_change_size_pt_BR_png__WEBPACK_IMPORTED_MODULE_110___default = /*#__PURE__*/__webpack_require__.n(_steps_change_size_pt_BR_png__WEBPACK_IMPORTED_MODULE_110__);
/* harmony import */ var _steps_spin_turn_pt_BR_png__WEBPACK_IMPORTED_MODULE_111__ = __webpack_require__(2204);
/* harmony import */ var _steps_spin_turn_pt_BR_png__WEBPACK_IMPORTED_MODULE_111___default = /*#__PURE__*/__webpack_require__.n(_steps_spin_turn_pt_BR_png__WEBPACK_IMPORTED_MODULE_111__);
/* harmony import */ var _steps_spin_point_in_direction_pt_BR_png__WEBPACK_IMPORTED_MODULE_112__ = __webpack_require__(2205);
/* harmony import */ var _steps_spin_point_in_direction_pt_BR_png__WEBPACK_IMPORTED_MODULE_112___default = /*#__PURE__*/__webpack_require__.n(_steps_spin_point_in_direction_pt_BR_png__WEBPACK_IMPORTED_MODULE_112__);
/* harmony import */ var _steps_record_a_sound_sounds_tab_pt_BR_png__WEBPACK_IMPORTED_MODULE_113__ = __webpack_require__(2206);
/* harmony import */ var _steps_record_a_sound_sounds_tab_pt_BR_png__WEBPACK_IMPORTED_MODULE_113___default = /*#__PURE__*/__webpack_require__.n(_steps_record_a_sound_sounds_tab_pt_BR_png__WEBPACK_IMPORTED_MODULE_113__);
/* harmony import */ var _steps_record_a_sound_click_record_pt_BR_png__WEBPACK_IMPORTED_MODULE_114__ = __webpack_require__(2207);
/* harmony import */ var _steps_record_a_sound_click_record_pt_BR_png__WEBPACK_IMPORTED_MODULE_114___default = /*#__PURE__*/__webpack_require__.n(_steps_record_a_sound_click_record_pt_BR_png__WEBPACK_IMPORTED_MODULE_114__);
/* harmony import */ var _steps_record_a_sound_press_record_button_pt_BR_png__WEBPACK_IMPORTED_MODULE_115__ = __webpack_require__(2208);
/* harmony import */ var _steps_record_a_sound_press_record_button_pt_BR_png__WEBPACK_IMPORTED_MODULE_115___default = /*#__PURE__*/__webpack_require__.n(_steps_record_a_sound_press_record_button_pt_BR_png__WEBPACK_IMPORTED_MODULE_115__);
/* harmony import */ var _steps_record_a_sound_choose_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_116__ = __webpack_require__(2209);
/* harmony import */ var _steps_record_a_sound_choose_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_116___default = /*#__PURE__*/__webpack_require__.n(_steps_record_a_sound_choose_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_116__);
/* harmony import */ var _steps_record_a_sound_play_your_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_117__ = __webpack_require__(2210);
/* harmony import */ var _steps_record_a_sound_play_your_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_117___default = /*#__PURE__*/__webpack_require__.n(_steps_record_a_sound_play_your_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_117__);
/* harmony import */ var _steps_move_arrow_keys_left_right_pt_BR_png__WEBPACK_IMPORTED_MODULE_118__ = __webpack_require__(2211);
/* harmony import */ var _steps_move_arrow_keys_left_right_pt_BR_png__WEBPACK_IMPORTED_MODULE_118___default = /*#__PURE__*/__webpack_require__.n(_steps_move_arrow_keys_left_right_pt_BR_png__WEBPACK_IMPORTED_MODULE_118__);
/* harmony import */ var _steps_move_arrow_keys_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_119__ = __webpack_require__(2212);
/* harmony import */ var _steps_move_arrow_keys_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_119___default = /*#__PURE__*/__webpack_require__.n(_steps_move_arrow_keys_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_119__);
/* harmony import */ var _steps_glide_around_back_and_forth_pt_BR_png__WEBPACK_IMPORTED_MODULE_120__ = __webpack_require__(2213);
/* harmony import */ var _steps_glide_around_back_and_forth_pt_BR_png__WEBPACK_IMPORTED_MODULE_120___default = /*#__PURE__*/__webpack_require__.n(_steps_glide_around_back_and_forth_pt_BR_png__WEBPACK_IMPORTED_MODULE_120__);
/* harmony import */ var _steps_glide_around_point_pt_BR_png__WEBPACK_IMPORTED_MODULE_121__ = __webpack_require__(2214);
/* harmony import */ var _steps_glide_around_point_pt_BR_png__WEBPACK_IMPORTED_MODULE_121___default = /*#__PURE__*/__webpack_require__.n(_steps_glide_around_point_pt_BR_png__WEBPACK_IMPORTED_MODULE_121__);
/* harmony import */ var _steps_code_cartoon_01_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_122__ = __webpack_require__(2215);
/* harmony import */ var _steps_code_cartoon_01_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_122___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_01_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_122__);
/* harmony import */ var _steps_code_cartoon_02_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_123__ = __webpack_require__(2216);
/* harmony import */ var _steps_code_cartoon_02_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_123___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_02_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_123__);
/* harmony import */ var _steps_code_cartoon_03_select_different_character_LTR_png__WEBPACK_IMPORTED_MODULE_124__ = __webpack_require__(415);
/* harmony import */ var _steps_code_cartoon_03_select_different_character_LTR_png__WEBPACK_IMPORTED_MODULE_124___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_03_select_different_character_LTR_png__WEBPACK_IMPORTED_MODULE_124__);
/* harmony import */ var _steps_code_cartoon_04_use_minus_sign_pt_BR_png__WEBPACK_IMPORTED_MODULE_125__ = __webpack_require__(2217);
/* harmony import */ var _steps_code_cartoon_04_use_minus_sign_pt_BR_png__WEBPACK_IMPORTED_MODULE_125___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_04_use_minus_sign_pt_BR_png__WEBPACK_IMPORTED_MODULE_125__);
/* harmony import */ var _steps_code_cartoon_05_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_126__ = __webpack_require__(2218);
/* harmony import */ var _steps_code_cartoon_05_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_126___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_05_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_126__);
/* harmony import */ var _steps_code_cartoon_06_select_another_different_character_LTR_png__WEBPACK_IMPORTED_MODULE_127__ = __webpack_require__(416);
/* harmony import */ var _steps_code_cartoon_06_select_another_different_character_LTR_png__WEBPACK_IMPORTED_MODULE_127___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_06_select_another_different_character_LTR_png__WEBPACK_IMPORTED_MODULE_127__);
/* harmony import */ var _steps_code_cartoon_07_jump_pt_BR_png__WEBPACK_IMPORTED_MODULE_128__ = __webpack_require__(2219);
/* harmony import */ var _steps_code_cartoon_07_jump_pt_BR_png__WEBPACK_IMPORTED_MODULE_128___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_07_jump_pt_BR_png__WEBPACK_IMPORTED_MODULE_128__);
/* harmony import */ var _steps_code_cartoon_08_change_scenes_pt_BR_png__WEBPACK_IMPORTED_MODULE_129__ = __webpack_require__(2220);
/* harmony import */ var _steps_code_cartoon_08_change_scenes_pt_BR_png__WEBPACK_IMPORTED_MODULE_129___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_08_change_scenes_pt_BR_png__WEBPACK_IMPORTED_MODULE_129__);
/* harmony import */ var _steps_code_cartoon_09_glide_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_130__ = __webpack_require__(2221);
/* harmony import */ var _steps_code_cartoon_09_glide_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_130___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_09_glide_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_130__);
/* harmony import */ var _steps_code_cartoon_10_change_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_131__ = __webpack_require__(2222);
/* harmony import */ var _steps_code_cartoon_10_change_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_131___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_10_change_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_131__);
/* harmony import */ var _steps_code_cartoon_11_choose_more_characters_LTR_png__WEBPACK_IMPORTED_MODULE_132__ = __webpack_require__(417);
/* harmony import */ var _steps_code_cartoon_11_choose_more_characters_LTR_png__WEBPACK_IMPORTED_MODULE_132___default = /*#__PURE__*/__webpack_require__.n(_steps_code_cartoon_11_choose_more_characters_LTR_png__WEBPACK_IMPORTED_MODULE_132__);
/* harmony import */ var _steps_talking_2_choose_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_133__ = __webpack_require__(418);
/* harmony import */ var _steps_talking_2_choose_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_133___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_2_choose_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_133__);
/* harmony import */ var _steps_talking_3_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_134__ = __webpack_require__(2223);
/* harmony import */ var _steps_talking_3_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_134___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_3_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_134__);
/* harmony import */ var _steps_talking_4_choose_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_135__ = __webpack_require__(419);
/* harmony import */ var _steps_talking_4_choose_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_135___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_4_choose_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_135__);
/* harmony import */ var _steps_talking_5_switch_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_136__ = __webpack_require__(2224);
/* harmony import */ var _steps_talking_5_switch_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_136___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_5_switch_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_136__);
/* harmony import */ var _steps_talking_6_choose_another_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_137__ = __webpack_require__(420);
/* harmony import */ var _steps_talking_6_choose_another_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_137___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_6_choose_another_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_137__);
/* harmony import */ var _steps_talking_7_move_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_138__ = __webpack_require__(2225);
/* harmony import */ var _steps_talking_7_move_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_138___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_7_move_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_138__);
/* harmony import */ var _steps_talking_8_choose_another_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_139__ = __webpack_require__(421);
/* harmony import */ var _steps_talking_8_choose_another_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_139___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_8_choose_another_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_139__);
/* harmony import */ var _steps_talking_9_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_140__ = __webpack_require__(2226);
/* harmony import */ var _steps_talking_9_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_140___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_9_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_140__);
/* harmony import */ var _steps_talking_10_choose_third_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_141__ = __webpack_require__(422);
/* harmony import */ var _steps_talking_10_choose_third_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_141___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_10_choose_third_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_141__);
/* harmony import */ var _steps_talking_11_choose_sound_pt_BR_gif__WEBPACK_IMPORTED_MODULE_142__ = __webpack_require__(2227);
/* harmony import */ var _steps_talking_11_choose_sound_pt_BR_gif__WEBPACK_IMPORTED_MODULE_142___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_11_choose_sound_pt_BR_gif__WEBPACK_IMPORTED_MODULE_142__);
/* harmony import */ var _steps_talking_12_dance_moves_pt_BR_png__WEBPACK_IMPORTED_MODULE_143__ = __webpack_require__(2228);
/* harmony import */ var _steps_talking_12_dance_moves_pt_BR_png__WEBPACK_IMPORTED_MODULE_143___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_12_dance_moves_pt_BR_png__WEBPACK_IMPORTED_MODULE_143__);
/* harmony import */ var _steps_talking_13_ask_and_answer_pt_BR_png__WEBPACK_IMPORTED_MODULE_144__ = __webpack_require__(2229);
/* harmony import */ var _steps_talking_13_ask_and_answer_pt_BR_png__WEBPACK_IMPORTED_MODULE_144___default = /*#__PURE__*/__webpack_require__.n(_steps_talking_13_ask_and_answer_pt_BR_png__WEBPACK_IMPORTED_MODULE_144__);
// Intro
// Text to Speech
// Cartoon Network
// Add sprite
// Animate a name
// Make Music
// Chase-Game
// Clicker-Game (Pop Game)
// Animate A Character
// Tell A Story
// Video Sensing
// Make it Fly
// Pong
// Imagine a World
// Add a Backdrop
// Add Effects
// Hide and Show
// Switch Costumes
// Change Size
// Spin
// Record a Sound
// Use Arrow Keys
// Glide Around
// Code a Cartoon
// Talking Tales
var ptBrImages = {
// Intro
introMove: _steps_intro_1_move_pt_BR_gif__WEBPACK_IMPORTED_MODULE_0___default.a,
introSay: _steps_intro_2_say_pt_BR_gif__WEBPACK_IMPORTED_MODULE_1___default.a,
introGreenFlag: _steps_intro_3_green_flag_pt_BR_gif__WEBPACK_IMPORTED_MODULE_2___default.a,
// Text to Speech
speechAddExtension: _steps_speech_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_3___default.a,
speechSaySomething: _steps_speech_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_4___default.a,
speechSetVoice: _steps_speech_set_voice_pt_BR_png__WEBPACK_IMPORTED_MODULE_5___default.a,
speechMoveAround: _steps_speech_move_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_6___default.a,
speechAddBackdrop: _steps_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_7___default.a,
speechAddSprite: _steps_speech_add_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_8___default.a,
speechSong: _steps_speech_song_pt_BR_png__WEBPACK_IMPORTED_MODULE_9___default.a,
speechChangeColor: _steps_speech_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_10___default.a,
speechSpin: _steps_speech_spin_pt_BR_png__WEBPACK_IMPORTED_MODULE_11___default.a,
speechGrowShrink: _steps_speech_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_12___default.a,
// Cartoon Network
cnShowCharacter: _steps_cn_show_character_LTR_gif__WEBPACK_IMPORTED_MODULE_13___default.a,
cnSay: _steps_cn_say_pt_BR_png__WEBPACK_IMPORTED_MODULE_14___default.a,
cnGlide: _steps_cn_glide_pt_BR_png__WEBPACK_IMPORTED_MODULE_15___default.a,
cnPickSprite: _steps_cn_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_16___default.a,
cnCollect: _steps_cn_collect_pt_BR_png__WEBPACK_IMPORTED_MODULE_17___default.a,
cnVariable: _steps_add_variable_pt_BR_gif__WEBPACK_IMPORTED_MODULE_18___default.a,
cnScore: _steps_cn_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_19___default.a,
cnBackdrop: _steps_cn_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_20___default.a,
// Add sprite
addSprite: _steps_add_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_21___default.a,
// Animate a name
namePickLetter: _steps_name_pick_letter_LTR_gif__WEBPACK_IMPORTED_MODULE_22___default.a,
namePlaySound: _steps_name_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_23___default.a,
namePickLetter2: _steps_name_pick_letter2_LTR_gif__WEBPACK_IMPORTED_MODULE_24___default.a,
nameChangeColor: _steps_name_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_25___default.a,
nameSpin: _steps_name_spin_pt_BR_png__WEBPACK_IMPORTED_MODULE_26___default.a,
nameGrow: _steps_name_grow_pt_BR_png__WEBPACK_IMPORTED_MODULE_27___default.a,
// Make-Music
musicPickInstrument: _steps_music_pick_instrument_LTR_gif__WEBPACK_IMPORTED_MODULE_28___default.a,
musicPlaySound: _steps_music_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_29___default.a,
musicMakeSong: _steps_music_make_song_pt_BR_png__WEBPACK_IMPORTED_MODULE_30___default.a,
musicMakeBeat: _steps_music_make_beat_pt_BR_png__WEBPACK_IMPORTED_MODULE_31___default.a,
musicMakeBeatbox: _steps_music_make_beatbox_pt_BR_png__WEBPACK_IMPORTED_MODULE_32___default.a,
// Chase-Game
chaseGameAddBackdrop: _steps_chase_game_add_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_33___default.a,
chaseGameAddSprite1: _steps_chase_game_add_sprite1_LTR_gif__WEBPACK_IMPORTED_MODULE_34___default.a,
chaseGameRightLeft: _steps_chase_game_right_left_pt_BR_png__WEBPACK_IMPORTED_MODULE_35___default.a,
chaseGameUpDown: _steps_chase_game_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_36___default.a,
chaseGameAddSprite2: _steps_chase_game_add_sprite2_LTR_gif__WEBPACK_IMPORTED_MODULE_37___default.a,
chaseGameMoveRandomly: _steps_chase_game_move_randomly_pt_BR_png__WEBPACK_IMPORTED_MODULE_38___default.a,
chaseGamePlaySound: _steps_chase_game_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_39___default.a,
chaseGameAddVariable: _steps_add_variable_pt_BR_gif__WEBPACK_IMPORTED_MODULE_18___default.a,
chaseGameChangeScore: _steps_chase_game_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_40___default.a,
// Make-A-Pop/Clicker Game
popGamePickSprite: _steps_pop_game_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_41___default.a,
popGamePlaySound: _steps_pop_game_play_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_42___default.a,
popGameAddScore: _steps_add_variable_pt_BR_gif__WEBPACK_IMPORTED_MODULE_18___default.a,
popGameChangeScore: _steps_pop_game_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_43___default.a,
popGameRandomPosition: _steps_pop_game_random_position_pt_BR_png__WEBPACK_IMPORTED_MODULE_44___default.a,
popGameChangeColor: _steps_pop_game_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_45___default.a,
popGameResetScore: _steps_pop_game_reset_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_46___default.a,
// Animate A Character
animateCharPickBackdrop: _steps_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_7___default.a,
animateCharPickSprite: _steps_animate_char_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_47___default.a,
animateCharSaySomething: _steps_animate_char_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_48___default.a,
animateCharAddSound: _steps_animate_char_add_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_49___default.a,
animateCharTalk: _steps_animate_char_talk_pt_BR_png__WEBPACK_IMPORTED_MODULE_50___default.a,
animateCharMove: _steps_animate_char_move_pt_BR_png__WEBPACK_IMPORTED_MODULE_51___default.a,
animateCharJump: _steps_animate_char_jump_pt_BR_png__WEBPACK_IMPORTED_MODULE_52___default.a,
animateCharChangeColor: _steps_animate_char_change_color_pt_BR_png__WEBPACK_IMPORTED_MODULE_53___default.a,
// Tell A Story
storyPickBackdrop: _steps_story_pick_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_54___default.a,
storyPickSprite: _steps_story_pick_sprite_LTR_gif__WEBPACK_IMPORTED_MODULE_55___default.a,
storySaySomething: _steps_story_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_56___default.a,
storyPickSprite2: _steps_story_pick_sprite2_LTR_gif__WEBPACK_IMPORTED_MODULE_57___default.a,
storyFlip: _steps_story_flip_pt_BR_gif__WEBPACK_IMPORTED_MODULE_58___default.a,
storyConversation: _steps_story_conversation_pt_BR_png__WEBPACK_IMPORTED_MODULE_59___default.a,
storyPickBackdrop2: _steps_story_pick_backdrop2_LTR_gif__WEBPACK_IMPORTED_MODULE_60___default.a,
storySwitchBackdrop: _steps_story_switch_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_61___default.a,
storyHideCharacter: _steps_story_hide_character_pt_BR_png__WEBPACK_IMPORTED_MODULE_62___default.a,
storyShowCharacter: _steps_story_show_character_pt_BR_png__WEBPACK_IMPORTED_MODULE_63___default.a,
// Video Sensing
videoAddExtension: _steps_video_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_64___default.a,
videoPet: _steps_video_pet_pt_BR_png__WEBPACK_IMPORTED_MODULE_65___default.a,
videoAnimate: _steps_video_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_66___default.a,
videoPop: _steps_video_pop_pt_BR_png__WEBPACK_IMPORTED_MODULE_67___default.a,
// Make it Fly
flyChooseBackdrop: _steps_fly_choose_backdrop_LTR_gif__WEBPACK_IMPORTED_MODULE_68___default.a,
flyChooseCharacter: _steps_fly_choose_character_LTR_png__WEBPACK_IMPORTED_MODULE_69___default.a,
flySaySomething: _steps_fly_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_70___default.a,
flyMoveArrows: _steps_fly_make_interactive_pt_BR_png__WEBPACK_IMPORTED_MODULE_71___default.a,
flyChooseObject: _steps_fly_object_to_collect_LTR_png__WEBPACK_IMPORTED_MODULE_72___default.a,
flyFlyingObject: _steps_fly_flying_heart_pt_BR_png__WEBPACK_IMPORTED_MODULE_73___default.a,
flySelectFlyingSprite: _steps_fly_select_flyer_LTR_png__WEBPACK_IMPORTED_MODULE_74___default.a,
flyAddScore: _steps_add_variable_pt_BR_gif__WEBPACK_IMPORTED_MODULE_18___default.a,
flyKeepScore: _steps_fly_keep_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_75___default.a,
flyAddScenery: _steps_fly_choose_scenery_LTR_gif__WEBPACK_IMPORTED_MODULE_76___default.a,
flyMoveScenery: _steps_fly_move_scenery_pt_BR_png__WEBPACK_IMPORTED_MODULE_77___default.a,
flySwitchLooks: _steps_fly_switch_costume_pt_BR_png__WEBPACK_IMPORTED_MODULE_78___default.a,
// Pong
pongAddBackdrop: _steps_pong_add_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_79___default.a,
pongAddBallSprite: _steps_pong_add_ball_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_80___default.a,
pongBounceAround: _steps_pong_bounce_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_81___default.a,
pongAddPaddle: _steps_pong_add_a_paddle_LTR_gif__WEBPACK_IMPORTED_MODULE_82___default.a,
pongMoveThePaddle: _steps_pong_move_the_paddle_pt_BR_png__WEBPACK_IMPORTED_MODULE_83___default.a,
pongSelectBallSprite: _steps_pong_select_ball_LTR_png__WEBPACK_IMPORTED_MODULE_84___default.a,
pongAddMoreCodeToBall: _steps_pong_add_code_to_ball_pt_BR_png__WEBPACK_IMPORTED_MODULE_85___default.a,
pongAddAScore: _steps_add_variable_pt_BR_gif__WEBPACK_IMPORTED_MODULE_18___default.a,
pongChooseScoreFromMenu: _steps_pong_choose_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_86___default.a,
pongInsertChangeScoreBlock: _steps_pong_insert_change_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_87___default.a,
pongResetScore: _steps_pong_reset_score_pt_BR_png__WEBPACK_IMPORTED_MODULE_88___default.a,
pongAddLineSprite: _steps_pong_add_line_LTR_gif__WEBPACK_IMPORTED_MODULE_89___default.a,
pongGameOver: _steps_pong_game_over_pt_BR_png__WEBPACK_IMPORTED_MODULE_90___default.a,
// Imagine a World
imagineTypeWhatYouWant: _steps_imagine_type_what_you_want_pt_BR_png__WEBPACK_IMPORTED_MODULE_91___default.a,
imagineClickGreenFlag: _steps_imagine_click_green_flag_pt_BR_png__WEBPACK_IMPORTED_MODULE_92___default.a,
imagineChooseBackdrop: _steps_imagine_choose_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_93___default.a,
imagineChooseSprite: _steps_imagine_choose_any_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_94___default.a,
imagineFlyAround: _steps_imagine_fly_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_95___default.a,
imagineChooseAnotherSprite: _steps_imagine_choose_another_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_96___default.a,
imagineLeftRight: _steps_imagine_left_right_pt_BR_png__WEBPACK_IMPORTED_MODULE_97___default.a,
imagineUpDown: _steps_imagine_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_98___default.a,
imagineChangeCostumes: _steps_imagine_change_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_99___default.a,
imagineGlideToPoint: _steps_imagine_glide_to_point_pt_BR_png__WEBPACK_IMPORTED_MODULE_100___default.a,
imagineGrowShrink: _steps_imagine_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_101___default.a,
imagineChooseAnotherBackdrop: _steps_imagine_choose_another_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_102___default.a,
imagineSwitchBackdrops: _steps_imagine_switch_backdrops_pt_BR_png__WEBPACK_IMPORTED_MODULE_103___default.a,
imagineRecordASound: _steps_imagine_record_a_sound_pt_BR_gif__WEBPACK_IMPORTED_MODULE_104___default.a,
imagineChooseSound: _steps_imagine_choose_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_105___default.a,
// Add a Backdrop
addBackdrop: _steps_add_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_106___default.a,
// Add Effects
addEffects: _steps_add_effects_pt_BR_png__WEBPACK_IMPORTED_MODULE_107___default.a,
// Hide and Show
hideAndShow: _steps_hide_show_pt_BR_png__WEBPACK_IMPORTED_MODULE_108___default.a,
// Switch Costumes
switchCostumes: _steps_switch_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_109___default.a,
// Change Size
changeSize: _steps_change_size_pt_BR_png__WEBPACK_IMPORTED_MODULE_110___default.a,
// Spin
spinTurn: _steps_spin_turn_pt_BR_png__WEBPACK_IMPORTED_MODULE_111___default.a,
spinPointInDirection: _steps_spin_point_in_direction_pt_BR_png__WEBPACK_IMPORTED_MODULE_112___default.a,
// Record a Sound
recordASoundSoundsTab: _steps_record_a_sound_sounds_tab_pt_BR_png__WEBPACK_IMPORTED_MODULE_113___default.a,
recordASoundClickRecord: _steps_record_a_sound_click_record_pt_BR_png__WEBPACK_IMPORTED_MODULE_114___default.a,
recordASoundPressRecordButton: _steps_record_a_sound_press_record_button_pt_BR_png__WEBPACK_IMPORTED_MODULE_115___default.a,
recordASoundChooseSound: _steps_record_a_sound_choose_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_116___default.a,
recordASoundPlayYourSound: _steps_record_a_sound_play_your_sound_pt_BR_png__WEBPACK_IMPORTED_MODULE_117___default.a,
// Use Arrow Keys
moveArrowKeysLeftRight: _steps_move_arrow_keys_left_right_pt_BR_png__WEBPACK_IMPORTED_MODULE_118___default.a,
moveArrowKeysUpDown: _steps_move_arrow_keys_up_down_pt_BR_png__WEBPACK_IMPORTED_MODULE_119___default.a,
// Glide Around
glideAroundBackAndForth: _steps_glide_around_back_and_forth_pt_BR_png__WEBPACK_IMPORTED_MODULE_120___default.a,
glideAroundPoint: _steps_glide_around_point_pt_BR_png__WEBPACK_IMPORTED_MODULE_121___default.a,
// Code a Cartoon
codeCartoonSaySomething: _steps_code_cartoon_01_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_122___default.a,
codeCartoonAnimate: _steps_code_cartoon_02_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_123___default.a,
codeCartoonSelectDifferentCharacter: _steps_code_cartoon_03_select_different_character_LTR_png__WEBPACK_IMPORTED_MODULE_124___default.a,
codeCartoonUseMinusSign: _steps_code_cartoon_04_use_minus_sign_pt_BR_png__WEBPACK_IMPORTED_MODULE_125___default.a,
codeCartoonGrowShrink: _steps_code_cartoon_05_grow_shrink_pt_BR_png__WEBPACK_IMPORTED_MODULE_126___default.a,
codeCartoonSelectDifferentCharacter2: _steps_code_cartoon_06_select_another_different_character_LTR_png__WEBPACK_IMPORTED_MODULE_127___default.a,
codeCartoonJump: _steps_code_cartoon_07_jump_pt_BR_png__WEBPACK_IMPORTED_MODULE_128___default.a,
codeCartoonChangeScenes: _steps_code_cartoon_08_change_scenes_pt_BR_png__WEBPACK_IMPORTED_MODULE_129___default.a,
codeCartoonGlideAround: _steps_code_cartoon_09_glide_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_130___default.a,
codeCartoonChangeCostumes: _steps_code_cartoon_10_change_costumes_pt_BR_png__WEBPACK_IMPORTED_MODULE_131___default.a,
codeCartoonChooseMoreCharacters: _steps_code_cartoon_11_choose_more_characters_LTR_png__WEBPACK_IMPORTED_MODULE_132___default.a,
// Talking Tales
talesAddExtension: _steps_speech_add_extension_pt_BR_gif__WEBPACK_IMPORTED_MODULE_3___default.a,
talesChooseSprite: _steps_talking_2_choose_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_133___default.a,
talesSaySomething: _steps_talking_3_say_something_pt_BR_png__WEBPACK_IMPORTED_MODULE_134___default.a,
talesAskAnswer: _steps_talking_13_ask_and_answer_pt_BR_png__WEBPACK_IMPORTED_MODULE_144___default.a,
talesChooseBackdrop: _steps_talking_4_choose_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_135___default.a,
talesSwitchBackdrop: _steps_talking_5_switch_backdrop_pt_BR_png__WEBPACK_IMPORTED_MODULE_136___default.a,
talesChooseAnotherSprite: _steps_talking_6_choose_another_sprite_LTR_png__WEBPACK_IMPORTED_MODULE_137___default.a,
talesMoveAround: _steps_talking_7_move_around_pt_BR_png__WEBPACK_IMPORTED_MODULE_138___default.a,
talesChooseAnotherBackdrop: _steps_talking_8_choose_another_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_139___default.a,
talesAnimateTalking: _steps_talking_9_animate_pt_BR_png__WEBPACK_IMPORTED_MODULE_140___default.a,
talesChooseThirdBackdrop: _steps_talking_10_choose_third_backdrop_LTR_png__WEBPACK_IMPORTED_MODULE_141___default.a,
talesChooseSound: _steps_talking_11_choose_sound_pt_BR_gif__WEBPACK_IMPORTED_MODULE_142___default.a,
talesDanceMoves: _steps_talking_12_dance_moves_pt_BR_png__WEBPACK_IMPORTED_MODULE_143___default.a
};
/***/ })
}]);
//# sourceMappingURL=pt_BR-steps.js.map
|
# -*- coding: utf-8 -*-
# Mocks for testing
import os
from xml.dom.minidom import parse
class Xbmc(object):
BACK = 1
LOGERROR = ['ERROR', 1]
LOGWARNING = ['WARNING', 2]
LOGNOTICE = ['NOTICE', 3]
LOGDEBUG = ['NOTICE', 4]
def __init__(self, level=LOGERROR):
self.level = level
class Keyboard(object):
def __init__(self, placeholder, header, hidden=False):
self.placeholder = placeholder
self.header = header
self.hidden = hidden
def doModal(self):
pass
def isConfirmed(self):
return True
def getText(self):
return 'bad'
def log(self, msg, level=LOGNOTICE):
if level[1] <= self.level[1]:
print msg
def translatePath(self, path):
if 'special://' in path:
return './' + path.split('special://')[1]
return path
class Player(object):
def play(self, *args, **kwargs):
print 'playing stream %s (%s)' % (kwargs['listitem'].infoLabels['Title'], kwargs['item'])
return Xbmc.BACK
class Xbmcplugin(object):
def __init__(self, xbmc):
self.xbmc = xbmc
self.dir_items = []
self.succeeded = False
def addDirectoryItem(self, handle, url, listitem, isFolder, totalItems=None):
self.dir_items.append((handle, url, listitem, isFolder))
self.xbmc.log('addDirectoryItem %s - %s' % (listitem.caption,
str(url)), Xbmc.LOGNOTICE)
def endOfDirectory(self, handle, succeeded=None, updateListing=None,
cacheToDisc=None):
self.succeeded = succeeded
def setResolvedUrl(self, handle, succeeded, listitem):
if succeeded:
msg = "start playing " + listitem.path
else:
msg = "could not find film"
self.xbmc.log(msg)
def reset(self):
self.dir_items = []
self.succeeded = False
class Xbmcgui(object):
class ListItem(object):
def __init__(self, *args, **kwargs):
if len(args) == 1:
self.caption = args[0]
self.properties = {}
def setInfo(self, type, infoLabels):
self.type = type
self.infoLabels = infoLabels
def setThumbnailImage(self, thumb_url):
pass
def setProperty(self, key, value):
self.properties[key] = value
def setPath(self, path):
self.path = path
class Dialog(object):
def ok(self, title, msg):
print '[DIALOG] %s - %s' % (title, msg)
return Xbmc.BACK
def select(self, title, alternatives):
print '[DIALOG SELECT] %s' % title
print "\n".join(alternatives)
return 0 # Select first one"
class Xbmcaddon(object):
class Addon:
def __init__(self, id=None):
self.pluginId = id
self.info = {'path': os.getcwd(), 'profile': os.getcwd()}
self.settings = {}
settingsFileName = 'resources/settings.xml'
if os.path.exists(settingsFileName):
self.readSettings(settingsFileName)
localSettingsFileName = 'localSettings.xml'
if os.path.exists(localSettingsFileName):
self.readSettings(localSettingsFileName)
self.strings = {}
for lang in ['Swedish', 'English']:
stringsFileName = 'resources/language/' + lang + '/strings.xml'
if not os.path.exists(stringsFileName): continue
doc = parse(stringsFileName)
for el in doc.getElementsByTagName('string'):
key = int(el.getAttribute('id'))
self.strings[key] = el.childNodes[0].data
break
self.readTestConfig()
self.info = {'path': os.getcwd(), 'profile': os.getcwd()}
def __del__(self):
self.writeTestConfig()
def readSettings(self, fileName):
doc = parse(fileName)
for el in doc.getElementsByTagName('setting'):
typ = el.getAttribute('type')
key = el.getAttribute('id')
if el.hasAttribute('value'):
value = el.getAttribute('value')
else:
value = el.getAttribute('default')
if typ == 'sep': continue
if typ == 'slider':
if el.getAttribute('option') == 'int':
typ = 'enum'
if typ == 'enum':
self.settings[key] = int(value)
else:
self.settings[key] = value
def readTestConfig(self):
testConfig = 'test.config'
if os.path.exists(testConfig):
doc = parse(testConfig)
for el in doc.getElementsByTagName('setting'):
typ = el.getAttribute('type')
key = el.getAttribute('id')
value = el.getAttribute('value')
if typ == 'int':
value = int(value)
self.setSetting(key, value)
def writeTestConfig(self):
testConfig = 'test.config'
if os.path.exists(testConfig):
doc = parse(testConfig)
for el in doc.getElementsByTagName('setting'):
key = el.getAttribute('id')
if key in self.settings:
el.setAttribute('value', str(self.settings[key]))
file = open(testConfig, 'w')
file.write(os.linesep.join(
[s for s in doc.toprettyxml().splitlines() if s.strip()]) +
os.linesep)
file.close()
def getLocalizedString(self, stringId):
if stringId in self.strings:
return self.strings[stringId]
else:
return "string not defined: " + str(stringId)
def getSetting(self, key):
if key in self.settings:
return self.settings[key]
return None
def setSetting(self, key, value):
self.settings[key] = value
def getAddonInfo(self, key):
if key in self.info:
return self.info[key]
return None
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _classnames = _interopRequireDefault(require("classnames"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireDefault(require("react"));
var _lib = require("../../lib");
/**
* A divider visually segments content into groups.
*/
function Divider(props) {
var children = props.children,
className = props.className,
clearing = props.clearing,
content = props.content,
fitted = props.fitted,
hidden = props.hidden,
horizontal = props.horizontal,
inverted = props.inverted,
section = props.section,
vertical = props.vertical;
var classes = (0, _classnames.default)('ui', (0, _lib.useKeyOnly)(clearing, 'clearing'), (0, _lib.useKeyOnly)(fitted, 'fitted'), (0, _lib.useKeyOnly)(hidden, 'hidden'), (0, _lib.useKeyOnly)(horizontal, 'horizontal'), (0, _lib.useKeyOnly)(inverted, 'inverted'), (0, _lib.useKeyOnly)(section, 'section'), (0, _lib.useKeyOnly)(vertical, 'vertical'), 'divider', className);
var rest = (0, _lib.getUnhandledProps)(Divider, props);
var ElementType = (0, _lib.getElementType)(Divider, props);
return _react.default.createElement(ElementType, (0, _extends2.default)({}, rest, {
className: classes
}), _lib.childrenUtils.isNil(children) ? content : children);
}
Divider.handledProps = ["as", "children", "className", "clearing", "content", "fitted", "hidden", "horizontal", "inverted", "section", "vertical"];
Divider.propTypes = process.env.NODE_ENV !== "production" ? {
/** An element type to render as (string or function). */
as: _lib.customPropTypes.as,
/** Primary content. */
children: _propTypes.default.node,
/** Additional classes. */
className: _propTypes.default.string,
/** Divider can clear the content above it. */
clearing: _propTypes.default.bool,
/** Shorthand for primary content. */
content: _lib.customPropTypes.contentShorthand,
/** Divider can be fitted without any space above or below it. */
fitted: _propTypes.default.bool,
/** Divider can divide content without creating a dividing line. */
hidden: _propTypes.default.bool,
/** Divider can segment content horizontally. */
horizontal: _propTypes.default.bool,
/** Divider can have its colours inverted. */
inverted: _propTypes.default.bool,
/** Divider can provide greater margins to divide sections of content. */
section: _propTypes.default.bool,
/** Divider can segment content vertically. */
vertical: _propTypes.default.bool
} : {};
var _default = Divider;
exports.default = _default;
|
import classNames from 'classnames';
import { arrayOf, bool, func, node, object, shape, string } from 'prop-types';
import React, { Component } from 'react';
import { FormattedMessage } from '../../util/reactIntl';
import css from './SelectSingleFilterPlain.css';
const getQueryParamName = queryParamNames => {
return Array.isArray(queryParamNames) ? queryParamNames[0] : queryParamNames;
};
class SelectSingleFilterPlain extends Component {
constructor(props) {
super(props);
this.state = { isOpen: true };
this.selectOption = this.selectOption.bind(this);
this.toggleIsOpen = this.toggleIsOpen.bind(this);
}
selectOption(option, e) {
const { queryParamNames, onSelect } = this.props;
const queryParamName = getQueryParamName(queryParamNames);
onSelect({ [queryParamName]: option });
// blur event target if event is passed
if (e && e.currentTarget) {
e.currentTarget.blur();
}
}
toggleIsOpen() {
this.setState({ isOpen: !this.state.isOpen });
}
render() {
const {
rootClassName,
className,
label,
options,
queryParamNames,
initialValues,
twoColumns,
useBullets,
} = this.props;
const queryParamName = getQueryParamName(queryParamNames);
const initialValue =
initialValues && initialValues[queryParamName] ? initialValues[queryParamName] : null;
const labelClass = initialValue ? css.filterLabelSelected : css.filterLabel;
const hasBullets = useBullets || twoColumns;
const optionsContainerClass = classNames({
[css.optionsContainerOpen]: this.state.isOpen,
[css.optionsContainerClosed]: !this.state.isOpen,
[css.hasBullets]: hasBullets,
[css.twoColumns]: twoColumns,
});
const classes = classNames(rootClassName || css.root, className);
return (
<div className={classes}>
<div className={labelClass}>
<button className={css.labelButton} onClick={this.toggleIsOpen}>
<span className={labelClass}>{label}</span>
</button>
<button className={css.clearButton} onClick={e => this.selectOption(null, e)}>
<FormattedMessage id={'SelectSingleFilter.plainClear'} />
</button>
</div>
<div className={optionsContainerClass}>
{options.map(option => {
// check if this option is selected
const selected = initialValue === option.key;
const optionClass = hasBullets && selected ? css.optionSelected : css.option;
// menu item selected bullet or border class
const optionBorderClass = hasBullets
? classNames({
[css.optionBulletSelected]: selected,
[css.optionBullet]: !selected,
})
: classNames({
[css.optionBorderSelected]: selected,
[css.optionBorder]: !selected,
});
return (
<button
key={option.key}
className={optionClass}
onClick={() => this.selectOption(option.key)}
>
<span className={optionBorderClass} />
{option.label}
</button>
);
})}
</div>
</div>
);
}
}
SelectSingleFilterPlain.defaultProps = {
rootClassName: null,
className: null,
initialValues: null,
twoColumns: false,
useBullets: false,
};
SelectSingleFilterPlain.propTypes = {
rootClassName: string,
className: string,
queryParamNames: arrayOf(string).isRequired,
label: node.isRequired,
onSelect: func.isRequired,
options: arrayOf(
shape({
key: string.isRequired,
label: string.isRequired,
})
).isRequired,
initialValues: object,
twoColumns: bool,
useBullets: bool,
};
export default SelectSingleFilterPlain;
|
# coding: utf-8
from PyQt5.QtWidgets import QWidget, QStackedLayout
from mhw_armor_edit.editor.models import EditorPlugin
from mhw_armor_edit.ftypes.wep_saxe import WepSaxe, WepSaxeEntry
from mhw_armor_edit.struct_table import StructTableModel, SortFilterTableView
class WepSaxeEditor(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.model = None
self.table_model = StructTableModel(WepSaxeEntry.fields(), self)
self.table_view = SortFilterTableView(self)
self.table_view.setModel(self.table_model)
self.setLayout(QStackedLayout(self))
self.layout().addWidget(self.table_view)
def set_model(self, model):
self.model = model
if model is None:
self.table_model.update([])
else:
self.table_model.update(model.data.entries)
class WepSaxePlugin(EditorPlugin):
pattern = "*.wep_saxe"
data_factory = WepSaxe
widget_factory = WepSaxeEditor
relations = {}
|
from pickle import dump, load
from shelve import open as o
from os import remove, path
class Serializer():
def __init__(self):
self.serialized_data = "serialized.p"
def serialize_a(self, data):
if path.isfile(self.serialized_data):
remove(self.serialized_data)
with o(self.serialized_data, 'c') as shelf:
shelf["js_class_data"] = data
def serialize_b(self, data):
with open(self.serialized_data, 'wb') as pfile:
dump(data, pfile)
def deserializer_a(self, args):
try:
with o(self.serialized_data, 'r') as shelf:
for key in shelf.keys():
print(repr(key), repr(shelf[key]))
if "-d" in args:
remove(f'{self.serialized_data}.bak')
remove(f'{self.serialized_data}.dat')
remove(f'{self.serialized_data}.dir')
except FileNotFoundError as file_not_found:
print("""Make a UML diagram using the create_uml command
and then use deserialize. Error Message: """ + str(file_not_found))
except:
print("""Use create_uml first. DB shelve error.
Error message: dbm.error: db file doesn't exist;
use 'c' or 'n' flag to create a new db""")
def deserializer_b(self, args):
try:
with open(self.serialized_data, 'rb') as pfile:
print(load(pfile))
if "-d" in args:
remove(self.serialized_data)
except FileNotFoundError as file_not_found:
print(f"""Generate a diagram using create_uml
before using deserialize. Error Message: {file_not_found}""")
|
#! /usr/bin/env python3
import sys
import json
from optparse import OptionParser
from glob import glob
try:
from collections.abc import Mapping
except ImportError: # Python 2.7 compatibility
from collections import Mapping
# Dict keys we merge into the same key in the real spec
MERGE_KEYS = ["paths", "definitions"]
HEADER_KEY = "headers"
ALL_PROPERTIES_KEY = "allProperties"
def update(d, u):
for k, v in list(u.items()):
if isinstance(v, Mapping):
r = update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d
def main():
parser = OptionParser()
parser.add_option("-f", "--file", help="Swagger API spec file to append")
parser.add_option("-j", "--json",
help="Directory containing json fragments")
parser.add_option("-o", "--out",
help="File to write the modified swagger spec to")
options, _ = parser.parse_args()
swagger_data = None
print(("Using base file {}".format(options.file)))
with open(options.file, 'r') as datafile:
swagger_data = json.loads(datafile.read())
if not swagger_data or not isinstance(swagger_data, dict):
print("Invalid swagger data")
sys.exit(-1)
for f in sorted(glob("{}/*.json".format(options.json))):
data = None
print(("Reading from {}".format(f)))
with open(f, 'r') as datafile:
data = json.loads(datafile.read())
if not data or not isinstance(data, dict):
print("Data file is invalid")
sys.exit(-1)
for key, value in list(data.items()):
if key in MERGE_KEYS:
if key not in swagger_data:
swagger_data[key] = {}
update(swagger_data[key], value)
elif key == HEADER_KEY:
for path, obj in list(swagger_data["paths"].items()):
if not isinstance(obj.get("parameters", None), list):
obj["parameters"] = []
obj["parameters"].extend(value)
elif key == ALL_PROPERTIES_KEY:
for model, obj in list(swagger_data["definitions"].items()):
if model not in value.get("exclude", []) and "parameters" in value:
swagger_data["definitions"][model]["properties"].update(value["parameters"])
pretty = json.dumps(swagger_data, indent=2, sort_keys=True)
print(("Writing data back to {}".format(options.out)))
with open(options.out, 'w') as datafile:
datafile.write(pretty)
if __name__ == "__main__":
main()
|
/*
* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
var moduleSearchIndex;
var packageSearchIndex;
var typeSearchIndex;
var memberSearchIndex;
var tagSearchIndex;
function loadScripts(doc, tag) {
createElem(doc, tag, 'jquery/jszip/dist/jszip.js');
createElem(doc, tag, 'jquery/jszip-utils/dist/jszip-utils.js');
if (window.navigator.userAgent.indexOf('MSIE ') > 0 || window.navigator.userAgent.indexOf('Trident/') > 0 ||
window.navigator.userAgent.indexOf('Edge/') > 0) {
createElem(doc, tag, 'jquery/jszip-utils/dist/jszip-utils-ie.js');
}
createElem(doc, tag, 'search.js');
$.get(pathtoroot + "module-search-index.zip")
.done(function() {
JSZipUtils.getBinaryContent(pathtoroot + "module-search-index.zip", function(e, data) {
var zip = new JSZip(data);
zip.load(data);
moduleSearchIndex = JSON.parse(zip.file("module-search-index.json").asText());
});
});
$.get(pathtoroot + "package-search-index.zip")
.done(function() {
JSZipUtils.getBinaryContent(pathtoroot + "package-search-index.zip", function(e, data) {
var zip = new JSZip(data);
zip.load(data);
packageSearchIndex = JSON.parse(zip.file("package-search-index.json").asText());
});
});
$.get(pathtoroot + "type-search-index.zip")
.done(function() {
JSZipUtils.getBinaryContent(pathtoroot + "type-search-index.zip", function(e, data) {
var zip = new JSZip(data);
zip.load(data);
typeSearchIndex = JSON.parse(zip.file("type-search-index.json").asText());
});
});
$.get(pathtoroot + "member-search-index.zip")
.done(function() {
JSZipUtils.getBinaryContent(pathtoroot + "member-search-index.zip", function(e, data) {
var zip = new JSZip(data);
zip.load(data);
memberSearchIndex = JSON.parse(zip.file("member-search-index.json").asText());
});
});
$.get(pathtoroot + "tag-search-index.zip")
.done(function() {
JSZipUtils.getBinaryContent(pathtoroot + "tag-search-index.zip", function(e, data) {
var zip = new JSZip(data);
zip.load(data);
tagSearchIndex = JSON.parse(zip.file("tag-search-index.json").asText());
});
});
if (!moduleSearchIndex) {
createElem(doc, tag, 'module-search-index.js');
}
if (!packageSearchIndex) {
createElem(doc, tag, 'package-search-index.js');
}
if (!typeSearchIndex) {
createElem(doc, tag, 'type-search-index.js');
}
if (!memberSearchIndex) {
createElem(doc, tag, 'member-search-index.js');
}
if (!tagSearchIndex) {
createElem(doc, tag, 'tag-search-index.js');
}
$(window).resize(function() {
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
});
}
function createElem(doc, tag, path) {
var script = doc.createElement(tag);
var scriptElement = doc.getElementsByTagName(tag)[0];
script.src = pathtoroot + path;
scriptElement.parentNode.insertBefore(script, scriptElement);
}
function show(type) {
count = 0;
for (var key in data) {
var row = document.getElementById(key);
if ((data[key] & type) !== 0) {
row.style.display = '';
row.className = (count++ % 2) ? rowColor : altColor;
}
else
row.style.display = 'none';
}
updateTabs(type);
}
function updateTabs(type) {
for (var value in tabs) {
var sNode = document.getElementById(tabs[value][0]);
var spanNode = sNode.firstChild;
if (value == type) {
sNode.className = activeTableTab;
spanNode.innerHTML = tabs[value][1];
}
else {
sNode.className = tableTab;
spanNode.innerHTML = "<a href=\"javascript:show("+ value + ");\">" + tabs[value][1] + "</a>";
}
}
}
function updateModuleFrame(pFrame, cFrame) {
top.packageFrame.location = pFrame;
top.classFrame.location = cFrame;
}
|
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, August 24, 2019 at 9:49:39 PM Mountain Standard Time
* Operating System: Version 12.4 (Build 16M568)
* Image Source: /System/Library/Frameworks/TVServices.framework/TVServices
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@protocol OS_os_log, TVSBluetoothManagerDelegate;
@class NSRecursiveLock, NSMutableArray, NSMutableSet, NSObject, NSSet;
@interface TVSBluetoothManager : NSObject {
NSRecursiveLock* _lock;
NSMutableArray* _allBTDevices;
NSMutableSet* _observers;
NSObject*<OS_os_log> _log;
long long _scanningState;
BOOL _discovering;
BOOL _finishedSetup;
NSSet* _connectedDevices;
NSSet* _pairedDevices;
NSSet* _discoveredDevices;
id<TVSBluetoothManagerDelegate> _delegate;
}
@property (nonatomic,copy) NSSet * connectedDevices; //@synthesize connectedDevices=_connectedDevices - In the implementation block
@property (nonatomic,copy) NSSet * pairedDevices; //@synthesize pairedDevices=_pairedDevices - In the implementation block
@property (nonatomic,copy) NSSet * discoveredDevices; //@synthesize discoveredDevices=_discoveredDevices - In the implementation block
@property (assign,nonatomic,__weak) id<TVSBluetoothManagerDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block
@property (getter=isPairing,nonatomic,readonly) BOOL pairing;
+(id)sharedInstance;
-(NSSet *)pairedDevices;
-(void)startScanning;
-(void)stopScanning;
-(NSSet *)discoveredDevices;
-(BOOL)isPairing;
-(id)__init;
-(NSSet *)connectedDevices;
-(void)setConnectedDevices:(NSSet *)arg1 ;
-(BOOL)filterDeviceScan;
-(void)_addBluetoothDevice:(id)arg1 ;
-(void)setPairedDevices:(NSSet *)arg1 ;
-(void)setDiscoveredDevices:(NSSet *)arg1 ;
-(void)_discoveredPeripheralsDidChangeNotification:(id)arg1 ;
-(void)_peripheralStateDidChangeNotification:(id)arg1 ;
-(void)_bluetoothAvailabilityChanged:(id)arg1 ;
-(void)_bluetoothDeviceRemoved:(id)arg1 ;
-(void)_bluetoothConnectionSuccess:(id)arg1 ;
-(void)_bluetoothConnectionFailed:(id)arg1 ;
-(void)_bluetoothDisconnectSuccess:(id)arg1 ;
-(void)_bluetoothDisconnectFailed:(id)arg1 ;
-(void)_bluetoothDidUnpair:(id)arg1 ;
-(void)_bluetoothPairingPINRequest:(id)arg1 ;
-(void)_bluetoothPairingPINResultSuccess:(id)arg1 ;
-(void)_bluetoothPairingPINResultFailed:(id)arg1 ;
-(void)_bluetoothPowerStateChanged:(id)arg1 ;
-(void)_bluetoothNotificationHandler:(id)arg1 ;
-(void)_updateDevicesLists;
-(unsigned long long)_pairingDeviceCount;
-(void)addScanObserver:(id)arg1 ;
-(void)_updateScanningStateIfNeeded;
-(void)removeScanObserver:(id)arg1 ;
-(id)bluetoothDeviceForBTLEPeripheral:(id)arg1 ;
-(void)_removeBluetoothDevice:(id)arg1 ;
-(void)_startBluetoothDeviceDiscovery;
-(id)bluetoothDeviceForClassicBluetoothDevice:(id)arg1 ;
-(void)cancelPINPairing;
-(void)_checkDeviceStatus;
-(void)_stopBluetoothDeviceDiscovery;
-(id)bluetoothDeviceWithIdentifier:(id)arg1 ;
-(void)connectDevice:(id)arg1 ;
-(void)disconnectDevice:(id)arg1 ;
-(void)unpairDevice:(id)arg1 ;
-(void)setFilterDeviceScan:(BOOL)arg1 ;
-(id)init;
-(void)dealloc;
-(void)setDelegate:(id<TVSBluetoothManagerDelegate>)arg1 ;
-(void)removeObserver:(id)arg1 ;
-(id<TVSBluetoothManagerDelegate>)delegate;
-(void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void*)arg4 ;
-(void)addObserver:(id)arg1 ;
@end
|
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
from tencentcloud.common.abstract_model import AbstractModel
class ApplyStackRequest(AbstractModel):
"""ApplyStack请求参数结构体
"""
def __init__(self):
"""
:param StackId: 资源栈ID
:type StackId: str
:param VersionId: 待执行apply事件的版本ID
:type VersionId: str
"""
self.StackId = None
self.VersionId = None
def _deserialize(self, params):
self.StackId = params.get("StackId")
self.VersionId = params.get("VersionId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class ApplyStackResponse(AbstractModel):
"""ApplyStack返回参数结构体
"""
def __init__(self):
"""
:param EventId: 执行的事件ID
:type EventId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventId = None
self.RequestId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class CreateStackRequest(AbstractModel):
"""CreateStack请求参数结构体
"""
def __init__(self):
"""
:param StackName: 资源栈名称,不得超过60个字符
:type StackName: str
:param StackRegion: 资源栈所在地域
:type StackRegion: str
:param TemplateUrl: HCL模板URL,⽬前仅限 COS URL, ⽂件为zip压缩格式
:type TemplateUrl: str
:param Description: 资源栈描述,不得超过200个字符
:type Description: str
"""
self.StackName = None
self.StackRegion = None
self.TemplateUrl = None
self.Description = None
def _deserialize(self, params):
self.StackName = params.get("StackName")
self.StackRegion = params.get("StackRegion")
self.TemplateUrl = params.get("TemplateUrl")
self.Description = params.get("Description")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class CreateStackResponse(AbstractModel):
"""CreateStack返回参数结构体
"""
def __init__(self):
"""
:param StackId: 创建得到的资源栈ID
:type StackId: str
:param VersionId: 资源栈版本ID
:type VersionId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.StackId = None
self.VersionId = None
self.RequestId = None
def _deserialize(self, params):
self.StackId = params.get("StackId")
self.VersionId = params.get("VersionId")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class CreateStackVersionRequest(AbstractModel):
"""CreateStackVersion请求参数结构体
"""
def __init__(self):
"""
:param StackId: 待增加版本的资源栈ID
:type StackId: str
:param TemplateUrl: 模板 URL,⽬前仅限 COS URL, ⽂件为zip压缩格式
:type TemplateUrl: str
:param VersionName: 版本名称,不得超过60个字符
:type VersionName: str
:param Description: 版本描述,不得超过200个字符
:type Description: str
"""
self.StackId = None
self.TemplateUrl = None
self.VersionName = None
self.Description = None
def _deserialize(self, params):
self.StackId = params.get("StackId")
self.TemplateUrl = params.get("TemplateUrl")
self.VersionName = params.get("VersionName")
self.Description = params.get("Description")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class CreateStackVersionResponse(AbstractModel):
"""CreateStackVersion返回参数结构体
"""
def __init__(self):
"""
:param VersionId: 新创建的版本ID
:type VersionId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.VersionId = None
self.RequestId = None
def _deserialize(self, params):
self.VersionId = params.get("VersionId")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DeleteStackRequest(AbstractModel):
"""DeleteStack请求参数结构体
"""
def __init__(self):
"""
:param StackId: 待删除的资源栈ID
:type StackId: str
"""
self.StackId = None
def _deserialize(self, params):
self.StackId = params.get("StackId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DeleteStackResponse(AbstractModel):
"""DeleteStack返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DeleteStackVersionRequest(AbstractModel):
"""DeleteStackVersion请求参数结构体
"""
def __init__(self):
"""
:param VersionId: 待删除的版本ID
:type VersionId: str
"""
self.VersionId = None
def _deserialize(self, params):
self.VersionId = params.get("VersionId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DeleteStackVersionResponse(AbstractModel):
"""DeleteStackVersion返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DescribeStackEventRequest(AbstractModel):
"""DescribeStackEvent请求参数结构体
"""
def __init__(self):
"""
:param EventId: 事件ID
:type EventId: str
"""
self.EventId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DescribeStackEventResponse(AbstractModel):
"""DescribeStackEvent返回参数结构体
"""
def __init__(self):
"""
:param EventId: 事件ID
:type EventId: str
:param VersionId: 版本ID
:type VersionId: str
:param StackId: 资源栈ID
:type StackId: str
:param Type: 事件类型
:type Type: str
:param Status: 事件状态
:type Status: str
:param EventMessage: 状态信息
:type EventMessage: str
:param CreateTime: 创建时间
:type CreateTime: str
:param ConsoleLog: 控制台输出文本
:type ConsoleLog: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventId = None
self.VersionId = None
self.StackId = None
self.Type = None
self.Status = None
self.EventMessage = None
self.CreateTime = None
self.ConsoleLog = None
self.RequestId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
self.VersionId = params.get("VersionId")
self.StackId = params.get("StackId")
self.Type = params.get("Type")
self.Status = params.get("Status")
self.EventMessage = params.get("EventMessage")
self.CreateTime = params.get("CreateTime")
self.ConsoleLog = params.get("ConsoleLog")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DescribeStackEventsRequest(AbstractModel):
"""DescribeStackEvents请求参数结构体
"""
def __init__(self):
"""
:param EventIds: 按照⼀个或者多个事件ID查询
:type EventIds: list of str
:param Filters: <li>**VersionId**</li>
按照【**版本ID**】过滤,VersionId形如 `ver-kg8hn58h`
类型:string
<li>**StackId**</li>
按照【**资源栈ID**】过滤,StackId形如 `stk-hz5vn3te`
类型:string
<li>**Type**</li>
按照【**事件类型**】过滤,Type 形如 plan, apply, destroy
类型:string
<li>**Status**</li>
按照【**事件状态**】过滤,Status形如 queueing, running, success, failed
类型:string
:type Filters: list of Filter
:param Offset: 偏移量,默认为0。关于Offset的更进一步介绍请参考 API [简介](https://cloud.tencent.com/document/api/213/15688)中的相关小节
:type Offset: int
:param Limit: 返回数量,默认为20,最大值为100。关于Limit的更进一步介绍请参考 API [简介](https://cloud.tencent.com/document/api/213/15688)中的相关小节
:type Limit: int
"""
self.EventIds = None
self.Filters = None
self.Offset = None
self.Limit = None
def _deserialize(self, params):
self.EventIds = params.get("EventIds")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = Filter()
obj._deserialize(item)
self.Filters.append(obj)
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DescribeStackEventsResponse(AbstractModel):
"""DescribeStackEvents返回参数结构体
"""
def __init__(self):
"""
:param TotalCount: 符合条件的事件数量
:type TotalCount: int
:param Events: 事件详细信息列表
:type Events: list of EventInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.Events = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("Events") is not None:
self.Events = []
for item in params.get("Events"):
obj = EventInfo()
obj._deserialize(item)
self.Events.append(obj)
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DescribeStackVersionsRequest(AbstractModel):
"""DescribeStackVersions请求参数结构体
"""
def __init__(self):
"""
:param VersionIds: 按照⼀个或者多个版本ID查询
:type VersionIds: list of str
:param Offset: 偏移量,默认为0。关于Offset的更进一步介绍请参考 API [简介](https://cloud.tencent.com/document/api/213/15688)中的相关小节
:type Offset: int
:param Limit: 返回数量,默认为20,最大值为100。关于Limit的更进一步介绍请参考 API [简介](https://cloud.tencent.com/document/api/213/15688)中的相关小节
:type Limit: int
:param Filters: <li>**Name**</li>
按照【**版本名称**】进行过滤
类型:string
<li>**Status**</li>
按照【**版本状态**】过滤,形如`VERSION_EDITING`,`PLAN_IN_PROGRESS`等
类型:string
<li>**StackId**</li>
按照版本所属的【**资源栈ID**】进行过滤,形如`stk-xxxxxx`
类型:string
:type Filters: list of Filter
"""
self.VersionIds = None
self.Offset = None
self.Limit = None
self.Filters = None
def _deserialize(self, params):
self.VersionIds = params.get("VersionIds")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = Filter()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DescribeStackVersionsResponse(AbstractModel):
"""DescribeStackVersions返回参数结构体
"""
def __init__(self):
"""
:param TotalCount: 符合条件的版本数量
:type TotalCount: int
:param Versions: 版本详细信息列表
:type Versions: list of VersionInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.Versions = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("Versions") is not None:
self.Versions = []
for item in params.get("Versions"):
obj = VersionInfo()
obj._deserialize(item)
self.Versions.append(obj)
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DescribeStacksRequest(AbstractModel):
"""DescribeStacks请求参数结构体
"""
def __init__(self):
"""
:param StackIds: 按照⼀个或者多个资源栈ID查询
:type StackIds: list of str
:param Offset: 偏移量,默认为0。关于Offset的更进一步介绍请参考 API [简介](https://cloud.tencent.com/document/api/213/15688)中的相关小节。
:type Offset: int
:param Limit: 返回数量,默认为20,最大值为100。关于Limit的更进一步介绍请参考 API [简介](https://cloud.tencent.com/document/api/213/15688)中的相关小节。
:type Limit: int
"""
self.StackIds = None
self.Offset = None
self.Limit = None
def _deserialize(self, params):
self.StackIds = params.get("StackIds")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DescribeStacksResponse(AbstractModel):
"""DescribeStacks返回参数结构体
"""
def __init__(self):
"""
:param TotalCount: 符合条件的资源栈数量
:type TotalCount: int
:param Stacks: 资源栈详细信息列表
:type Stacks: list of StackInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.Stacks = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("Stacks") is not None:
self.Stacks = []
for item in params.get("Stacks"):
obj = StackInfo()
obj._deserialize(item)
self.Stacks.append(obj)
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DestroyStackRequest(AbstractModel):
"""DestroyStack请求参数结构体
"""
def __init__(self):
"""
:param StackId: 资源栈ID
:type StackId: str
:param VersionId: 待执行destroy事件的版本ID
:type VersionId: str
"""
self.StackId = None
self.VersionId = None
def _deserialize(self, params):
self.StackId = params.get("StackId")
self.VersionId = params.get("VersionId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class DestroyStackResponse(AbstractModel):
"""DestroyStack返回参数结构体
"""
def __init__(self):
"""
:param EventId: 事件ID
:type EventId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventId = None
self.RequestId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class EventInfo(AbstractModel):
"""事件详情
"""
def __init__(self):
"""
:param EventId: 事件ID
:type EventId: str
:param VersionId: 版本ID
:type VersionId: str
:param StackId: 资源栈ID
:type StackId: str
:param Type: 事件类型
:type Type: str
:param Status: 版本状态
:type Status: str
:param Message: 状态信息
:type Message: str
:param CreateTime: 创建时间
:type CreateTime: str
"""
self.EventId = None
self.VersionId = None
self.StackId = None
self.Type = None
self.Status = None
self.Message = None
self.CreateTime = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
self.VersionId = params.get("VersionId")
self.StackId = params.get("StackId")
self.Type = params.get("Type")
self.Status = params.get("Status")
self.Message = params.get("Message")
self.CreateTime = params.get("CreateTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class Filter(AbstractModel):
"""查询过滤条件
"""
def __init__(self):
"""
:param Name: 条件名字
:type Name: str
:param Values: 匹配的值,可以有多个
:type Values: list of str
"""
self.Name = None
self.Values = None
def _deserialize(self, params):
self.Name = params.get("Name")
self.Values = params.get("Values")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class PlanStackRequest(AbstractModel):
"""PlanStack请求参数结构体
"""
def __init__(self):
"""
:param StackId: 资源栈ID
:type StackId: str
:param VersionId: 待执行plan事件的版本ID
:type VersionId: str
"""
self.StackId = None
self.VersionId = None
def _deserialize(self, params):
self.StackId = params.get("StackId")
self.VersionId = params.get("VersionId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class PlanStackResponse(AbstractModel):
"""PlanStack返回参数结构体
"""
def __init__(self):
"""
:param EventId: 执行的事件ID
:type EventId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventId = None
self.RequestId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class StackInfo(AbstractModel):
"""资源栈信息
"""
def __init__(self):
"""
:param StackId: 资源栈ID
:type StackId: str
:param StackName: 资源栈名称
:type StackName: str
:param Description: 资源栈描述
:type Description: str
:param Region: 所处地域
:type Region: str
:param Status: 资源栈状态
:type Status: str
:param CreateTime: 创建时间
:type CreateTime: str
"""
self.StackId = None
self.StackName = None
self.Description = None
self.Region = None
self.Status = None
self.CreateTime = None
def _deserialize(self, params):
self.StackId = params.get("StackId")
self.StackName = params.get("StackName")
self.Description = params.get("Description")
self.Region = params.get("Region")
self.Status = params.get("Status")
self.CreateTime = params.get("CreateTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class UpdateStackRequest(AbstractModel):
"""UpdateStack请求参数结构体
"""
def __init__(self):
"""
:param StackId: 待更新的资源栈ID
:type StackId: str
:param StackName: 资源栈名称,不得超过60个字符
:type StackName: str
:param Description: 资源栈描述,不得超过200个字符
:type Description: str
"""
self.StackId = None
self.StackName = None
self.Description = None
def _deserialize(self, params):
self.StackId = params.get("StackId")
self.StackName = params.get("StackName")
self.Description = params.get("Description")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class UpdateStackResponse(AbstractModel):
"""UpdateStack返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class UpdateStackVersionRequest(AbstractModel):
"""UpdateStackVersion请求参数结构体
"""
def __init__(self):
"""
:param VersionId: 待更新的版本ID
:type VersionId: str
:param TemplateUrl: 模板 URL,⽬前仅限 COS URL, ⽂件为zip压缩格式
:type TemplateUrl: str
:param VersionName: 版本名称,不得超过60个字符
:type VersionName: str
:param Description: 版本描述,不得超过200个字符
:type Description: str
"""
self.VersionId = None
self.TemplateUrl = None
self.VersionName = None
self.Description = None
def _deserialize(self, params):
self.VersionId = params.get("VersionId")
self.TemplateUrl = params.get("TemplateUrl")
self.VersionName = params.get("VersionName")
self.Description = params.get("Description")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class UpdateStackVersionResponse(AbstractModel):
"""UpdateStackVersion返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class VersionInfo(AbstractModel):
"""版本信息
"""
def __init__(self):
"""
:param VersionId: 版本ID
:type VersionId: str
:param VersionName: 版本名称
:type VersionName: str
:param Description: 版本描述
:type Description: str
:param StackId: 资源栈ID
:type StackId: str
:param Status: 版本状态
:type Status: str
:param CreateTime: 创建时间
:type CreateTime: str
"""
self.VersionId = None
self.VersionName = None
self.Description = None
self.StackId = None
self.Status = None
self.CreateTime = None
def _deserialize(self, params):
self.VersionId = params.get("VersionId")
self.VersionName = params.get("VersionName")
self.Description = params.get("Description")
self.StackId = params.get("StackId")
self.Status = params.get("Status")
self.CreateTime = params.get("CreateTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
|
__version__ = "1.0.1"
__all__ = ['websocket_connections', 'zeromq_connection', 'config_manager', 'main']
|
({
/**
* Change Log:
* 3 April 2020
* Updated error handling logError
* Added onPrevious to return to previous flow screen
*/
handleSubmit : function(component, event, helper) {
event.preventDefault(); // stop form submission
let userEditForm = component.find("userEditForm") ;
let fields = event.getParam('fields');
let profileId = component.get("v.profileId") ;
fields.ProfileId = profileId ;
fields.Id = (component.get("v.userId") != '' ) ? component.get("v.userId") : '' ;
component.set("v.UserSObject", fields );
component.find('userEditForm').submit(fields);
$A.util.addClass( component.find('errorMessageAccordion'), 'slds-hide');
},
logError : function(component, event, helper) {
let warningMessage = "We received the below errors when attempting to save: \n" ;
let fieldErrorMessages = JSON.parse(JSON.stringify( event.getParam("output").fieldErrors)) ;
try{
for (const property in fieldErrorMessages) {
warningMessage+= "\n " + property + " " + JSON.stringify(fieldErrorMessages[property][0]) ;
}
$A.util.removeClass( component.find('errorMessageAccordion'), 'slds-hide');
component.set("v.errorMessage", warningMessage);
}catch(err){
//Couldnt parse the error
$A.util.removeClass( component.find('errorMessageAccordion'), 'slds-hide');
warningMessage += "We couldn't parse the error message correctly : \n" +JSON.stringify( event.getParam("output").fieldErrors) ;
component.set("v.errorMessage", warningMessage)
}
console.log("Error occurred: " ,JSON.parse(JSON.stringify(event.getParams() ))) ;
},
contactLoaded : function(component, event, helper) {
if(component.get("v.fieldList").length === 0){
let fieldInputs = (component.get("v.userId") ) ? helper.defaultFieldsDisplay(component) : helper.defaultNewUser(component) ;
$A.createComponents(fieldInputs,
function(components, status, errorMessage){
if (status === "SUCCESS") {
component.set("v.fieldList", components)
}
else if (status === "INCOMPLETE") {
console.log("No response from server or client is offline.")
// Show offline error
}
else if (status === "ERROR") {
console.log("Error: " + errorMessage);
}
} ) ;
}
},
onPrevious: function(component,event,helper){
let navigate = component.get("v.navigateFlow");
navigate("BACK");
},
onSuccess: function(component,event,helper){
component.set("v.userId", event.getParam("response").id) ;
helper.showToast("Success", "User was created successfully", "success" );
let navigate = component.get("v.navigateFlow");
navigate("NEXT");
},
recordLoadError : function(component, event, helper) {
console.log("Error occurred: " , JSON.parse(JSON.stringify(event.getParams() ))) ;
}
})
|
import React from 'react';
import './LoadingElement.scss';
import classNames from 'classnames';
export default class LoadingElement extends React.Component {
render() {
const elementClasses = classNames({
'loading-element': true,
[this.props.className]: true
});
return(
<span className={elementClasses}>
<svg width="20px" height="20px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid"><rect x="0" y="0" width="100" height="100" fill="none"/><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(0 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(30 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.08333333333333333s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(60 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.16666666666666666s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(90 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.25s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(120 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.3333333333333333s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(150 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.4166666666666667s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(180 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.5s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(210 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.5833333333333334s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(240 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.6666666666666666s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(270 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.75s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(300 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.8333333333333334s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#ffffff" transform="rotate(330 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="1s" begin="0.9166666666666666s" repeatCount="indefinite"/></rect></svg>
</span>
);
}
}
LoadingElement.propTypes = {
className: React.PropTypes.string
};
|
(this["webpackJsonpstreamlit-browser"]=this["webpackJsonpstreamlit-browser"]||[]).push([[12],{1182:function(t,n){t.exports=function(t){var n=typeof t;return null!=t&&("object"==n||"function"==n)}},1185:function(t,n,r){var o=r(1250),e="object"==typeof self&&self&&self.Object===Object&&self,i=o||e||Function("return this")();t.exports=i},1189:function(t,n){t.exports=function(t){return null!=t&&"object"==typeof t}},1196:function(t,n,r){var o=r(1200),e=r(1281),i=r(1282),u=o?o.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":u&&u in Object(t)?e(t):i(t)}},1200:function(t,n,r){var o=r(1185).Symbol;t.exports=o},1201:function(t,n,r){var o=r(1389),e=r(1392);t.exports=function(t,n){var r=e(t,n);return o(r)?r:void 0}},1204:function(t,n,r){var o=r(1222),e=r(1232);t.exports=function(t){return null!=t&&e(t.length)&&!o(t)}},1213:function(t,n){t.exports=function(t,n){return t===n||t!==t&&n!==n}},1214:function(t,n,r){var o=r(1213);t.exports=function(t,n){for(var r=t.length;r--;)if(o(t[r][0],n))return r;return-1}},1215:function(t,n,r){var o=r(1201)(Object,"create");t.exports=o},1216:function(t,n,r){var o=r(1401);t.exports=function(t,n){var r=t.__data__;return o(n)?r["string"==typeof n?"string":"hash"]:r.map}},1222:function(t,n,r){var o=r(1196),e=r(1182);t.exports=function(t){if(!e(t))return!1;var n=o(t);return"[object Function]"==n||"[object GeneratorFunction]"==n||"[object AsyncFunction]"==n||"[object Proxy]"==n}},1232:function(t,n){t.exports=function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}},1247:function(t,n){t.exports=function(t){return t}},1250:function(t,n,r){(function(n){var r="object"==typeof n&&n&&n.Object===Object&&n;t.exports=r}).call(this,r(45))},1254:function(t,n,r){var o=r(1384),e=r(1385),i=r(1386),u=r(1387),c=r(1388);function a(t){var n=-1,r=null==t?0:t.length;for(this.clear();++n<r;){var o=t[n];this.set(o[0],o[1])}}a.prototype.clear=o,a.prototype.delete=e,a.prototype.get=i,a.prototype.has=u,a.prototype.set=c,t.exports=a},1281:function(t,n,r){var o=r(1200),e=Object.prototype,i=e.hasOwnProperty,u=e.toString,c=o?o.toStringTag:void 0;t.exports=function(t){var n=i.call(t,c),r=t[c];try{t[c]=void 0;var o=!0}catch(a){}var e=u.call(t);return o&&(n?t[c]=r:delete t[c]),e}},1282:function(t,n){var r=Object.prototype.toString;t.exports=function(t){return r.call(t)}},1288:function(t,n,r){var o=r(1201)(r(1185),"Map");t.exports=o},1289:function(t,n,r){var o=r(1393),e=r(1400),i=r(1402),u=r(1403),c=r(1404);function a(t){var n=-1,r=null==t?0:t.length;for(this.clear();++n<r;){var o=t[n];this.set(o[0],o[1])}}a.prototype.clear=o,a.prototype.delete=e,a.prototype.get=i,a.prototype.has=u,a.prototype.set=c,t.exports=a},1291:function(t,n){t.exports=function(t){return function(n){return t(n)}}},1322:function(t,n){var r=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return r.call(t)}catch(n){}try{return t+""}catch(n){}}return""}},1367:function(t,n){t.exports=function(t,n){for(var r=-1,o=null==t?0:t.length,e=Array(o);++r<o;)e[r]=n(t[r],r,t);return e}},1369:function(t,n,r){var o=r(1201),e=function(){try{var t=o(Object,"defineProperty");return t({},"",{}),t}catch(n){}}();t.exports=e},1384:function(t,n){t.exports=function(){this.__data__=[],this.size=0}},1385:function(t,n,r){var o=r(1214),e=Array.prototype.splice;t.exports=function(t){var n=this.__data__,r=o(n,t);return!(r<0)&&(r==n.length-1?n.pop():e.call(n,r,1),--this.size,!0)}},1386:function(t,n,r){var o=r(1214);t.exports=function(t){var n=this.__data__,r=o(n,t);return r<0?void 0:n[r][1]}},1387:function(t,n,r){var o=r(1214);t.exports=function(t){return o(this.__data__,t)>-1}},1388:function(t,n,r){var o=r(1214);t.exports=function(t,n){var r=this.__data__,e=o(r,t);return e<0?(++this.size,r.push([t,n])):r[e][1]=n,this}},1389:function(t,n,r){var o=r(1222),e=r(1390),i=r(1182),u=r(1322),c=/^\[object .+?Constructor\]$/,a=Function.prototype,s=Object.prototype,f=a.toString,p=s.hasOwnProperty,l=RegExp("^"+f.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return!(!i(t)||e(t))&&(o(t)?l:c).test(u(t))}},1390:function(t,n,r){var o=r(1391),e=function(){var t=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();t.exports=function(t){return!!e&&e in t}},1391:function(t,n,r){var o=r(1185)["__core-js_shared__"];t.exports=o},1392:function(t,n){t.exports=function(t,n){return null==t?void 0:t[n]}},1393:function(t,n,r){var o=r(1394),e=r(1254),i=r(1288);t.exports=function(){this.size=0,this.__data__={hash:new o,map:new(i||e),string:new o}}},1394:function(t,n,r){var o=r(1395),e=r(1396),i=r(1397),u=r(1398),c=r(1399);function a(t){var n=-1,r=null==t?0:t.length;for(this.clear();++n<r;){var o=t[n];this.set(o[0],o[1])}}a.prototype.clear=o,a.prototype.delete=e,a.prototype.get=i,a.prototype.has=u,a.prototype.set=c,t.exports=a},1395:function(t,n,r){var o=r(1215);t.exports=function(){this.__data__=o?o(null):{},this.size=0}},1396:function(t,n){t.exports=function(t){var n=this.has(t)&&delete this.__data__[t];return this.size-=n?1:0,n}},1397:function(t,n,r){var o=r(1215),e=Object.prototype.hasOwnProperty;t.exports=function(t){var n=this.__data__;if(o){var r=n[t];return"__lodash_hash_undefined__"===r?void 0:r}return e.call(n,t)?n[t]:void 0}},1398:function(t,n,r){var o=r(1215),e=Object.prototype.hasOwnProperty;t.exports=function(t){var n=this.__data__;return o?void 0!==n[t]:e.call(n,t)}},1399:function(t,n,r){var o=r(1215);t.exports=function(t,n){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=o&&void 0===n?"__lodash_hash_undefined__":n,this}},1400:function(t,n,r){var o=r(1216);t.exports=function(t){var n=o(this,t).delete(t);return this.size-=n?1:0,n}},1401:function(t,n){t.exports=function(t){var n=typeof t;return"string"==n||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==t:null===t}},1402:function(t,n,r){var o=r(1216);t.exports=function(t){return o(this,t).get(t)}},1403:function(t,n,r){var o=r(1216);t.exports=function(t){return o(this,t).has(t)}},1404:function(t,n,r){var o=r(1216);t.exports=function(t,n){var r=o(this,t),e=r.size;return r.set(t,n),this.size+=r.size==e?0:1,this}},1405:function(t,n,r){var o=r(1289),e=r(1406),i=r(1407);function u(t){var n=-1,r=null==t?0:t.length;for(this.__data__=new o;++n<r;)this.add(t[n])}u.prototype.add=u.prototype.push=e,u.prototype.has=i,t.exports=u},1406:function(t,n){t.exports=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this}},1407:function(t,n){t.exports=function(t){return this.__data__.has(t)}},1408:function(t,n){t.exports=function(t,n){return t.has(n)}},1481:function(t,n,r){var o=r(1204),e=r(1189);t.exports=function(t){return e(t)&&o(t)}},1482:function(t,n,r){var o=r(1247),e=r(1483),i=r(1485);t.exports=function(t,n){return i(e(t,n,o),t+"")}},1483:function(t,n,r){var o=r(1484),e=Math.max;t.exports=function(t,n,r){return n=e(void 0===n?t.length-1:n,0),function(){for(var i=arguments,u=-1,c=e(i.length-n,0),a=Array(c);++u<c;)a[u]=i[n+u];u=-1;for(var s=Array(n+1);++u<n;)s[u]=i[u];return s[n]=r(a),o(t,this,s)}}},1484:function(t,n){t.exports=function(t,n,r){switch(r.length){case 0:return t.call(n);case 1:return t.call(n,r[0]);case 2:return t.call(n,r[0],r[1]);case 3:return t.call(n,r[0],r[1],r[2])}return t.apply(n,r)}},1485:function(t,n,r){var o=r(1486),e=r(1488)(o);t.exports=e},1486:function(t,n,r){var o=r(1487),e=r(1369),i=r(1247),u=e?function(t,n){return e(t,"toString",{configurable:!0,enumerable:!1,value:o(n),writable:!0})}:i;t.exports=u},1487:function(t,n){t.exports=function(t){return function(){return t}}},1488:function(t,n){var r=Date.now;t.exports=function(t){var n=0,o=0;return function(){var e=r(),i=16-(e-o);if(o=e,i>0){if(++n>=800)return arguments[0]}else n=0;return t.apply(void 0,arguments)}}},2434:function(t,n,r){var o=r(2435),e=r(1482),i=r(1481),u=e((function(t,n){return i(t)?o(t,n):[]}));t.exports=u},2435:function(t,n,r){var o=r(1405),e=r(2436),i=r(2441),u=r(1367),c=r(1291),a=r(1408);t.exports=function(t,n,r,s){var f=-1,p=e,l=!0,h=t.length,v=[],_=n.length;if(!h)return v;r&&(n=u(n,c(r))),s?(p=i,l=!1):n.length>=200&&(p=a,l=!1,n=new o(n));t:for(;++f<h;){var x=t[f],y=null==r?x:r(x);if(x=s||0!==x?x:0,l&&y===y){for(var d=_;d--;)if(n[d]===y)continue t;v.push(x)}else p(n,y,s)||v.push(x)}return v}},2436:function(t,n,r){var o=r(2437);t.exports=function(t,n){return!!(null==t?0:t.length)&&o(t,n,0)>-1}},2437:function(t,n,r){var o=r(2438),e=r(2439),i=r(2440);t.exports=function(t,n,r){return n===n?i(t,n,r):o(t,e,r)}},2438:function(t,n){t.exports=function(t,n,r,o){for(var e=t.length,i=r+(o?1:-1);o?i--:++i<e;)if(n(t[i],i,t))return i;return-1}},2439:function(t,n){t.exports=function(t){return t!==t}},2440:function(t,n){t.exports=function(t,n,r){for(var o=r-1,e=t.length;++o<e;)if(t[o]===n)return o;return-1}},2441:function(t,n){t.exports=function(t,n,r){for(var o=-1,e=null==t?0:t.length;++o<e;)if(r(n,t[o]))return!0;return!1}}}]);
//# sourceMappingURL=12.86661a0b.chunk.js.map
|
/**
* Copyright (c) 2018, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt
* of any required approvals from the U.S. Dept. of Energy).
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import "./App.css";
import React, {Component} from 'react';
import { HashRouter as Router, Route, Switch } from "react-router-dom";
import Prism from "prismjs"; // eslint-disable-line
import "prismjs/components/prism-typescript";
import "prismjs/themes/prism.css";
import Intro from "./components/Intro";
import Guide from "./components/Guide";
import Example from "./components/Example";
import API from "./components/API";
import Header from './Header';
import Sidebar from './Sidebar';
import ScrollToTop from "./ScrollToTop";
import {bodyStyle, mainStyle, contentStyle} from './styles';
class App extends Component {
render() {
return(
<Router>
<div style={bodyStyle}>
<Header />
<Route component={ScrollToTop} />
<div style={mainStyle}>
<div style={contentStyle}>
{" "}
<Switch>
<Route exact path="/" component={Intro}/>
<Route path="/guide/:doc" component={Guide} />
<Route path="/example/:example" component={Example} />
<Route path="/api/:component" component={API} />
</Switch>
</div>
<Sidebar />
</div>
</div>
</Router>
)
}
}
export default App;
|
#include <syscall.h>
#include <process.h>
#include <scheduler.h>
#include <kprintf.h>
#include <trap.h>
#include <types.h>
#include <sysapi.h>
static int (*syscalls[])() = {
[SYS_PRINT] = print
};
// 获取cpu当前正在执行的进程
static inline struct process*
curproc()
{
struct cpu *curcpu = current_cpu();
return curcpu->curprocess;
}
void
syscall_handler(struct trapframe *tf)
{
syscall();
}
void
syscall_init()
{
register_trap_handler(IRQ_SYSCALL, syscall_handler);
}
// 获取addr处的int参数值,
// 成功返回0,失败返回-1
int
fetch_int(uint_t addr, int *res)
{
struct process *proc = curproc();
if(addr>=proc->size || (addr + 4)>proc->size){
return -1;
}
*res = *(int*)addr;
return 0;
}
// 获取addr处字符串,
// 成功返回字符串长度,失败返回-1
int
fetch_str(uint_t addr, char **res)
{
struct process *proc = curproc();
if(addr>=proc->size){
return -1;
}
*res = (char*)addr;
char *s, *ep;
ep = (char*)proc->size;
for(s=*res; s<ep; s++){
if(*s==0){
return s - *res;
}
}
return -1;
}
// 第n个int参数
int
argint(int n, int *res)
{
struct process *proc = curproc();
return fetch_int((proc->tf->esp)+n*4+4, res);
}
// 第n个指针参数
int
argptr(int n, char **res, int size)
{
int addr;
struct process *proc = curproc();
if(argint(n, &addr)<0){
return -1;
}
if(size<0 || (uint_t)addr>=proc->size || (uint_t)addr+size>proc->size){
return -1;
}
*res = (char*)addr;
return 0;
}
// 第n个字符串参数
int
argstr(int n, char **res)
{
int addr;
if(argint(n, &addr)<0){
return -1;
}
return fetch_str(addr, res);
}
void
syscall()
{
struct cpu *curcpu = current_cpu();
struct process *curproc = curcpu->curprocess;
int idx = curproc->tf->eax;
if(idx > 0 && syscalls[idx]){
curproc->tf->eax = syscalls[idx]();
}else{
kprintf("%d %s: unknown system call %d!\n",
curproc->pid, curproc->name, idx);
curproc->tf->eax = -1;
}
}
|
import React from 'react';
const User = ({user}) => {
return (
<li key={user.id} >
<span className="user">{user.name}</span>
</li>
)
}
export default User;
|
# -*- encoding:utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ..base import activations
from ..base.activations import Sigmoid, Relu, Identity
from ..base.initializers import xavier_uniform_initializer
from ..layers.layer import Layer
from ..ops import _check_convolution_layer
class Filter(object):
def __init__(self, filter_shape, initializer):
"""
Filter,过滤器,滤波器
# Params
filter_shape: (filter_height, filter_width, input_depth)
initializer: 滤波器的初始化方法
"""
assert len(filter_shape) == 3
self.filter_shape = filter_shape
self.__W = initializer(filter_shape) # filter权重矩阵
self.__b = 0. # filter偏置bias
self.__delta_W = np.zeros(filter_shape) # filter的权重矩阵梯度
self.__delta_b = 0. # filter的偏置梯度
@property
def W(self):
return self.__W
@property
def b(self):
return self.__b
@property
def delta_W(self):
return self.__delta_W
@property
def delta_b(self):
return self.__delta_b
@W.setter
def W(self, W):
self.__W = W
@b.setter
def b(self, b):
self.__b = b
@delta_W.setter
def delta_W(self, delta_W):
self.__delta_W = delta_W
@delta_b.setter
def delta_b(self, delta_b):
self.__delta_b = delta_b
def update(self):
self.__W -= self.__delta_W
self.__b -= self.__delta_b
class Conv2d(Layer):
def __init__(self, filter_size, filter_num, input_shape=None,
zero_padding=0, stride=1, activator=Relu, initializer=xavier_uniform_initializer):
"""
二维卷积层,考虑输入包含width于height(除去输入的batch size与depth)
# Params
filter_size: 格式为(height, width),代表输入的每个filter的尺寸
filter_num: filter个数
input_shape: 格式为(batch, height, width, depth),代表输入数据的形状
zero_padding: zero-padding数, int or tuple
stride: 步长,int or tuple, 可以输入(stride_height, stride_width) 或 stride
控制输出的feature map的大小
activator: 激活函数(如tanh、sigmoid或relu)
initializer: 所有filter的权重矩阵与偏置向量的初始化方法
"""
# 判定输入的参数zero_padding是否合法
super(Conv2d, self).__init__()
if isinstance(zero_padding, int):
zero_padding = (zero_padding, zero_padding)
# 其余参数检验
_check_convolution_layer(filter_size, filter_num, zero_padding, stride)
self.input_shape = input_shape
self.filter_size = filter_size
self.filter_num = filter_num
self.output_shape = None
self.zero_padding = zero_padding
self.activator = activations.get(activator)
self.initializer = initializer
self.stride = stride if isinstance(stride, list) or isinstance(stride, tuple) \
else (stride, stride)
if self.input_shape is not None:
self.connection(None)
@property
def delta(self):
return self.__delta
@property
def W(self):
return [filter.W for filter in self.filters]
@property
def b(self):
return [filter.b for filter in self.filters]
@property
def delta_W(self):
return [filter.delta_W for filter in self.filters]
@property
def delta_b(self):
return [filter.delta_b for filter in self.filters]
@property
def params(self):
return self.W + self.b
@property
def grads(self):
return self.delta_W + self.delta_b
def call(self, pre_layer=None, *args, **kwargs):
self.connection(pre_layer)
return self
def connection(self, pre_layer):
"""
用来连接各个层的控制函数,输入前一层的Layer对象,并与当前层的Layer对象连接。
# Params
pre_layer: 之前的一层Layer对象
"""
if pre_layer is None:
if self.input_shape is None:
raise ValueError('input_shape must not be `None` as the first layer.')
else:
self.input_shape = pre_layer.output_shape
self.pre_layer = pre_layer
pre_layer.next_layer = self
assert len(self.input_shape) == 4
# 计算输出的shape
if self.output_shape is None:
self.output_shape = self._calc_output_shape(self.input_shape, self.filter_size,
self.stride, self.zero_padding, self.filter_num)
# 增加需要学习的filters
self.filters = [Filter(list(self.filter_size) + [self.input_shape[3]], self.initializer)
for _ in xrange(self.filter_num)]
def forward(self, input, *args, **kwargs):
"""
输入input,经过卷积后得到新的特征图(feature map)
# Params
input: 输入的feature map,形状为(batch_size, height, width, depth)
# Return: 经过该层的输出结果
"""
self.input = np.asarray(input)
assert list(self.input_shape[1:]) == list(self.input.shape[1:])
self.input_shape = self.input.shape
self.output_shape[0] = self.input.shape[0]
# add logit
self.logit = np.zeros(self.output_shape)
# add output
self.output = np.zeros(self.output_shape)
assert list(self.input.shape[1:]) == list(self.input_shape[1:])
# 如果需要补零padding,则进行padding操作
self.padded_input = self._padding(self.input, self.zero_padding)
# 将每个filter作用在input样本上,得到filter_num个output的feature map
for o_c, filter in enumerate(self.filters):
filter_W = filter.W
filter_b = filter.b
for bn in xrange(self.input_shape[0]):
# 关键步骤,实现卷积
self._conv(self.padded_input[bn], filter_W,
self.logit[bn,:,:,o_c], filter_b, self.stride)
self.output = self.activator.forward(self.logit)
return self.output
def backward(self, pre_delta_map, *args, **kwargs):
"""
通过从前一层传递过来的误差计算当前各个参数(filters的参数)的梯度。
# Params
pre_delta_map: 从前一层传递的梯度,形状与当前层的输出output一致
"""
# 当前层误差
self.__delta = np.zeros(self.input_shape)
pre_delta_map = pre_delta_map * self.activator.backward(self.logit)
# 按照stride对feature map进行扩展,在中间填充零
expanded_pre_delta_map = self.__expand_sensitive_map(pre_delta_map)
expanded_batch, expanded_height, expanded_width, expanded_channel = \
expanded_pre_delta_map.shape
# expanded_height + 2*pad - filter_height + 1 = input_height
zero_padding = [0, 0]
zero_padding[0] = (self.input_shape[1] + self.filter_size[0] - expanded_height - 1) // 2
zero_padding[1] = (self.input_shape[2] + self.filter_size[1] - expanded_width - 1) // 2
zero_padding[0] = max(0, zero_padding[0])
zero_padding[1] = max(0, zero_padding[1])
# 对误差的feature map进行zero-padding
padded_delta_map = self._padding(expanded_pre_delta_map, zero_padding)
# 对每个filter进行梯度计算
for i, filter in enumerate(self.filters):
rot_weights = np.zeros(filter.W.shape)
for c in xrange(rot_weights.shape[2]):
rot_weights[:,:,c] = np.rot90(filter.W[:,:,c], 2)
delta_a = np.zeros(self.input_shape)
for i_c in xrange(self.input_shape[3]):
for bn in xrange(self.input_shape[0]):
# calculate delta_{l-1}
self._conv(padded_delta_map[bn,:,:,i], rot_weights[:,:,i_c],
delta_a[bn,:,:,i_c], 0, (1, 1))
# calclulate gradient of w
self._conv(self.padded_input[bn,:,:,i_c], expanded_pre_delta_map[bn,:,:,i],
filter.delta_W[:,:,i_c], 0, (1, 1))
filter.delta_W = filter.delta_W / self.input.shape[0]
filter.delta_b = np.sum(expanded_pre_delta_map[:,:,:,i]) / self.input.shape[0]
self.__delta += delta_a
# backward delta_{l-1}
self.__delta *= self.activator.backward(self.input)
return self.delta
def _padding(self, inputs, zero_padding):
"""
对输入的feature map进行零填充
# Params
inputs: 输入的feature map
zero_padding: 需要填充的零的个数,输入是一个二元tuple,分别表示填充在高度和宽度上的零的个数
"""
inputs = np.asarray(inputs)
if list(zero_padding) == [0, 0]:
return inputs
if inputs.ndim == 3:
inputs = inputs[:,:,:,None]
if inputs.ndim == 4:
input_batch, input_height, input_width, input_channel = inputs.shape
padded_input = np.zeros([input_batch, input_height + 2 * zero_padding[0],
input_width + 2 * zero_padding[1], input_channel])
padded_input[:, zero_padding[0]:input_height + zero_padding[0],
zero_padding[1]:input_width + zero_padding[1], :] = inputs
return padded_input
else:
raise ValueError('Your input must be a 3-D or 4-D tensor.')
def _conv(self, inputs, filter_W, outputs, filter_b, stride):
"""
卷积操作。
# Params
inputs: 输入的feature map
filter_W: 当前滤波器的W
outputs: 输出的feature map
filter_b: 当前滤波器的b
stride: 步长
"""
inputs = np.asarray(inputs)
if inputs.ndim == 2:
inputs = inputs[:,:,None]
elif inputs.ndim == 3:
inputs = inputs
else:
raise ValueError('Your input must be a 2-D or 3-D tensor.')
if filter_W.ndim == 2:
filter_W = filter_W[:,:,None]
elif filter_W.ndim == 3:
filter_W = filter_W
else:
raise ValueError('Your filter_W must be a 2-D or 3-D tensor.')
i_height, i_width, _ = inputs.shape
o_height, o_width = outputs.shape
stride_height, stride_width = stride
f_height, f_width, _ = filter_W.shape
bw = bh = 0
eh = f_height; ew = f_width
# 卷积操作
for idx_height in xrange(o_height):
for idx_width in xrange(o_width):
if eh > i_height or ew > i_width:
break
outputs[idx_height,idx_width] = \
np.sum(inputs[bh:eh,bw:ew,:] * filter_W) + filter_b
bw += stride_width
ew += stride_width
bh += stride_height
eh += stride_height
bw = 0; ew = f_width
def __expand_sensitive_map(self, pre_delta_map):
"""
根据stride对梯度map进行零填充,用于梯度计算
"""
batch, height, width, depth = pre_delta_map.shape
stride_height, stride_width = self.stride
expanded_height = (height - 1) * stride_height + 1
expanded_width = (width - 1) * stride_width + 1
expanded_pre_delta_map = np.zeros([batch, expanded_height, expanded_width, depth])
for i in xrange(height):
for j in xrange(width):
expanded_pre_delta_map[:, stride_height * i,
stride_width * j, :] = pre_delta_map[:,i,j,:]
return expanded_pre_delta_map
def _calc_output_size(self, input_len, filter_len, stride, zero_padding):
"""
根据当前长度、stride大小以及零填充大小,判定输出长度。
# Params
input_len: 输入长度(可以是feature map的宽度或高度)
filter_len: filter的长度(对应的filter的宽度或高度)
stride: 步长
zero_padding: 零填充的长度(单侧)
"""
return (input_len + 2 * zero_padding - filter_len) // stride + 1
def _calc_output_shape(self, input_shape, filter_shape, stride, zero_padding, filter_num):
"""
计算output的shape,这个shape也是回传的误差的shape
"""
output_height = self._calc_output_size(input_shape[1], filter_shape[0],
stride[0], zero_padding[0])
output_width = self._calc_output_size(input_shape[2], filter_shape[1],
stride[1], zero_padding[1])
output_channel = filter_num
return [input_shape[0], output_height, output_width, output_channel]
|
//
// Fcgo_publicNetworkTools.h
// Fcgo
//
// Created by huafanxiao on 2017/5/16.
// Copyright © 2017年 huafanxiao. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Fcgo_publicNetworkTools : NSObject
/*
typedef void(^RequestSuccessBlock)(NSMutableArray *mutableArray);
typedef void(^RequestFailBlock)(void);
//请求地址数据
+ (void)postRequestAreaLocalListSuccessBlock:(RequestSuccessBlock)successBlock
failureBlock:(RequestFailBlock)failBlock;
*/
@end
|
import contextlib
from typing import Optional
import discord
import random
from redbot.core import commands
from redbot.core.utils.chat_formatting import bold, box
class TextEditor(commands.Cog):
"""
Edit and manipulate with text.
"""
__author__ = ["Kreusada"]
__version__ = "2.0.0"
def __init__(self, bot):
self.bot = bot
def format_help_for_context(self, ctx: commands.Context) -> str:
context = super().format_help_for_context(ctx)
authors = ", ".join(self.__author__)
return f"{context}\n\nAuthor: {authors}\nVersion: {self.__version__}"
async def red_delete_data_for_user(self, **kwargs):
"""
Nothing to delete
"""
return
def cog_unload(self):
with contextlib.suppress(Exception):
self.bot.remove_dev_env_value("texteditor")
async def initialize(self) -> None:
if 719988449867989142 in self.bot.owner_ids:
with contextlib.suppress(Exception):
self.bot.add_dev_env_value("texteditor", lambda x: self)
@commands.group()
async def editor(self, ctx: commands.Context):
"""Base command for editting text."""
@editor.command(name="charcount")
async def editor_charcount(self, ctx: commands.Context, include_spaces: Optional[bool] = True, *, text: str):
"""Count the number of characters appearing in the text."""
if include_spaces:
await ctx.send("Character count (with spaces): {}".format(bold(str(len(text)))))
else:
await ctx.send("Character count: {}".format(bold(str(len(text) - text.count(" ")))))
@editor.command(name="wordcount")
async def editor_wordcount(self, ctx: commands.Context, *, text: str):
"""Count the number of words appearing in the text."""
count = 0
for word in text.split():
if word.isspace():
continue
count += 1
await ctx.send("Word count: {}".format(bold(str(count))))
@editor.command(name="occurance")
async def editor_occurance(self, ctx: commands.Context, check: str, *, text: str):
"""Count how many times something appears in the text."""
counter = text.count(check)
plural_check = "once" if counter == 1 else f"{counter} times"
await ctx.send("`{}` is present in the text {}.".format(str(check), bold(plural_check)))
@editor.command(name="upper")
async def editor_upper(self, ctx: commands.Context, *, text: str):
"""Convert the text to uppercase."""
await ctx.send(box(text.upper()))
@editor.command(name="lower")
async def editor_lower(self, ctx: commands.Context, *, text: str):
"""Convert the text to lowercase."""
await ctx.send(box(text.lower()))
@editor.command(name="title")
async def editor_title(self, ctx: commands.Context, *, text: str):
"""Convert the text to titlecase."""
await ctx.send(box(text.title()))
@editor.command(name="snake")
async def editor_snake(self, ctx: commands.Context, *, text: str):
"""Convert all spaces to underscores."""
snake = lambda x: x.replace(" ", "_")
await ctx.send(box(snake(text)))
@editor.command(name="alternating")
async def editor_alternating(self, ctx: commands.Context, *, text: str):
"""Convert the text to alternating case."""
text = list(text)
text[0::2] = map(str.upper, text[0::2])
text[1::2] = map(str.lower, text[1::2])
await ctx.send(box("".join(text)))
@editor.command(name="replace")
async def editor_replace(
self,
ctx: commands.Context,
text_to_replace: str,
replacement: str,
*,
text: str
):
"""Replace certain parts of the text."""
replace = lambda x: x.replace(text_to_replace, replacement)
await ctx.send(box(replace(text)))
@editor.command(name="squash")
async def editor_squash(self, ctx: commands.Context, *, text: str):
"""Squash all the words into one."""
await ctx.send(box(text.replace(" ", "")))
@editor.command(name="remove")
async def editor_remove(self, ctx: commands.Context, remove: str, *, text: str):
"""Remove something from the text."""
await ctx.send(box(text.replace(remove, "")))
@editor.command(name="trim", aliases=["strip"], usage='[trimmer=" "] <text>')
async def editor_trim(self, ctx: commands.Context, trimmer: Optional[str] = " ", *, text: str):
"""Trim the outskirts of the text."""
await ctx.send(box(text.strip(trimmer).strip()))
@editor.command(name="shuffle", aliases=["jumble"])
async def editor_shuffle(self, ctx: commands.Context, *, text: str):
"""Completely shuffle the text."""
data = text.split()
random.shuffle(data)
await ctx.send(box(" ".join(data)))
@editor.command(name="reverse")
async def editor_reverse(self, ctx: commands.Context, *, text: str):
"""Reverse the text."""
await ctx.send(box(text[::-1]))
|
if (IS_DEV_SERVER) {
if (module.hot) {
module.hot.accept();
module.hot.addStatusHandler((status) => {
if (status === 'prepare') {
console.clear();
}
});
}
}
|
"""
PASSENGERS
"""
numPassengers = 1373
passenger_arriving = (
(0, 5, 7, 2, 0, 0, 2, 1, 1, 1, 0, 0), # 0
(1, 5, 5, 4, 2, 0, 1, 3, 4, 6, 1, 0), # 1
(1, 3, 5, 0, 0, 0, 3, 4, 2, 1, 1, 0), # 2
(2, 1, 4, 0, 2, 0, 2, 6, 4, 2, 1, 0), # 3
(3, 5, 3, 5, 0, 0, 4, 2, 3, 2, 1, 0), # 4
(2, 4, 4, 0, 3, 0, 4, 0, 2, 0, 0, 0), # 5
(1, 8, 4, 5, 0, 0, 4, 2, 6, 3, 3, 0), # 6
(2, 7, 4, 0, 1, 0, 2, 5, 2, 1, 2, 0), # 7
(1, 4, 2, 2, 3, 0, 1, 1, 5, 2, 0, 0), # 8
(2, 1, 1, 2, 2, 0, 2, 4, 2, 3, 1, 0), # 9
(3, 3, 4, 3, 0, 0, 9, 6, 3, 1, 2, 0), # 10
(4, 1, 3, 0, 0, 0, 6, 3, 6, 0, 1, 0), # 11
(2, 3, 2, 2, 1, 0, 1, 3, 0, 3, 2, 0), # 12
(3, 4, 2, 3, 2, 0, 3, 4, 2, 1, 1, 0), # 13
(0, 3, 2, 4, 1, 0, 2, 2, 1, 2, 0, 0), # 14
(1, 5, 2, 2, 1, 0, 2, 5, 3, 2, 0, 0), # 15
(1, 2, 1, 1, 3, 0, 4, 1, 0, 0, 2, 0), # 16
(1, 2, 6, 2, 1, 0, 5, 5, 3, 0, 2, 0), # 17
(1, 2, 2, 1, 2, 0, 1, 7, 5, 0, 2, 0), # 18
(1, 5, 2, 0, 0, 0, 5, 7, 2, 0, 0, 0), # 19
(2, 6, 3, 3, 2, 0, 3, 5, 1, 2, 1, 0), # 20
(2, 2, 2, 1, 1, 0, 3, 2, 2, 4, 1, 0), # 21
(4, 3, 4, 2, 1, 0, 4, 4, 3, 1, 3, 0), # 22
(4, 3, 1, 1, 0, 0, 3, 1, 3, 0, 2, 0), # 23
(1, 5, 4, 3, 0, 0, 3, 3, 1, 2, 1, 0), # 24
(2, 5, 3, 0, 0, 0, 3, 1, 2, 3, 0, 0), # 25
(3, 9, 3, 4, 1, 0, 3, 2, 3, 3, 1, 0), # 26
(0, 4, 3, 0, 0, 0, 1, 4, 2, 2, 1, 0), # 27
(3, 4, 4, 2, 1, 0, 4, 7, 6, 1, 0, 0), # 28
(0, 3, 3, 1, 1, 0, 4, 6, 3, 3, 2, 0), # 29
(4, 2, 3, 3, 0, 0, 2, 6, 4, 4, 1, 0), # 30
(2, 5, 6, 0, 0, 0, 4, 5, 1, 1, 0, 0), # 31
(3, 4, 2, 1, 0, 0, 2, 3, 4, 1, 2, 0), # 32
(2, 7, 3, 0, 2, 0, 3, 3, 4, 1, 0, 0), # 33
(2, 2, 3, 0, 0, 0, 2, 2, 2, 2, 1, 0), # 34
(3, 2, 3, 0, 1, 0, 5, 5, 3, 2, 1, 0), # 35
(0, 8, 4, 2, 1, 0, 4, 2, 5, 2, 0, 0), # 36
(2, 2, 3, 0, 3, 0, 4, 5, 3, 3, 1, 0), # 37
(0, 9, 2, 0, 1, 0, 2, 3, 3, 2, 1, 0), # 38
(1, 4, 2, 2, 3, 0, 3, 5, 1, 2, 1, 0), # 39
(3, 3, 1, 2, 1, 0, 5, 1, 9, 2, 0, 0), # 40
(1, 6, 2, 1, 0, 0, 2, 2, 1, 2, 3, 0), # 41
(3, 3, 0, 2, 1, 0, 3, 6, 1, 3, 1, 0), # 42
(2, 2, 3, 0, 0, 0, 3, 1, 5, 2, 1, 0), # 43
(2, 3, 0, 1, 1, 0, 1, 3, 1, 3, 0, 0), # 44
(0, 5, 7, 0, 1, 0, 3, 4, 2, 1, 4, 0), # 45
(2, 2, 3, 3, 2, 0, 2, 2, 1, 2, 1, 0), # 46
(4, 5, 2, 1, 1, 0, 1, 2, 0, 0, 1, 0), # 47
(3, 3, 5, 1, 0, 0, 3, 4, 1, 2, 0, 0), # 48
(1, 7, 6, 1, 0, 0, 1, 3, 3, 5, 1, 0), # 49
(2, 0, 2, 1, 0, 0, 2, 2, 4, 2, 1, 0), # 50
(0, 6, 2, 3, 3, 0, 4, 4, 3, 2, 2, 0), # 51
(2, 6, 4, 1, 0, 0, 2, 5, 1, 1, 2, 0), # 52
(2, 2, 2, 0, 0, 0, 1, 4, 1, 0, 0, 0), # 53
(2, 3, 3, 3, 3, 0, 3, 3, 4, 3, 1, 0), # 54
(1, 1, 5, 3, 1, 0, 4, 4, 4, 0, 2, 0), # 55
(1, 2, 4, 1, 1, 0, 5, 1, 0, 5, 0, 0), # 56
(1, 3, 2, 2, 0, 0, 4, 0, 0, 2, 0, 0), # 57
(3, 4, 3, 3, 0, 0, 2, 6, 3, 2, 1, 0), # 58
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # 59
)
station_arriving_intensity = (
(1.5897909350307289, 4.077876420454546, 4.7965416131105405, 3.8017663043478263, 4.285817307692308, 2.8540760869565225), # 0
(1.6047132060286802, 4.123224959227694, 4.822449322514998, 3.8229386322463776, 4.317939903846154, 2.853103283514493), # 1
(1.6194650863330406, 4.167900841750842, 4.84774207369323, 3.8436449275362325, 4.349384615384616, 2.8521007246376815), # 2
(1.6340340539947322, 4.211855859375001, 4.8724013897814915, 3.863867527173913, 4.380122596153847, 2.851068546195653), # 3
(1.6484075870646768, 4.25504180345118, 4.896408793916025, 3.883588768115943, 4.410125000000001, 2.850006884057971), # 4
(1.662573163593796, 4.297410465330389, 4.919745809233077, 3.902790987318841, 4.439362980769231, 2.848915874094203), # 5
(1.6765182616330119, 4.338913636363637, 4.942393958868896, 3.9214565217391315, 4.467807692307693, 2.8477956521739136), # 6
(1.690230359233246, 4.379503107901936, 4.964334765959726, 3.939567708333334, 4.49543028846154, 2.8466463541666673), # 7
(1.7036969344454203, 4.419130671296296, 4.985549753641818, 3.9571068840579713, 4.522201923076924, 2.845468115942029), # 8
(1.7169054653204567, 4.457748117897728, 5.006020445051415, 3.974056385869566, 4.5480937500000005, 2.8442610733695655), # 9
(1.7298434299092773, 4.49530723905724, 5.025728363324765, 3.9903985507246387, 4.573076923076924, 2.8430253623188406), # 10
(1.7424983062628039, 4.5317598261258425, 5.044655031598115, 4.0061157155797105, 4.597122596153847, 2.841761118659421), # 11
(1.7548575724319582, 4.567057670454545, 5.062781973007713, 4.021190217391305, 4.620201923076923, 2.8404684782608696), # 12
(1.7669087064676616, 4.601152563394361, 5.080090710689803, 4.035604393115943, 4.642286057692309, 2.839147576992754), # 13
(1.7786391864208373, 4.6339962962962975, 5.096562767780633, 4.049340579710145, 4.663346153846154, 2.8377985507246377), # 14
(1.7900364903424055, 4.665540660511364, 5.112179667416452, 4.062381114130435, 4.683353365384616, 2.8364215353260875), # 15
(1.8010880962832896, 4.695737447390573, 5.126922932733506, 4.074708333333334, 4.702278846153847, 2.835016666666667), # 16
(1.8117814822944105, 4.724538448284933, 5.1407740868680385, 4.0863045742753625, 4.720093750000001, 2.833584080615943), # 17
(1.8221041264266904, 4.751895454545455, 5.1537146529563, 4.097152173913044, 4.736769230769233, 2.8321239130434788), # 18
(1.8320435067310508, 4.777760257523148, 5.165726154134534, 4.107233469202899, 4.752276442307693, 2.830636299818841), # 19
(1.841587101258414, 4.802084648569023, 5.176790113538988, 4.11653079710145, 4.76658653846154, 2.8291213768115946), # 20
(1.850722388059702, 4.82482041903409, 5.186888054305914, 4.125026494565218, 4.779670673076923, 2.827579279891305), # 21
(1.8594368451858356, 4.845919360269361, 5.196001499571551, 4.1327028985507255, 4.7915, 2.8260101449275368), # 22
(1.867717950687738, 4.865333263625843, 5.204111972472152, 4.139542346014493, 4.802045673076924, 2.8244141077898557), # 23
(1.8755531826163303, 4.8830139204545455, 5.211200996143959, 4.145527173913044, 4.811278846153846, 2.8227913043478265), # 24
(1.8829300190225344, 4.898913122106482, 5.217250093723223, 4.150639719202899, 4.819170673076923, 2.8211418704710147), # 25
(1.8898359379572727, 4.91298265993266, 5.222240788346188, 4.15486231884058, 4.825692307692308, 2.819465942028986), # 26
(1.8962584174714663, 4.9251743252840905, 5.2261546031491, 4.15817730978261, 4.830814903846155, 2.817763654891305), # 27
(1.9021849356160379, 4.935439909511785, 5.22897306126821, 4.160567028985508, 4.834509615384616, 2.8160351449275365), # 28
(1.9076029704419084, 4.943731203966752, 5.23067768583976, 4.162013813405798, 4.836747596153847, 2.814280548007247), # 29
(1.9125000000000003, 4.950000000000001, 5.231250000000001, 4.1625000000000005, 4.8375, 2.8125000000000004), # 30
(1.9170822170716115, 4.955207279829545, 5.230820969202899, 4.162412193627452, 4.837226196808512, 2.8100257558720645), # 31
(1.92156550511509, 4.960345738636365, 5.229546014492754, 4.162150490196079, 4.836410638297873, 2.8062148550724646), # 32
(1.925951878196931, 4.96541473721591, 5.227443342391306, 4.161717463235295, 4.83506210106383, 2.8011046101949026), # 33
(1.9302433503836318, 4.970413636363637, 5.22453115942029, 4.161115686274511, 4.833189361702129, 2.794732333833084), # 34
(1.9344419357416882, 4.975341796875, 5.22082767210145, 4.160347732843138, 4.830801196808512, 2.78713533858071), # 35
(1.9385496483375964, 4.980198579545456, 5.216351086956522, 4.1594161764705895, 4.827906382978725, 2.7783509370314845), # 36
(1.9425685022378518, 4.9849833451704555, 5.211119610507247, 4.158323590686275, 4.824513696808511, 2.768416441779111), # 37
(1.9465005115089515, 4.989695454545455, 5.2051514492753626, 4.157072549019608, 4.820631914893617, 2.757369165417291), # 38
(1.9503476902173915, 4.994334268465909, 5.1984648097826085, 4.155665625000001, 4.816269813829788, 2.7452464205397304), # 39
(1.9541120524296678, 4.998899147727274, 5.191077898550725, 4.154105392156863, 4.811436170212766, 2.73208551974013), # 40
(1.9577956122122764, 5.003389453125, 5.18300892210145, 4.152394424019608, 4.806139760638298, 2.717923775612195), # 41
(1.9614003836317138, 5.0078045454545475, 5.174276086956523, 4.150535294117647, 4.800389361702129, 2.702798500749626), # 42
(1.9649283807544762, 5.0121437855113635, 5.164897599637682, 4.148530575980393, 4.794193750000001, 2.6867470077461273), # 43
(1.968381617647059, 5.01640653409091, 5.154891666666668, 4.146382843137255, 4.78756170212766, 2.6698066091954025), # 44
(1.971762108375959, 5.0205921519886365, 5.144276494565219, 4.1440946691176475, 4.780501994680852, 2.652014617691155), # 45
(1.9750718670076732, 5.024700000000001, 5.133070289855074, 4.141668627450981, 4.77302340425532, 2.633408345827087), # 46
(1.978312907608696, 5.028729438920456, 5.121291259057971, 4.139107291666667, 4.765134707446809, 2.6140251061969018), # 47
(1.981487244245525, 5.032679829545455, 5.108957608695652, 4.136413235294118, 4.7568446808510645, 2.5939022113943038), # 48
(1.9845968909846547, 5.0365505326704545, 5.096087545289856, 4.133589031862746, 4.748162101063831, 2.5730769740129937), # 49
(1.9876438618925836, 5.040340909090909, 5.0826992753623195, 4.130637254901962, 4.739095744680852, 2.551586706646677), # 50
(1.990630171035806, 5.044050319602273, 5.0688110054347835, 4.127560477941177, 4.729654388297873, 2.5294687218890557), # 51
(1.9935578324808187, 5.047678125000001, 5.054440942028986, 4.124361274509805, 4.719846808510639, 2.5067603323338337), # 52
(1.996428860294118, 5.051223686079546, 5.039607291666667, 4.121042218137255, 4.709681781914894, 2.483498850574713), # 53
(1.9992452685422, 5.054686363636364, 5.024328260869566, 4.117605882352942, 4.6991680851063835, 2.4597215892053974), # 54
(2.0020090712915604, 5.058065518465909, 5.00862205615942, 4.114054840686276, 4.688314494680852, 2.4354658608195905), # 55
(2.0047222826086957, 5.061360511363636, 4.992506884057971, 4.110391666666667, 4.677129787234043, 2.410768978010995), # 56
(2.007386916560103, 5.064570703125002, 4.976000951086957, 4.10661893382353, 4.6656227393617025, 2.3856682533733133), # 57
(2.0100049872122767, 5.067695454545454, 4.959122463768116, 4.102739215686276, 4.653802127659575, 2.3602009995002504), # 58
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 59
)
passenger_arriving_acc = (
(0, 5, 7, 2, 0, 0, 2, 1, 1, 1, 0, 0), # 0
(1, 10, 12, 6, 2, 0, 3, 4, 5, 7, 1, 0), # 1
(2, 13, 17, 6, 2, 0, 6, 8, 7, 8, 2, 0), # 2
(4, 14, 21, 6, 4, 0, 8, 14, 11, 10, 3, 0), # 3
(7, 19, 24, 11, 4, 0, 12, 16, 14, 12, 4, 0), # 4
(9, 23, 28, 11, 7, 0, 16, 16, 16, 12, 4, 0), # 5
(10, 31, 32, 16, 7, 0, 20, 18, 22, 15, 7, 0), # 6
(12, 38, 36, 16, 8, 0, 22, 23, 24, 16, 9, 0), # 7
(13, 42, 38, 18, 11, 0, 23, 24, 29, 18, 9, 0), # 8
(15, 43, 39, 20, 13, 0, 25, 28, 31, 21, 10, 0), # 9
(18, 46, 43, 23, 13, 0, 34, 34, 34, 22, 12, 0), # 10
(22, 47, 46, 23, 13, 0, 40, 37, 40, 22, 13, 0), # 11
(24, 50, 48, 25, 14, 0, 41, 40, 40, 25, 15, 0), # 12
(27, 54, 50, 28, 16, 0, 44, 44, 42, 26, 16, 0), # 13
(27, 57, 52, 32, 17, 0, 46, 46, 43, 28, 16, 0), # 14
(28, 62, 54, 34, 18, 0, 48, 51, 46, 30, 16, 0), # 15
(29, 64, 55, 35, 21, 0, 52, 52, 46, 30, 18, 0), # 16
(30, 66, 61, 37, 22, 0, 57, 57, 49, 30, 20, 0), # 17
(31, 68, 63, 38, 24, 0, 58, 64, 54, 30, 22, 0), # 18
(32, 73, 65, 38, 24, 0, 63, 71, 56, 30, 22, 0), # 19
(34, 79, 68, 41, 26, 0, 66, 76, 57, 32, 23, 0), # 20
(36, 81, 70, 42, 27, 0, 69, 78, 59, 36, 24, 0), # 21
(40, 84, 74, 44, 28, 0, 73, 82, 62, 37, 27, 0), # 22
(44, 87, 75, 45, 28, 0, 76, 83, 65, 37, 29, 0), # 23
(45, 92, 79, 48, 28, 0, 79, 86, 66, 39, 30, 0), # 24
(47, 97, 82, 48, 28, 0, 82, 87, 68, 42, 30, 0), # 25
(50, 106, 85, 52, 29, 0, 85, 89, 71, 45, 31, 0), # 26
(50, 110, 88, 52, 29, 0, 86, 93, 73, 47, 32, 0), # 27
(53, 114, 92, 54, 30, 0, 90, 100, 79, 48, 32, 0), # 28
(53, 117, 95, 55, 31, 0, 94, 106, 82, 51, 34, 0), # 29
(57, 119, 98, 58, 31, 0, 96, 112, 86, 55, 35, 0), # 30
(59, 124, 104, 58, 31, 0, 100, 117, 87, 56, 35, 0), # 31
(62, 128, 106, 59, 31, 0, 102, 120, 91, 57, 37, 0), # 32
(64, 135, 109, 59, 33, 0, 105, 123, 95, 58, 37, 0), # 33
(66, 137, 112, 59, 33, 0, 107, 125, 97, 60, 38, 0), # 34
(69, 139, 115, 59, 34, 0, 112, 130, 100, 62, 39, 0), # 35
(69, 147, 119, 61, 35, 0, 116, 132, 105, 64, 39, 0), # 36
(71, 149, 122, 61, 38, 0, 120, 137, 108, 67, 40, 0), # 37
(71, 158, 124, 61, 39, 0, 122, 140, 111, 69, 41, 0), # 38
(72, 162, 126, 63, 42, 0, 125, 145, 112, 71, 42, 0), # 39
(75, 165, 127, 65, 43, 0, 130, 146, 121, 73, 42, 0), # 40
(76, 171, 129, 66, 43, 0, 132, 148, 122, 75, 45, 0), # 41
(79, 174, 129, 68, 44, 0, 135, 154, 123, 78, 46, 0), # 42
(81, 176, 132, 68, 44, 0, 138, 155, 128, 80, 47, 0), # 43
(83, 179, 132, 69, 45, 0, 139, 158, 129, 83, 47, 0), # 44
(83, 184, 139, 69, 46, 0, 142, 162, 131, 84, 51, 0), # 45
(85, 186, 142, 72, 48, 0, 144, 164, 132, 86, 52, 0), # 46
(89, 191, 144, 73, 49, 0, 145, 166, 132, 86, 53, 0), # 47
(92, 194, 149, 74, 49, 0, 148, 170, 133, 88, 53, 0), # 48
(93, 201, 155, 75, 49, 0, 149, 173, 136, 93, 54, 0), # 49
(95, 201, 157, 76, 49, 0, 151, 175, 140, 95, 55, 0), # 50
(95, 207, 159, 79, 52, 0, 155, 179, 143, 97, 57, 0), # 51
(97, 213, 163, 80, 52, 0, 157, 184, 144, 98, 59, 0), # 52
(99, 215, 165, 80, 52, 0, 158, 188, 145, 98, 59, 0), # 53
(101, 218, 168, 83, 55, 0, 161, 191, 149, 101, 60, 0), # 54
(102, 219, 173, 86, 56, 0, 165, 195, 153, 101, 62, 0), # 55
(103, 221, 177, 87, 57, 0, 170, 196, 153, 106, 62, 0), # 56
(104, 224, 179, 89, 57, 0, 174, 196, 153, 108, 62, 0), # 57
(107, 228, 182, 92, 57, 0, 176, 202, 156, 110, 63, 0), # 58
(107, 228, 182, 92, 57, 0, 176, 202, 156, 110, 63, 0), # 59
)
passenger_arriving_rate = (
(1.5897909350307289, 3.2623011363636363, 2.877924967866324, 1.5207065217391305, 0.8571634615384615, 0.0, 2.8540760869565225, 3.428653846153846, 2.2810597826086956, 1.918616645244216, 0.8155752840909091, 0.0), # 0
(1.6047132060286802, 3.298579967382155, 2.8934695935089985, 1.5291754528985508, 0.8635879807692308, 0.0, 2.853103283514493, 3.4543519230769233, 2.2937631793478266, 1.928979729005999, 0.8246449918455387, 0.0), # 1
(1.6194650863330406, 3.3343206734006734, 2.908645244215938, 1.5374579710144929, 0.8698769230769231, 0.0, 2.8521007246376815, 3.4795076923076924, 2.3061869565217394, 1.939096829477292, 0.8335801683501683, 0.0), # 2
(1.6340340539947322, 3.369484687500001, 2.9234408338688946, 1.545547010869565, 0.8760245192307694, 0.0, 2.851068546195653, 3.5040980769230776, 2.3183205163043477, 1.9489605559125964, 0.8423711718750002, 0.0), # 3
(1.6484075870646768, 3.4040334427609436, 2.9378452763496146, 1.553435507246377, 0.8820250000000001, 0.0, 2.850006884057971, 3.5281000000000002, 2.3301532608695656, 1.9585635175664096, 0.8510083606902359, 0.0), # 4
(1.662573163593796, 3.437928372264311, 2.951847485539846, 1.5611163949275362, 0.8878725961538462, 0.0, 2.848915874094203, 3.5514903846153847, 2.3416745923913043, 1.9678983236932306, 0.8594820930660777, 0.0), # 5
(1.6765182616330119, 3.4711309090909093, 2.9654363753213375, 1.5685826086956525, 0.8935615384615384, 0.0, 2.8477956521739136, 3.5742461538461536, 2.352873913043479, 1.9769575835475584, 0.8677827272727273, 0.0), # 6
(1.690230359233246, 3.5036024863215487, 2.9786008595758355, 1.5758270833333334, 0.8990860576923079, 0.0, 2.8466463541666673, 3.5963442307692315, 2.363740625, 1.9857339063838901, 0.8759006215803872, 0.0), # 7
(1.7036969344454203, 3.5353045370370366, 2.991329852185091, 1.5828427536231884, 0.9044403846153848, 0.0, 2.845468115942029, 3.617761538461539, 2.3742641304347827, 1.994219901456727, 0.8838261342592592, 0.0), # 8
(1.7169054653204567, 3.566198494318182, 3.003612267030849, 1.5896225543478264, 0.90961875, 0.0, 2.8442610733695655, 3.638475, 2.3844338315217395, 2.002408178020566, 0.8915496235795455, 0.0), # 9
(1.7298434299092773, 3.5962457912457917, 3.015437017994859, 1.5961594202898552, 0.9146153846153847, 0.0, 2.8430253623188406, 3.658461538461539, 2.394239130434783, 2.0102913453299056, 0.8990614478114479, 0.0), # 10
(1.7424983062628039, 3.625407860900674, 3.0267930189588688, 1.602446286231884, 0.9194245192307693, 0.0, 2.841761118659421, 3.677698076923077, 2.403669429347826, 2.0178620126392457, 0.9063519652251685, 0.0), # 11
(1.7548575724319582, 3.653646136363636, 3.0376691838046277, 1.6084760869565218, 0.9240403846153845, 0.0, 2.8404684782608696, 3.696161538461538, 2.4127141304347828, 2.025112789203085, 0.913411534090909, 0.0), # 12
(1.7669087064676616, 3.680922050715489, 3.048054426413882, 1.614241757246377, 0.9284572115384617, 0.0, 2.839147576992754, 3.713828846153847, 2.4213626358695657, 2.032036284275921, 0.9202305126788722, 0.0), # 13
(1.7786391864208373, 3.7071970370370377, 3.05793766066838, 1.6197362318840578, 0.9326692307692308, 0.0, 2.8377985507246377, 3.7306769230769232, 2.429604347826087, 2.038625107112253, 0.9267992592592594, 0.0), # 14
(1.7900364903424055, 3.732432528409091, 3.0673078004498713, 1.624952445652174, 0.9366706730769232, 0.0, 2.8364215353260875, 3.746682692307693, 2.437428668478261, 2.044871866966581, 0.9331081321022727, 0.0), # 15
(1.8010880962832896, 3.7565899579124578, 3.0761537596401034, 1.6298833333333334, 0.9404557692307693, 0.0, 2.835016666666667, 3.7618230769230774, 2.4448250000000002, 2.050769173093402, 0.9391474894781144, 0.0), # 16
(1.8117814822944105, 3.779630758627946, 3.084464452120823, 1.634521829710145, 0.9440187500000001, 0.0, 2.833584080615943, 3.7760750000000005, 2.4517827445652176, 2.0563096347472154, 0.9449076896569865, 0.0), # 17
(1.8221041264266904, 3.8015163636363636, 3.09222879177378, 1.6388608695652176, 0.9473538461538464, 0.0, 2.8321239130434788, 3.7894153846153857, 2.4582913043478265, 2.0614858611825198, 0.9503790909090909, 0.0), # 18
(1.8320435067310508, 3.8222082060185185, 3.09943569248072, 1.6428933876811593, 0.9504552884615385, 0.0, 2.830636299818841, 3.801821153846154, 2.464340081521739, 2.0662904616538134, 0.9555520515046296, 0.0), # 19
(1.841587101258414, 3.841667718855218, 3.106074068123393, 1.6466123188405797, 0.9533173076923078, 0.0, 2.8291213768115946, 3.8132692307692313, 2.46991847826087, 2.0707160454155953, 0.9604169297138045, 0.0), # 20
(1.850722388059702, 3.8598563352272715, 3.1121328325835482, 1.650010597826087, 0.9559341346153846, 0.0, 2.827579279891305, 3.8237365384615383, 2.475015896739131, 2.0747552217223655, 0.9649640838068179, 0.0), # 21
(1.8594368451858356, 3.8767354882154885, 3.1176008997429308, 1.65308115942029, 0.9582999999999999, 0.0, 2.8260101449275368, 3.8331999999999997, 2.4796217391304354, 2.0784005998286204, 0.9691838720538721, 0.0), # 22
(1.867717950687738, 3.892266610900674, 3.122467183483291, 1.655816938405797, 0.9604091346153847, 0.0, 2.8244141077898557, 3.8416365384615387, 2.483725407608696, 2.0816447889888607, 0.9730666527251685, 0.0), # 23
(1.8755531826163303, 3.9064111363636362, 3.1267205976863752, 1.6582108695652176, 0.9622557692307692, 0.0, 2.8227913043478265, 3.8490230769230767, 2.4873163043478264, 2.0844803984575835, 0.9766027840909091, 0.0), # 24
(1.8829300190225344, 3.919130497685185, 3.1303500562339335, 1.6602558876811595, 0.9638341346153845, 0.0, 2.8211418704710147, 3.855336538461538, 2.4903838315217395, 2.086900037489289, 0.9797826244212963, 0.0), # 25
(1.8898359379572727, 3.930386127946128, 3.1333444730077127, 1.661944927536232, 0.9651384615384615, 0.0, 2.819465942028986, 3.860553846153846, 2.492917391304348, 2.088896315338475, 0.982596531986532, 0.0), # 26
(1.8962584174714663, 3.940139460227272, 3.1356927618894597, 1.6632709239130437, 0.966162980769231, 0.0, 2.817763654891305, 3.864651923076924, 2.4949063858695655, 2.0904618412596396, 0.985034865056818, 0.0), # 27
(1.9021849356160379, 3.948351927609427, 3.1373838367609257, 1.664226811594203, 0.9669019230769231, 0.0, 2.8160351449275365, 3.8676076923076925, 2.4963402173913045, 2.091589224507284, 0.9870879819023568, 0.0), # 28
(1.9076029704419084, 3.954984963173401, 3.138406611503856, 1.664805525362319, 0.9673495192307693, 0.0, 2.814280548007247, 3.869398076923077, 2.4972082880434785, 2.092271074335904, 0.9887462407933503, 0.0), # 29
(1.9125000000000003, 3.9600000000000004, 3.1387500000000004, 1.665, 0.9675, 0.0, 2.8125000000000004, 3.87, 2.4975, 2.0925000000000002, 0.9900000000000001, 0.0), # 30
(1.9170822170716115, 3.9641658238636355, 3.138492581521739, 1.6649648774509804, 0.9674452393617023, 0.0, 2.8100257558720645, 3.8697809574468094, 2.497447316176471, 2.0923283876811594, 0.9910414559659089, 0.0), # 31
(1.92156550511509, 3.9682765909090914, 3.137727608695652, 1.6648601960784315, 0.9672821276595746, 0.0, 2.8062148550724646, 3.869128510638298, 2.497290294117647, 2.091818405797101, 0.9920691477272728, 0.0), # 32
(1.925951878196931, 3.9723317897727273, 3.1364660054347833, 1.6646869852941177, 0.9670124202127659, 0.0, 2.8011046101949026, 3.8680496808510636, 2.497030477941177, 2.090977336956522, 0.9930829474431818, 0.0), # 33
(1.9302433503836318, 3.976330909090909, 3.134718695652174, 1.664446274509804, 0.9666378723404256, 0.0, 2.794732333833084, 3.8665514893617026, 2.496669411764706, 2.0898124637681157, 0.9940827272727273, 0.0), # 34
(1.9344419357416882, 3.9802734374999997, 3.13249660326087, 1.664139093137255, 0.9661602393617023, 0.0, 2.78713533858071, 3.864640957446809, 2.4962086397058827, 2.0883310688405796, 0.9950683593749999, 0.0), # 35
(1.9385496483375964, 3.984158863636364, 3.1298106521739135, 1.6637664705882356, 0.9655812765957449, 0.0, 2.7783509370314845, 3.8623251063829795, 2.4956497058823537, 2.086540434782609, 0.996039715909091, 0.0), # 36
(1.9425685022378518, 3.987986676136364, 3.126671766304348, 1.66332943627451, 0.9649027393617021, 0.0, 2.768416441779111, 3.8596109574468085, 2.494994154411765, 2.0844478442028986, 0.996996669034091, 0.0), # 37
(1.9465005115089515, 3.9917563636363633, 3.1230908695652175, 1.662829019607843, 0.9641263829787234, 0.0, 2.757369165417291, 3.8565055319148938, 2.4942435294117646, 2.082060579710145, 0.9979390909090908, 0.0), # 38
(1.9503476902173915, 3.995467414772727, 3.119078885869565, 1.6622662500000003, 0.9632539627659574, 0.0, 2.7452464205397304, 3.8530158510638297, 2.4933993750000005, 2.079385923913043, 0.9988668536931817, 0.0), # 39
(1.9541120524296678, 3.9991193181818185, 3.114646739130435, 1.661642156862745, 0.9622872340425531, 0.0, 2.73208551974013, 3.8491489361702125, 2.492463235294118, 2.0764311594202898, 0.9997798295454546, 0.0), # 40
(1.9577956122122764, 4.0027115625, 3.10980535326087, 1.660957769607843, 0.9612279521276595, 0.0, 2.717923775612195, 3.844911808510638, 2.4914366544117645, 2.07320356884058, 1.000677890625, 0.0), # 41
(1.9614003836317138, 4.006243636363638, 3.1045656521739136, 1.6602141176470588, 0.9600778723404256, 0.0, 2.702798500749626, 3.8403114893617025, 2.490321176470588, 2.0697104347826087, 1.0015609090909094, 0.0), # 42
(1.9649283807544762, 4.00971502840909, 3.0989385597826087, 1.6594122303921572, 0.9588387500000001, 0.0, 2.6867470077461273, 3.8353550000000003, 2.4891183455882357, 2.0659590398550725, 1.0024287571022725, 0.0), # 43
(1.968381617647059, 4.013125227272727, 3.0929350000000007, 1.6585531372549018, 0.9575123404255319, 0.0, 2.6698066091954025, 3.8300493617021276, 2.487829705882353, 2.061956666666667, 1.0032813068181818, 0.0), # 44
(1.971762108375959, 4.016473721590909, 3.086565896739131, 1.657637867647059, 0.9561003989361703, 0.0, 2.652014617691155, 3.824401595744681, 2.4864568014705886, 2.0577105978260875, 1.0041184303977273, 0.0), # 45
(1.9750718670076732, 4.019760000000001, 3.0798421739130446, 1.6566674509803923, 0.954604680851064, 0.0, 2.633408345827087, 3.818418723404256, 2.4850011764705884, 2.0532281159420296, 1.0049400000000002, 0.0), # 46
(1.978312907608696, 4.022983551136364, 3.0727747554347826, 1.6556429166666666, 0.9530269414893617, 0.0, 2.6140251061969018, 3.812107765957447, 2.483464375, 2.0485165036231883, 1.005745887784091, 0.0), # 47
(1.981487244245525, 4.026143863636364, 3.0653745652173914, 1.654565294117647, 0.9513689361702128, 0.0, 2.5939022113943038, 3.805475744680851, 2.4818479411764707, 2.043583043478261, 1.006535965909091, 0.0), # 48
(1.9845968909846547, 4.029240426136363, 3.0576525271739134, 1.6534356127450982, 0.9496324202127661, 0.0, 2.5730769740129937, 3.7985296808510642, 2.4801534191176473, 2.0384350181159423, 1.0073101065340908, 0.0), # 49
(1.9876438618925836, 4.032272727272726, 3.0496195652173914, 1.6522549019607846, 0.9478191489361703, 0.0, 2.551586706646677, 3.791276595744681, 2.478382352941177, 2.0330797101449276, 1.0080681818181816, 0.0), # 50
(1.990630171035806, 4.035240255681818, 3.04128660326087, 1.6510241911764707, 0.9459308776595745, 0.0, 2.5294687218890557, 3.783723510638298, 2.476536286764706, 2.0275244021739134, 1.0088100639204545, 0.0), # 51
(1.9935578324808187, 4.0381425, 3.0326645652173916, 1.6497445098039216, 0.9439693617021278, 0.0, 2.5067603323338337, 3.775877446808511, 2.4746167647058828, 2.0217763768115944, 1.009535625, 0.0), # 52
(1.996428860294118, 4.0409789488636365, 3.0237643750000003, 1.6484168872549019, 0.9419363563829788, 0.0, 2.483498850574713, 3.767745425531915, 2.472625330882353, 2.0158429166666667, 1.0102447372159091, 0.0), # 53
(1.9992452685422, 4.043749090909091, 3.014596956521739, 1.6470423529411766, 0.9398336170212767, 0.0, 2.4597215892053974, 3.7593344680851066, 2.470563529411765, 2.009731304347826, 1.0109372727272727, 0.0), # 54
(2.0020090712915604, 4.046452414772727, 3.005173233695652, 1.6456219362745101, 0.9376628989361703, 0.0, 2.4354658608195905, 3.750651595744681, 2.4684329044117654, 2.003448822463768, 1.0116131036931817, 0.0), # 55
(2.0047222826086957, 4.049088409090909, 2.995504130434783, 1.6441566666666665, 0.9354259574468086, 0.0, 2.410768978010995, 3.7417038297872343, 2.4662349999999997, 1.9970027536231885, 1.0122721022727272, 0.0), # 56
(2.007386916560103, 4.051656562500001, 2.9856005706521738, 1.6426475735294117, 0.9331245478723404, 0.0, 2.3856682533733133, 3.732498191489362, 2.4639713602941176, 1.9904003804347825, 1.0129141406250002, 0.0), # 57
(2.0100049872122767, 4.054156363636363, 2.9754734782608696, 1.64109568627451, 0.930760425531915, 0.0, 2.3602009995002504, 3.72304170212766, 2.461643529411765, 1.9836489855072463, 1.0135390909090907, 0.0), # 58
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 59
)
passenger_allighting_rate = (
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 0
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 1
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 2
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 3
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 4
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 5
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 6
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 7
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 8
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 9
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 10
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 11
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 12
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 13
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 14
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 15
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 16
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 17
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 18
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 19
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 20
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 21
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 22
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 23
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 24
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 25
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 26
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 27
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 28
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 29
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 30
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 31
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 32
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 33
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 34
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 35
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 36
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 37
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 38
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 39
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 40
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 41
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 42
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 43
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 44
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 45
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 46
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 47
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 48
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 49
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 50
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 51
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 52
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 53
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 54
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 55
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 56
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 57
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 58
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 59
)
"""
parameters for reproducibiliy. More information: https://numpy.org/doc/stable/reference/random/parallel.html
"""
#initial entropy
entropy = 258194110137029475889902652135037600173
#index for seed sequence child
child_seed_index = (
1, # 0
38, # 1
)
|
var test = require('../util/test')(__filename);
var replaceAll = require('../../packages/string-replace-all');
test('string with replacements', function(t) {
t.plan(4);
t.equal(replaceAll('hello, world', 'l', 'q'), 'heqqo, worqd');
t.equal(replaceAll('hello, world', 'l', 'qq'), 'heqqqqo, worqqd');
t.equal(replaceAll('hello, world', 'll', 'q'), 'heqo, world');
t.equal(replaceAll('hello, world', 'l', ''), 'heo, word');
t.end();
});
test('string with no replacements', function(t) {
t.plan(1);
t.equal(replaceAll('hello, world', '', 'q'), 'hello, world');
t.end();
});
test('invalid arguments', function(t) {
t.plan(6);
t.throws(function() {
replaceAll('hello, world', 'l');
});
t.throws(function() {
replaceAll('hello, world');
});
t.throws(function() {
replaceAll();
});
t.throws(function() {
replaceAll(null, 'l', 'q');
});
t.throws(function() {
replaceAll('hello, world', null, 'q');
});
t.throws(function() {
replaceAll('hello, world', 'l', null);
});
t.end();
});
|
module.exports = new Date(1993, 0, 3)
|
/*! jQuery v1.8.3 jquery.com | jquery.org/license */
(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
function utf16to8(str) {
var out, i, len, c;
out = "";
len = str.length;
for(i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
function utf8to16(str) {
var out, i, len, c;
var char2, char3;
out = "";
len = str.length;
i = 0;
while(i < len) {
c = str.charCodeAt(i++);
switch(c >> 4)
{
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
out += str.charAt(i-1);
break;
case 12: case 13:
// 110x xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}
function QR8bitByte(a){
this.mode=QRMode.MODE_8BIT_BYTE,
this.data=a
}
function QRCode(a,b){
this.typeNumber=a,
this.errorCorrectLevel=b,
this.modules=null,
this.moduleCount=0,
this.dataCache=null,
this.dataList=new Array()
}
function QRPolynomial(a,b){
var c,d;
if(void 0==a.length){
throw new Error(a.length+"/"+b)
}
for(c=0;c<a.length&&0==a[c];){
c++
}
for(this.num=new Array(a.length-c+b),d=0;d<a.length-c;d++){
this.num[d]=a[d+c]
}
}
function QRRSBlock(a,b){
this.totalCount=a,
this.dataCount=b
}
function QRBitBuffer(){
this.buffer=new Array(),
this.length=0
}
var QRMode,QRErrorCorrectLevel,QRMaskPattern,QRUtil,QRMath,i;
for(function(a){
a.fn.qrcode=function(b){
var c,d;
return"string"==typeof b&&(b={text:b}),
b=a.extend({},{
render:"canvas",
width:256,
height:256,
//这里是图片的高度和宽度
imgWidth:b.width/4.7,
imgHeight:b.height/4,
typeNumber:-1,
correctLevel:QRErrorCorrectLevel.H,
background:"#ffffff",
foreground:"#000000"
},b),c=function(){
var c,d,e,f,g,h,i,j,k,a=new QRCode(b.typeNumber,b.correctLevel);
for(a.addData(utf16to8(b.text)),a.make(),
c=document.createElement("canvas"),
c.width=b.width,c.height=b.height,d=c.getContext("2d"),
b.src&&(e=new Image(),e.src=b.src,e.onload=function(){
d.drawImage(e,(b.width-b.imgWidth)/2,(b.height-b.imgHeight)/2,
b.imgWidth,b.imgHeight)}),f=b.width/a.getModuleCount(),
g=b.height/a.getModuleCount(),h=0;h<a.getModuleCount();h++)
{for(i=0;i<a.getModuleCount();i++){
d.fillStyle=a.isDark(h,i)?b.foreground:b.background,
j=Math.ceil((i+1)*f)-Math.floor(i*f),
k=Math.ceil((h+1)*f)-Math.floor(h*f),
d.fillRect(Math.round(i*f),Math.round(h*g),j,k)
}}return c},
d=function(){var d,e,f,g,h,i,
c=new QRCode(b.typeNumber,b.correctLevel);
//这里的utf16to8(b.text)是对Text中的字符串进行转码,让其支持中文
for(c.addData(utf16to8(b.text)),c.make(),d=a("<table></table>").css("width",b.width+"px").css("height",b.height+"px").css("border","0px").css("border-collapse","collapse").css("background-color",b.background),e=b.width/c.getModuleCount(),f=b.height/c.getModuleCount(),g=0;g<c.getModuleCount();g++){for(h=a("<tr></tr>").css("height",f+"px").appendTo(d),i=0;i<c.getModuleCount();i++){a("<td></td>").css("width",e+"px").css("background-color",c.isDark(g,i)?b.foreground:b.background).appendTo(h)}}return d},this.each(function(){var e="canvas"==b.render?c():d();a(e).appendTo(this)})}}(jQuery),QR8bitByte.prototype={getLength:function(){return this.data.length},write:function(a){for(var b=0;b<this.data.length;b++){a.put(this.data.charCodeAt(b),8)}}},QRCode.prototype={addData:function(a){var b=new QR8bitByte(a);this.dataList.push(b),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b){throw new Error(a+","+b)}return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){var a,b,c,d,e,f;if(this.typeNumber<1){for(a=1,a=1;40>a;a++){for(b=QRRSBlock.getRSBlocks(a,this.errorCorrectLevel),c=new QRBitBuffer(),d=0,e=0;e<b.length;e++){d+=b[e].dataCount}for(e=0;e<this.dataList.length;e++){f=this.dataList[e],c.put(f.mode,4),c.put(f.getLength(),QRUtil.getLengthInBits(f.mode,a)),f.write(c)}if(c.getLengthInBits()<=8*d){break}}this.typeNumber=a}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,b){var c,d;for(this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount),c=0;c<this.moduleCount;c++){for(this.modules[c]=new Array(this.moduleCount),d=0;d<this.moduleCount;d++){this.modules[c][d]=null}}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(a,b),this.typeNumber>=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=QRCode.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,b)},setupPositionProbePattern:function(a,b){var c,d;for(c=-1;7>=c;c++){if(!(-1>=a+c||this.moduleCount<=a+c)){for(d=-1;7>=d;d++){-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)}}}},getBestMaskPattern:function(){var c,d,a=0,b=0;for(c=0;8>c;c++){this.makeImpl(!0,c),d=QRUtil.getLostPoint(this),(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var f,g,h,i,j,d=a.createEmptyMovieClip(b,c),e=1;for(this.make(),f=0;f<this.modules.length;f++){for(g=f*e,h=0;h<this.modules[f].length;h++){i=h*e,j=this.modules[f][h],j&&(d.beginFill(0,100),d.moveTo(i,g),d.lineTo(i+e,g),d.lineTo(i+e,g+e),d.lineTo(i,g+e),d.endFill())}}return d},setupTimingPattern:function(){var a,b;for(a=8;a<this.moduleCount-8;a++){null==this.modules[a][6]&&(this.modules[a][6]=0==a%2)}for(b=8;b<this.moduleCount-8;b++){null==this.modules[6][b]&&(this.modules[6][b]=0==b%2)}},setupPositionAdjustPattern:function(){var b,c,d,e,f,g,a=QRUtil.getPatternPosition(this.typeNumber);for(b=0;b<a.length;b++){for(c=0;c<a.length;c++){if(d=a[b],e=a[c],null==this.modules[d][e]){for(f=-2;2>=f;f++){for(g=-2;2>=g;g++){this.modules[d+f][e+g]=-2==f||2==f||-2==g||2==g||0==f&&0==g?!0:!1}}}}}},setupTypeNumber:function(a){var c,d,b=QRUtil.getBCHTypeNumber(this.typeNumber);for(c=0;18>c;c++){d=!a&&1==(1&b>>c),this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(c=0;18>c;c++){d=!a&&1==(1&b>>c),this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){var e,f,c=this.errorCorrectLevel<<3|b,d=QRUtil.getBCHTypeInfo(c);for(e=0;15>e;e++){f=!a&&1==(1&d>>e),6>e?this.modules[e][8]=f:8>e?this.modules[e+1][8]=f:this.modules[this.moduleCount-15+e][8]=f}for(e=0;15>e;e++){f=!a&&1==(1&d>>e),8>e?this.modules[8][this.moduleCount-e-1]=f:9>e?this.modules[8][15-e-1+1]=f:this.modules[8][15-e-1]=f}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){var g,h,i,j,c=-1,d=this.moduleCount-1,e=7,f=0;for(g=this.moduleCount-1;g>0;g-=2){for(6==g&&g--;;){for(h=0;2>h;h++){null==this.modules[d][g-h]&&(i=!1,f<a.length&&(i=1==(1&a[f]>>>e)),j=QRUtil.getMask(b,d,g-h),j&&(i=!i),this.modules[d][g-h]=i,e--,-1==e&&(f++,e=7))}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}}},QRCode.PAD0=236,QRCode.PAD1=17,QRCode.createData=function(a,b,c){var f,g,h,d=QRRSBlock.getRSBlocks(a,b),e=new QRBitBuffer();for(f=0;f<c.length;f++){g=c[f],e.put(g.mode,4),e.put(g.getLength(),QRUtil.getLengthInBits(g.mode,a)),g.write(e)}for(h=0,f=0;f<d.length;f++){h+=d[f].dataCount}if(e.getLengthInBits()>8*h){throw new Error("code length overflow. ("+e.getLengthInBits()+">"+8*h+")")}for(e.getLengthInBits()+4<=8*h&&e.put(0,4);0!=e.getLengthInBits()%8;){e.putBit(!1)}for(;;){if(e.getLengthInBits()>=8*h){break}if(e.put(QRCode.PAD0,8),e.getLengthInBits()>=8*h){break}e.put(QRCode.PAD1,8)}return QRCode.createBytes(e,d)},QRCode.createBytes=function(a,b){var h,i,j,k,l,m,n,o,p,q,r,c=0,d=0,e=0,f=new Array(b.length),g=new Array(b.length);for(h=0;h<b.length;h++){for(i=b[h].dataCount,j=b[h].totalCount-i,d=Math.max(d,i),e=Math.max(e,j),f[h]=new Array(i),k=0;k<f[h].length;k++){f[h][k]=255&a.buffer[k+c]}for(c+=i,l=QRUtil.getErrorCorrectPolynomial(j),m=new QRPolynomial(f[h],l.getLength()-1),n=m.mod(l),g[h]=new Array(l.getLength()-1),k=0;k<g[h].length;k++){o=k+n.getLength()-g[h].length,g[h][k]=o>=0?n.get(o):0}}for(p=0,k=0;k<b.length;k++){p+=b[k].totalCount}for(q=new Array(p),r=0,k=0;d>k;k++){for(h=0;h<b.length;h++){k<f[h].length&&(q[r++]=f[h][k])}}for(k=0;e>k;k++){for(h=0;h<b.length;h++){k<g[h].length&&(q[r++]=g[h][k])}}return q},QRMode={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},QRErrorCorrectLevel={L:1,M:0,Q:3,H:2},QRMaskPattern={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},QRUtil={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(a){for(var b=a<<10;QRUtil.getBCHDigit(b)-QRUtil.getBCHDigit(QRUtil.G15)>=0;){b^=QRUtil.G15<<QRUtil.getBCHDigit(b)-QRUtil.getBCHDigit(QRUtil.G15)}return(a<<10|b)^QRUtil.G15_MASK},getBCHTypeNumber:function(a){for(var b=a<<12;QRUtil.getBCHDigit(b)-QRUtil.getBCHDigit(QRUtil.G18)>=0;){b^=QRUtil.G18<<QRUtil.getBCHDigit(b)-QRUtil.getBCHDigit(QRUtil.G18)}return a<<12|b},getBCHDigit:function(a){for(var b=0;0!=a;){b++,a>>>=1}return b},getPatternPosition:function(a){return QRUtil.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,b,c){switch(a){case QRMaskPattern.PATTERN000:return 0==(b+c)%2;case QRMaskPattern.PATTERN001:return 0==b%2;case QRMaskPattern.PATTERN010:return 0==c%3;case QRMaskPattern.PATTERN011:return 0==(b+c)%3;case QRMaskPattern.PATTERN100:return 0==(Math.floor(b/2)+Math.floor(c/3))%2;case QRMaskPattern.PATTERN101:return 0==b*c%2+b*c%3;case QRMaskPattern.PATTERN110:return 0==(b*c%2+b*c%3)%2;case QRMaskPattern.PATTERN111:return 0==(b*c%3+(b+c)%2)%2;default:throw new Error("bad maskPattern:"+a)}},getErrorCorrectPolynomial:function(a){var c,b=new QRPolynomial([1],0);for(c=0;a>c;c++){b=b.multiply(new QRPolynomial([1,QRMath.gexp(c)],0))}return b},getLengthInBits:function(a,b){if(b>=1&&10>b){switch(a){case QRMode.MODE_NUMBER:return 10;case QRMode.MODE_ALPHA_NUM:return 9;case QRMode.MODE_8BIT_BYTE:return 8;case QRMode.MODE_KANJI:return 8;default:throw new Error("mode:"+a)}}else{if(27>b){switch(a){case QRMode.MODE_NUMBER:return 12;case QRMode.MODE_ALPHA_NUM:return 11;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 10;default:throw new Error("mode:"+a)}}else{if(!(41>b)){throw new Error("type:"+b)}switch(a){case QRMode.MODE_NUMBER:return 14;case QRMode.MODE_ALPHA_NUM:return 13;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 12;default:throw new Error("mode:"+a)}}}},getLostPoint:function(a){var d,e,f,g,h,i,j,k,l,b=a.getModuleCount(),c=0;for(d=0;b>d;d++){for(e=0;b>e;e++){for(f=0,g=a.isDark(d,e),h=-1;1>=h;h++){if(!(0>d+h||d+h>=b)){for(i=-1;1>=i;i++){0>e+i||e+i>=b||(0!=h||0!=i)&&g==a.isDark(d+h,e+i)&&f++}}}f>5&&(c+=3+f-5)}}for(d=0;b-1>d;d++){for(e=0;b-1>e;e++){j=0,a.isDark(d,e)&&j++,a.isDark(d+1,e)&&j++,a.isDark(d,e+1)&&j++,a.isDark(d+1,e+1)&&j++,(0==j||4==j)&&(c+=3)}}for(d=0;b>d;d++){for(e=0;b-6>e;e++){a.isDark(d,e)&&!a.isDark(d,e+1)&&a.isDark(d,e+2)&&a.isDark(d,e+3)&&a.isDark(d,e+4)&&!a.isDark(d,e+5)&&a.isDark(d,e+6)&&(c+=40)}}for(e=0;b>e;e++){for(d=0;b-6>d;d++){a.isDark(d,e)&&!a.isDark(d+1,e)&&a.isDark(d+2,e)&&a.isDark(d+3,e)&&a.isDark(d+4,e)&&!a.isDark(d+5,e)&&a.isDark(d+6,e)&&(c+=40)}}for(k=0,e=0;b>e;e++){for(d=0;b>d;d++){a.isDark(d,e)&&k++}}return l=Math.abs(100*k/b/b-50)/5,c+=10*l}},QRMath={glog:function(a){if(1>a){throw new Error("glog("+a+")")}return QRMath.LOG_TABLE[a]},gexp:function(a){for(;0>a;){a+=255}for(;a>=256;){a-=255}return QRMath.EXP_TABLE[a]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},i=0;8>i;i++){QRMath.EXP_TABLE[i]=1<<i}for(i=8;256>i;i++){QRMath.EXP_TABLE[i]=QRMath.EXP_TABLE[i-4]^QRMath.EXP_TABLE[i-5]^QRMath.EXP_TABLE[i-6]^QRMath.EXP_TABLE[i-8]}for(i=0;255>i;i++){QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]]=i}QRPolynomial.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){var c,d,b=new Array(this.getLength()+a.getLength()-1);for(c=0;c<this.getLength();c++){for(d=0;d<a.getLength();d++){b[c+d]^=QRMath.gexp(QRMath.glog(this.get(c))+QRMath.glog(a.get(d)))}}return new QRPolynomial(b,0)},mod:function(a){var b,c,d;if(this.getLength()-a.getLength()<0){return this}for(b=QRMath.glog(this.get(0))-QRMath.glog(a.get(0)),c=new Array(this.getLength()),d=0;d<this.getLength();d++){c[d]=this.get(d)}for(d=0;d<a.getLength();d++){c[d]^=QRMath.gexp(QRMath.glog(a.get(d))+b)}return new QRPolynomial(c,0).mod(a)}},QRRSBlock.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],QRRSBlock.getRSBlocks=function(a,b){var d,e,f,g,h,i,j,c=QRRSBlock.getRsBlockTable(a,b);if(void 0==c){throw new Error("bad rs block @ typeNumber:"+a+"/errorCorrectLevel:"+b)}for(d=c.length/3,e=new Array(),f=0;d>f;f++){for(g=c[3*f+0],h=c[3*f+1],i=c[3*f+2],j=0;g>j;j++){e.push(new QRRSBlock(h,i))}}return e},QRRSBlock.getRsBlockTable=function(a,b){switch(b){case QRErrorCorrectLevel.L:return QRRSBlock.RS_BLOCK_TABLE[4*(a-1)+0];case QRErrorCorrectLevel.M:return QRRSBlock.RS_BLOCK_TABLE[4*(a-1)+1];case QRErrorCorrectLevel.Q:return QRRSBlock.RS_BLOCK_TABLE[4*(a-1)+2];case QRErrorCorrectLevel.H:return QRRSBlock.RS_BLOCK_TABLE[4*(a-1)+3];default:return void 0}},QRBitBuffer.prototype={get:function(a){var b=Math.floor(a/8);return 1==(1&this.buffer[b]>>>7-a%8)},put:function(a,b){for(var c=0;b>c;c++){this.putBit(1==(1&a>>>b-c-1))}},getLengthInBits:function(){return this.length},putBit:function(a){var b=Math.floor(this.length/8);this.buffer.length<=b&&this.buffer.push(0),a&&(this.buffer[b]|=128>>>this.length%8),this.length++}};
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: convert_kvret_data.py
"""
import json
import ast
import numpy as np
def convert_text_for_model(input_file, out_file):
all_samples = []
sample = {}
uid = []
dialog = []
kb = []
gold_entity = []
ptr_index = []
kb_index = []
dialog_id = 0
with open(input_file, 'r') as fr:
for line in fr:
line = line.strip()
if line:
if line.startswith('#'):
task = line.replace('#', '')
sample['task'] = task
elif line.startswith('0'):
triples = line.split()[1:]
if len(triples) <= 4:
if len(triples) == 2:
kb_triple = triples[0] + " <pad> " + triples[1]
elif len(triples) == 4:
kb_triple = triples[0] + " " + triples[1] + "_" + triples[2] + " " + triples[3]
else:
if "poi_type" in triples:
kb_triple = triples[2] + " poi " + triples[0]
else:
kb_triple = " ".join(triples)
kb.append(kb_triple)
else:
u, s, gold_ent = line.split('\t')
u = " ".join(u.split()[1:])
uid.append('1')
dialog.append(u)
uid.append('0')
dialog.append(s)
gold_ent = ast.literal_eval(gold_ent)
gold_entity.append(gold_ent)
ptr = [1 if (w in gold_ent and len(kb) > 0) else 0 for w in s.split()]
ptr_index.append(ptr)
if len(kb) == 0:
kb_ptr = [0]
else:
kb_ptr = []
for triple in kb:
tup = triple.split()
assert len(tup) == 3
obj = tup[2]
if obj in s.split():
kb_ptr.append(1)
else:
kb_ptr.append(0)
kb_index.append(kb_ptr)
else:
sample['dialog_id'] = dialog_id
sample['uid'] = uid
sample['dialog'] = dialog
sample['gold_entity'] = gold_entity
sample['ptr_index'] = ptr_index
sample['kb_index'] = kb_index
if len(kb) == 0:
sample['kb'] = ["<pad> <pad> <pad>"]
else:
sample['kb'] = kb
all_samples.append(sample)
sample = {}
dialog_id += 1
uid = []
dialog = []
kb = []
gold_entity = []
ptr_index = []
kb_index = []
print("total samples:", len(all_samples))
for i, s in enumerate(all_samples):
if len(s['uid']) == 0:
print("index=%d utterance is None! filtered." % i)
del all_samples[i]
print("max utterances:", max([len(s['uid']) for s in all_samples])) # 12
print("min utterances:", min([len(s['uid']) for s in all_samples])) # 2
print("avg utterances:", np.mean([len(s['uid']) for s in all_samples]))
print("max kb triples:", max([len(s['kb']) for s in all_samples])) # 148
print("min kb triples:", min([len(s['kb']) for s in all_samples])) # 0
print("avg kb triples:", np.mean([len(s['kb']) for s in all_samples])) # 62.3
with open(out_file, 'w') as fw:
for sample in all_samples:
line = json.dumps(sample)
fw.write(line)
fw.write('\n')
if __name__ == '__main__':
data_dir = "./data/KVR"
modes = ['train', 'dev', 'test']
for mode in modes:
input_file = "%s/%s.txt" % (data_dir, mode)
out_file = "%s/%s.data.txt" % (data_dir, mode)
convert_text_for_model(input_file, out_file)
|
const parseDecimal = number => parseInt(number, 10)
module.exports = parseDecimal
|
# Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
import os
import re
import time
import math
import subprocess
import operator
import numpy as np
import scipy
from google.protobuf import text_format
import caffe
import caffe_pb2
from train import TrainTask
from digits.config import config_value
from digits.status import Status
from digits import utils, dataset
from digits.utils import subclass, override, constants
# NOTE: Increment this everytime the pickled object changes
PICKLE_VERSION = 3
# Constants
CAFFE_SOLVER_FILE = 'solver.prototxt'
CAFFE_TRAIN_VAL_FILE = 'train_val.prototxt'
CAFFE_SNAPSHOT_PREFIX = 'snapshot'
CAFFE_DEPLOY_FILE = 'deploy.prototxt'
@subclass
class CaffeTrainTask(TrainTask):
"""
Trains a caffe model
"""
CAFFE_LOG = 'caffe_output.log'
@staticmethod
def upgrade_network(network):
#TODO
pass
def __init__(self, **kwargs):
"""
Arguments:
network -- a caffe NetParameter defining the network
"""
super(CaffeTrainTask, self).__init__(**kwargs)
self.pickver_task_caffe_train = PICKLE_VERSION
self.current_iteration = 0
self.loaded_snapshot_file = None
self.loaded_snapshot_epoch = None
self.image_mean = None
self.solver = None
self.solver_file = CAFFE_SOLVER_FILE
self.train_val_file = CAFFE_TRAIN_VAL_FILE
self.snapshot_prefix = CAFFE_SNAPSHOT_PREFIX
self.deploy_file = CAFFE_DEPLOY_FILE
self.log_file = self.CAFFE_LOG
def __getstate__(self):
state = super(CaffeTrainTask, self).__getstate__()
# Don't pickle these things
if 'caffe_log' in state:
del state['caffe_log']
if '_transformer' in state:
del state['_transformer']
if '_caffe_net' in state:
del state['_caffe_net']
return state
def __setstate__(self, state):
super(CaffeTrainTask, self).__setstate__(state)
# Upgrade pickle file
if state['pickver_task_caffe_train'] <= 1:
print 'Upgrading CaffeTrainTask to version 2 ...'
self.caffe_log_file = self.CAFFE_LOG
if state['pickver_task_caffe_train'] <= 2:
print 'Upgrading CaffeTrainTask to version 3 ...'
self.log_file = self.caffe_log_file
self.framework_id = 'caffe'
self.pickver_task_caffe_train = PICKLE_VERSION
# Make changes to self
self.loaded_snapshot_file = None
self.loaded_snapshot_epoch = None
# These things don't get pickled
self.image_mean = None
### Task overrides
@override
def name(self):
return 'Train Caffe Model'
@override
def before_run(self):
super(CaffeTrainTask, self).before_run()
if isinstance(self.dataset, dataset.ImageClassificationDatasetJob):
self.save_files_classification()
elif isinstance(self.dataset, dataset.GenericImageDatasetJob):
self.save_files_generic()
else:
raise NotImplementedError
self.caffe_log = open(self.path(self.CAFFE_LOG), 'a')
self.saving_snapshot = False
self.receiving_train_output = False
self.receiving_val_output = False
self.last_train_update = None
return True
def get_mean_image(self, mean_file, resize = False):
mean_image = None
with open(self.dataset.path(mean_file), 'rb') as f:
blob = caffe_pb2.BlobProto()
blob.MergeFromString(f.read())
if isinstance(self.dataset, dataset.ImageClassificationDatasetJob):
mean_image = np.reshape(blob.data,
(
self.dataset.image_dims[2],
self.dataset.image_dims[0],
self.dataset.image_dims[1],
)
)
elif isinstance(self.dataset, dataset.GenericImageDatasetJob):
task = self.dataset.analyze_db_tasks()[0]
mean_image = np.reshape(blob.data,
(
task.image_channels,
task.image_height,
task.image_width,
)
)
# Resize the mean image if crop_size exists
if mean_image is not None and resize:
# Get the image size needed
network = caffe_pb2.NetParameter()
with open(self.path(self.deploy_file)) as infile:
text_format.Merge(infile.read(), network)
if network.input_shape:
data_shape = network.input_shape[0].dim
else:
data_shape = network.input_dim[:4]
assert len(data_shape) == 4, 'Bad data shape.'
# Get the image
mean_image = mean_image.astype('uint8')
mean_image = mean_image.transpose(1,2,0)
shape = list(mean_image.shape)
# imresize will not resize if the depth is anything
# other than 3 or 4. If it's 1, imresize expects an
# array.
if (len(shape) == 2 or (len(shape) == 3 and (shape[2] == 3 or shape[2] == 4))):
mean_image = scipy.misc.imresize(mean_image, (data_shape[2], data_shape[3]))
else:
mean_image = scipy.misc.imresize(mean_image[:,:,0],
(data_shape[2], data_shape[3]))
mean_image = np.expand_dims(mean_image, axis=2)
mean_image = mean_image.transpose(2,0,1)
mean_image = mean_image.astype('float')
return mean_image
def get_mean_pixel(self, mean_file):
mean_image = self.get_mean_image(mean_file)
mean_pixel = None
if mean_image is not None:
mean_pixel = mean_image.mean(1).mean(1)
return mean_pixel
def set_mean_value(self, layer, mean_pixel):
# remove any values that may already be in the network
if layer.transform_param.HasField('mean_file'):
layer.transform_param.ClearField('mean_file')
self.logger.warning('Ignoring mean_file from network ...')
if len(layer.transform_param.mean_value) > 0:
layer.transform_param.ClearField('mean_value')
self.logger.warning('Ignoring mean_value from network ...')
layer.transform_param.mean_value.extend(list(mean_pixel))
def set_mean_file(self, layer, mean_file):
# remove any values that may already be in the network
if layer.transform_param.HasField('mean_file'):
layer.transform_param.ClearField('mean_file')
self.logger.warning('Ignoring mean_file from network ...')
if len(layer.transform_param.mean_value) > 0:
layer.transform_param.ClearField('mean_value')
self.logger.warning('Ignoring mean_value from network ...')
layer.transform_param.mean_file = mean_file
# TODO merge these monolithic save_files functions
# TODO break them up into separate functions
def save_files_classification(self):
"""
Save solver, train_val and deploy files to disk
"""
has_val_set = self.dataset.val_db_task() is not None
### Check what has been specified in self.network
tops = []
bottoms = {}
train_data_layer = None
val_data_layer = None
hidden_layers = caffe_pb2.NetParameter()
loss_layers = []
accuracy_layers = []
for layer in self.network.layer:
assert layer.type not in ['DummyData', 'ImageData', 'MemoryData', 'WindowData'], 'unsupported data layer type'
if layer.type in ['Data', 'HDF5Data']:
for rule in layer.include:
if rule.phase == caffe_pb2.TRAIN:
assert train_data_layer is None, 'cannot specify two train data layers'
train_data_layer = layer
elif rule.phase == caffe_pb2.TEST:
assert val_data_layer is None, 'cannot specify two test data layers'
val_data_layer = layer
elif layer.type == 'SoftmaxWithLoss':
loss_layers.append(layer)
elif layer.type == 'Accuracy':
addThis = True
if layer.accuracy_param.HasField('top_k'):
if layer.accuracy_param.top_k >= len(self.get_labels()):
self.logger.warning('Removing layer %s because top_k=%s while there are are only %s labels in this dataset' % (layer.name, layer.accuracy_param.top_k, len(self.get_labels())))
addThis = False
if addThis:
accuracy_layers.append(layer)
else:
hidden_layers.layer.add().CopyFrom(layer)
if len(layer.bottom) == 1 and len(layer.top) == 1 and layer.bottom[0] == layer.top[0]:
pass
else:
for top in layer.top:
tops.append(top)
for bottom in layer.bottom:
bottoms[bottom] = True
if train_data_layer is None:
assert val_data_layer is None, 'cannot specify a test data layer without a train data layer'
assert len(loss_layers) > 0, 'must specify a loss layer'
network_outputs = []
for name in tops:
if name not in bottoms:
network_outputs.append(name)
assert len(network_outputs), 'network must have an output'
# Update num_output for any output InnerProduct layers automatically
for layer in hidden_layers.layer:
if layer.type == 'InnerProduct':
for top in layer.top:
if top in network_outputs:
layer.inner_product_param.num_output = len(self.get_labels())
break
### Write train_val file
train_val_network = caffe_pb2.NetParameter()
dataset_backend = self.dataset.train_db_task().backend
# data layers
if train_data_layer is not None:
if dataset_backend == 'lmdb':
assert train_data_layer.type == 'Data', 'expecting a Data layer'
elif dataset_backend == 'hdf5':
assert train_data_layer.type == 'HDF5Data', 'expecting an HDF5Data layer'
if dataset_backend == 'lmdb' and train_data_layer.HasField('data_param'):
assert not train_data_layer.data_param.HasField('source'), "don't set the data_param.source"
assert not train_data_layer.data_param.HasField('backend'), "don't set the data_param.backend"
if dataset_backend == 'hdf5' and train_data_layer.HasField('hdf5_data_param'):
assert not train_data_layer.hdf5_data_param.HasField('source'), "don't set the hdf5_data_param.source"
max_crop_size = min(self.dataset.image_dims[0], self.dataset.image_dims[1])
if self.crop_size:
assert dataset_backend != 'hdf5', 'HDF5Data layer does not support cropping'
assert self.crop_size <= max_crop_size, 'crop_size is larger than the image size'
train_data_layer.transform_param.crop_size = self.crop_size
elif train_data_layer.transform_param.HasField('crop_size'):
cs = train_data_layer.transform_param.crop_size
if cs > max_crop_size:
# don't throw an error here
cs = max_crop_size
train_data_layer.transform_param.crop_size = cs
self.crop_size = cs
train_val_network.layer.add().CopyFrom(train_data_layer)
train_data_layer = train_val_network.layer[-1]
if val_data_layer is not None and has_val_set:
if dataset_backend == 'lmdb':
assert val_data_layer.type == 'Data', 'expecting a Data layer'
elif dataset_backend == 'hdf5':
assert val_data_layer.type == 'HDF5Data', 'expecting an HDF5Data layer'
if dataset_backend == 'lmdb' and val_data_layer.HasField('data_param'):
assert not val_data_layer.data_param.HasField('source'), "don't set the data_param.source"
assert not val_data_layer.data_param.HasField('backend'), "don't set the data_param.backend"
if dataset_backend == 'hdf5' and val_data_layer.HasField('hdf5_data_param'):
assert not val_data_layer.hdf5_data_param.HasField('source'), "don't set the hdf5_data_param.source"
if self.crop_size:
# use our error checking from the train layer
val_data_layer.transform_param.crop_size = self.crop_size
train_val_network.layer.add().CopyFrom(val_data_layer)
val_data_layer = train_val_network.layer[-1]
else:
layer_type = 'Data'
if dataset_backend == 'hdf5':
layer_type = 'HDF5Data'
train_data_layer = train_val_network.layer.add(type = layer_type, name = 'data')
train_data_layer.top.append('data')
train_data_layer.top.append('label')
train_data_layer.include.add(phase = caffe_pb2.TRAIN)
if dataset_backend == 'lmdb':
train_data_layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
elif dataset_backend == 'hdf5':
train_data_layer.hdf5_data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if self.crop_size:
assert dataset_backend != 'hdf5', 'HDF5Data layer does not support cropping'
train_data_layer.transform_param.crop_size = self.crop_size
if has_val_set:
val_data_layer = train_val_network.layer.add(type = layer_type, name = 'data')
val_data_layer.top.append('data')
val_data_layer.top.append('label')
val_data_layer.include.add(phase = caffe_pb2.TEST)
if dataset_backend == 'lmdb':
val_data_layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
elif dataset_backend == 'hdf5':
val_data_layer.hdf5_data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if self.crop_size:
val_data_layer.transform_param.crop_size = self.crop_size
if dataset_backend == 'lmdb':
train_data_layer.data_param.source = self.dataset.path(self.dataset.train_db_task().db_name)
train_data_layer.data_param.backend = caffe_pb2.DataParameter.LMDB
if val_data_layer is not None and has_val_set:
val_data_layer.data_param.source = self.dataset.path(self.dataset.val_db_task().db_name)
val_data_layer.data_param.backend = caffe_pb2.DataParameter.LMDB
elif dataset_backend == 'hdf5':
train_data_layer.hdf5_data_param.source = self.dataset.path(self.dataset.train_db_task().textfile)
if val_data_layer is not None and has_val_set:
val_data_layer.hdf5_data_param.source = self.dataset.path(self.dataset.val_db_task().textfile)
if self.use_mean == 'pixel':
assert dataset_backend != 'hdf5', 'HDF5Data layer does not support mean subtraction'
mean_pixel = self.get_mean_pixel(self.dataset.path(self.dataset.train_db_task().mean_file))
self.set_mean_value(train_data_layer, mean_pixel)
if val_data_layer is not None and has_val_set:
self.set_mean_value(val_data_layer, mean_pixel)
elif self.use_mean == 'image':
self.set_mean_file(train_data_layer, self.dataset.path(self.dataset.train_db_task().mean_file))
if val_data_layer is not None and has_val_set:
self.set_mean_file(val_data_layer, self.dataset.path(self.dataset.train_db_task().mean_file))
if self.batch_size:
if dataset_backend == 'lmdb':
train_data_layer.data_param.batch_size = self.batch_size
if val_data_layer is not None and has_val_set:
val_data_layer.data_param.batch_size = self.batch_size
elif dataset_backend == 'hdf5':
train_data_layer.hdf5_data_param.batch_size = self.batch_size
if val_data_layer is not None and has_val_set:
val_data_layer.hdf5_data_param.batch_size = self.batch_size
else:
if dataset_backend == 'lmdb':
if not train_data_layer.data_param.HasField('batch_size'):
train_data_layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if val_data_layer is not None and has_val_set and not val_data_layer.data_param.HasField('batch_size'):
val_data_layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
elif dataset_backend == 'hdf5':
if not train_data_layer.hdf5_data_param.HasField('batch_size'):
train_data_layer.hdf5_data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if val_data_layer is not None and has_val_set and not val_data_layer.hdf5_data_param.HasField('batch_size'):
val_data_layer.hdf5_data_param.batch_size = constants.DEFAULT_BATCH_SIZE
# hidden layers
train_val_network.MergeFrom(hidden_layers)
# output layers
train_val_network.layer.extend(loss_layers)
train_val_network.layer.extend(accuracy_layers)
with open(self.path(self.train_val_file), 'w') as outfile:
text_format.PrintMessage(train_val_network, outfile)
### Write deploy file
deploy_network = caffe_pb2.NetParameter()
# input
deploy_network.input.append('data')
shape = deploy_network.input_shape.add()
shape.dim.append(1)
shape.dim.append(self.dataset.image_dims[2])
if self.crop_size:
shape.dim.append(self.crop_size)
shape.dim.append(self.crop_size)
else:
shape.dim.append(self.dataset.image_dims[0])
shape.dim.append(self.dataset.image_dims[1])
# hidden layers
deploy_network.MergeFrom(hidden_layers)
# output layers
if loss_layers[-1].type == 'SoftmaxWithLoss':
prob_layer = deploy_network.layer.add(
type = 'Softmax',
name = 'prob')
prob_layer.bottom.append(network_outputs[-1])
prob_layer.top.append('prob')
with open(self.path(self.deploy_file), 'w') as outfile:
text_format.PrintMessage(deploy_network, outfile)
### Write solver file
solver = caffe_pb2.SolverParameter()
# get enum value for solver type
solver.solver_type = getattr(solver, self.solver_type)
solver.net = self.train_val_file
# Set CPU/GPU mode
if config_value('caffe_root')['cuda_enabled'] and \
bool(config_value('gpu_list')):
solver.solver_mode = caffe_pb2.SolverParameter.GPU
else:
solver.solver_mode = caffe_pb2.SolverParameter.CPU
solver.snapshot_prefix = self.snapshot_prefix
# Epochs -> Iterations
train_iter = int(math.ceil(float(self.dataset.train_db_task().entries_count) / train_data_layer.data_param.batch_size))
solver.max_iter = train_iter * self.train_epochs
snapshot_interval = self.snapshot_interval * train_iter
if 0 < snapshot_interval <= 1:
solver.snapshot = 1 # don't round down
elif 1 < snapshot_interval < solver.max_iter:
solver.snapshot = int(snapshot_interval)
else:
solver.snapshot = 0 # only take one snapshot at the end
if has_val_set and self.val_interval:
solver.test_iter.append(int(math.ceil(float(self.dataset.val_db_task().entries_count) / val_data_layer.data_param.batch_size)))
val_interval = self.val_interval * train_iter
if 0 < val_interval <= 1:
solver.test_interval = 1 # don't round down
elif 1 < val_interval < solver.max_iter:
solver.test_interval = int(val_interval)
else:
solver.test_interval = solver.max_iter # only test once at the end
# Learning rate
solver.base_lr = self.learning_rate
solver.lr_policy = self.lr_policy['policy']
scale = float(solver.max_iter)/100.0
if solver.lr_policy == 'fixed':
pass
elif solver.lr_policy == 'step':
# stepsize = stepsize * scale
solver.stepsize = int(math.ceil(float(self.lr_policy['stepsize']) * scale))
solver.gamma = self.lr_policy['gamma']
elif solver.lr_policy == 'multistep':
for value in self.lr_policy['stepvalue']:
# stepvalue = stepvalue * scale
solver.stepvalue.append(int(math.ceil(float(value) * scale)))
solver.gamma = self.lr_policy['gamma']
elif solver.lr_policy == 'exp':
# gamma = gamma^(1/scale)
solver.gamma = math.pow(self.lr_policy['gamma'], 1.0/scale)
elif solver.lr_policy == 'inv':
# gamma = gamma / scale
solver.gamma = self.lr_policy['gamma'] / scale
solver.power = self.lr_policy['power']
elif solver.lr_policy == 'poly':
solver.power = self.lr_policy['power']
elif solver.lr_policy == 'sigmoid':
# gamma = -gamma / scale
solver.gamma = -1.0 * self.lr_policy['gamma'] / scale
# stepsize = stepsize * scale
solver.stepsize = int(math.ceil(float(self.lr_policy['stepsize']) * scale))
else:
raise Exception('Unknown lr_policy: "%s"' % solver.lr_policy)
# go with the suggested defaults
if solver.solver_type != solver.ADAGRAD:
solver.momentum = 0.9
solver.weight_decay = 0.0005
# Display 8x per epoch, or once per 5000 images, whichever is more frequent
solver.display = max(1, min(
int(math.floor(float(solver.max_iter) / (self.train_epochs * 8))),
int(math.ceil(5000.0 / train_data_layer.data_param.batch_size))
))
if self.random_seed is not None:
solver.random_seed = self.random_seed
with open(self.path(self.solver_file), 'w') as outfile:
text_format.PrintMessage(solver, outfile)
self.solver = solver # save for later
return True
def save_files_generic(self):
"""
Save solver, train_val and deploy files to disk
"""
train_image_db = None
train_labels_db = None
val_image_db = None
val_labels_db = None
for task in self.dataset.tasks:
if task.purpose == 'Training Images':
train_image_db = task
if task.purpose == 'Training Labels':
train_labels_db = task
if task.purpose == 'Validation Images':
val_image_db = task
if task.purpose == 'Validation Labels':
val_labels_db = task
assert train_image_db is not None, 'Training images are required'
### Split up train_val and deploy layers
train_image_data_layer = None
train_label_data_layer = None
val_image_data_layer = None
val_label_data_layer = None
train_val_layers = caffe_pb2.NetParameter()
deploy_layers = caffe_pb2.NetParameter()
for layer in self.network.layer:
assert layer.type not in ['MemoryData', 'HDF5Data', 'ImageData'], 'unsupported data layer type'
if layer.name.startswith('train_'):
train_val_layers.layer.add().CopyFrom(layer)
train_val_layers.layer[-1].name = train_val_layers.layer[-1].name[6:]
elif layer.name.startswith('deploy_'):
deploy_layers.layer.add().CopyFrom(layer)
deploy_layers.layer[-1].name = deploy_layers.layer[-1].name[7:]
elif layer.type == 'Data':
for rule in layer.include:
if rule.phase == caffe_pb2.TRAIN:
if 'data' in layer.top:
assert train_image_data_layer is None, 'cannot specify two train image data layers'
train_image_data_layer = layer
elif 'label' in layer.top:
assert train_label_data_layer is None, 'cannot specify two train label data layers'
train_label_data_layer = layer
elif rule.phase == caffe_pb2.TEST:
if 'data' in layer.top:
assert val_image_data_layer is None, 'cannot specify two val image data layers'
val_image_data_layer = layer
elif 'label' in layer.top:
assert val_label_data_layer is None, 'cannot specify two val label data layers'
val_label_data_layer = layer
elif 'loss' in layer.type.lower():
# Don't add it to the deploy network
train_val_layers.layer.add().CopyFrom(layer)
elif 'accuracy' in layer.type.lower():
# Don't add it to the deploy network
train_val_layers.layer.add().CopyFrom(layer)
else:
train_val_layers.layer.add().CopyFrom(layer)
deploy_layers.layer.add().CopyFrom(layer)
### Write train_val file
train_val_network = caffe_pb2.NetParameter()
# data layers
train_image_data_layer = self.make_generic_data_layer(train_image_db, train_image_data_layer, 'data', 'data', caffe_pb2.TRAIN)
if train_image_data_layer is not None:
train_val_network.layer.add().CopyFrom(train_image_data_layer)
train_label_data_layer = self.make_generic_data_layer(train_labels_db, train_label_data_layer, 'label', 'label', caffe_pb2.TRAIN)
if train_label_data_layer is not None:
train_val_network.layer.add().CopyFrom(train_label_data_layer)
val_image_data_layer = self.make_generic_data_layer(val_image_db, val_image_data_layer, 'data', 'data', caffe_pb2.TEST)
if val_image_data_layer is not None:
train_val_network.layer.add().CopyFrom(val_image_data_layer)
val_label_data_layer = self.make_generic_data_layer(val_labels_db, val_label_data_layer, 'label', 'label', caffe_pb2.TEST)
if val_label_data_layer is not None:
train_val_network.layer.add().CopyFrom(val_label_data_layer)
# hidden layers
train_val_network.MergeFrom(train_val_layers)
with open(self.path(self.train_val_file), 'w') as outfile:
text_format.PrintMessage(train_val_network, outfile)
### Write deploy file
deploy_network = caffe_pb2.NetParameter()
# input
deploy_network.input.append('data')
shape = deploy_network.input_shape.add()
shape.dim.append(1)
shape.dim.append(train_image_db.image_channels)
if train_image_data_layer.transform_param.HasField('crop_size'):
shape.dim.append(
train_image_data_layer.transform_param.crop_size)
shape.dim.append(
train_image_data_layer.transform_param.crop_size)
else:
shape.dim.append(train_image_db.image_height)
shape.dim.append(train_image_db.image_width)
# hidden layers
deploy_network.MergeFrom(deploy_layers)
with open(self.path(self.deploy_file), 'w') as outfile:
text_format.PrintMessage(deploy_network, outfile)
### Write solver file
solver = caffe_pb2.SolverParameter()
# get enum value for solver type
solver.solver_type = getattr(solver, self.solver_type)
solver.net = self.train_val_file
# Set CPU/GPU mode
if config_value('caffe_root')['cuda_enabled'] and \
bool(config_value('gpu_list')):
solver.solver_mode = caffe_pb2.SolverParameter.GPU
else:
solver.solver_mode = caffe_pb2.SolverParameter.CPU
solver.snapshot_prefix = self.snapshot_prefix
# Epochs -> Iterations
train_iter = int(math.ceil(float(train_image_db.image_count) / train_image_data_layer.data_param.batch_size))
solver.max_iter = train_iter * self.train_epochs
snapshot_interval = self.snapshot_interval * train_iter
if 0 < snapshot_interval <= 1:
solver.snapshot = 1 # don't round down
elif 1 < snapshot_interval < solver.max_iter:
solver.snapshot = int(snapshot_interval)
else:
solver.snapshot = 0 # only take one snapshot at the end
if val_image_data_layer:
solver.test_iter.append(int(math.ceil(float(val_image_db.image_count) / val_image_data_layer.data_param.batch_size)))
val_interval = self.val_interval * train_iter
if 0 < val_interval <= 1:
solver.test_interval = 1 # don't round down
elif 1 < val_interval < solver.max_iter:
solver.test_interval = int(val_interval)
else:
solver.test_interval = solver.max_iter # only test once at the end
# Learning rate
solver.base_lr = self.learning_rate
solver.lr_policy = self.lr_policy['policy']
scale = float(solver.max_iter)/100.0
if solver.lr_policy == 'fixed':
pass
elif solver.lr_policy == 'step':
# stepsize = stepsize * scale
solver.stepsize = int(math.ceil(float(self.lr_policy['stepsize']) * scale))
solver.gamma = self.lr_policy['gamma']
elif solver.lr_policy == 'multistep':
for value in self.lr_policy['stepvalue']:
# stepvalue = stepvalue * scale
solver.stepvalue.append(int(math.ceil(float(value) * scale)))
solver.gamma = self.lr_policy['gamma']
elif solver.lr_policy == 'exp':
# gamma = gamma^(1/scale)
solver.gamma = math.pow(self.lr_policy['gamma'], 1.0/scale)
elif solver.lr_policy == 'inv':
# gamma = gamma / scale
solver.gamma = self.lr_policy['gamma'] / scale
solver.power = self.lr_policy['power']
elif solver.lr_policy == 'poly':
solver.power = self.lr_policy['power']
elif solver.lr_policy == 'sigmoid':
# gamma = -gamma / scale
solver.gamma = -1.0 * self.lr_policy['gamma'] / scale
# stepsize = stepsize * scale
solver.stepsize = int(math.ceil(float(self.lr_policy['stepsize']) * scale))
else:
raise Exception('Unknown lr_policy: "%s"' % solver.lr_policy)
# go with the suggested defaults
if solver.solver_type != solver.ADAGRAD:
solver.momentum = 0.9
solver.weight_decay = 0.0005
# Display 8x per epoch, or once per 5000 images, whichever is more frequent
solver.display = max(1, min(
int(math.floor(float(solver.max_iter) / (self.train_epochs * 8))),
int(math.ceil(5000.0 / train_image_data_layer.data_param.batch_size))
))
if self.random_seed is not None:
solver.random_seed = self.random_seed
with open(self.path(self.solver_file), 'w') as outfile:
text_format.PrintMessage(solver, outfile)
self.solver = solver # save for later
return True
def make_generic_data_layer(self, db, orig_layer, name, top, phase):
"""
Utility within save_files_generic for creating a Data layer
Returns a LayerParameter (or None)
Arguments:
db -- an AnalyzeDbTask (or None)
orig_layer -- a LayerParameter supplied by the user (or None)
"""
if db is None:
#TODO allow user to specify a standard data layer even if it doesn't exist in the dataset
return None
layer = caffe_pb2.LayerParameter()
if orig_layer is not None:
layer.CopyFrom(orig_layer)
layer.type = 'Data'
layer.name = name
if top not in layer.top:
layer.ClearField('top')
layer.top.append(top)
layer.ClearField('include')
layer.include.add(phase=phase)
# source
if layer.data_param.HasField('source'):
self.logger.warning('Ignoring data_param.source ...')
layer.data_param.source = db.path(db.database)
if layer.data_param.HasField('backend'):
self.logger.warning('Ignoring data_param.backend ...')
layer.data_param.backend = caffe_pb2.DataParameter.LMDB
# batch size
if not layer.data_param.HasField('batch_size'):
layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if self.batch_size:
layer.data_param.batch_size = self.batch_size
# mean
if name == 'data' and self.dataset.mean_file:
if self.use_mean == 'pixel':
mean_pixel = self.get_mean_pixel(self.dataset.path(self.dataset.mean_file))
## remove any values that may already be in the network
self.set_mean_value(layer, mean_pixel)
elif self.use_mean == 'image':
self.set_mean_file(layer, self.dataset.path(self.dataset.mean_file))
# crop size
if name == 'data' and self.crop_size:
max_crop_size = min(db.image_width, db.image_height)
assert self.crop_size <= max_crop_size, 'crop_size is larger than the image size'
layer.transform_param.crop_size = self.crop_size
return layer
def iteration_to_epoch(self, it):
return float(it * self.train_epochs) / self.solver.max_iter
@override
def task_arguments(self, resources, env):
args = [config_value('caffe_root')['executable'],
'train',
'--solver=%s' % self.path(self.solver_file),
]
if 'gpus' in resources:
identifiers = []
for identifier, value in resources['gpus']:
identifiers.append(identifier)
if len(identifiers) == 1:
args.append('--gpu=%s' % identifiers[0])
elif len(identifiers) > 1:
if config_value('caffe_root')['version'] < utils.parse_version('0.14.0-alpha'):
# Prior to version 0.14, NVcaffe used the --gpus switch
args.append('--gpus=%s' % ','.join(identifiers))
else:
args.append('--gpu=%s' % ','.join(identifiers))
if self.pretrained_model:
args.append('--weights=%s' % self.path(self.pretrained_model))
return args
@override
def process_output(self, line):
float_exp = '(NaN|[-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?)'
self.caffe_log.write('%s\n' % line)
self.caffe_log.flush()
# parse caffe output
timestamp, level, message = self.preprocess_output_caffe(line)
if not message:
return True
# iteration updates
match = re.match(r'Iteration (\d+)', message)
if match:
i = int(match.group(1))
self.new_iteration(i)
# net output
match = re.match(r'(Train|Test) net output #(\d+): (\S*) = %s' % float_exp, message, flags=re.IGNORECASE)
if match:
phase = match.group(1)
index = int(match.group(2))
name = match.group(3)
value = match.group(4)
assert value.lower() != 'nan', 'Network outputted NaN for "%s" (%s phase). Try decreasing your learning rate.' % (name, phase)
value = float(value)
# Find the layer type
kind = '?'
for layer in self.network.layer:
if name in layer.top:
kind = layer.type
break
if phase.lower() == 'train':
self.save_train_output(name, kind, value)
elif phase.lower() == 'test':
self.save_val_output(name, kind, value)
return True
# learning rate updates
match = re.match(r'Iteration (\d+).*lr = %s' % float_exp, message, flags=re.IGNORECASE)
if match:
i = int(match.group(1))
lr = float(match.group(2))
self.save_train_output('learning_rate', 'LearningRate', lr)
return True
# snapshot saved
if self.saving_snapshot:
if not message.startswith('Snapshotting solver state'):
self.logger.warning('caffe output format seems to have changed. Expected "Snapshotting solver state..." after "Snapshotting to..."')
else:
self.logger.debug('Snapshot saved.')
self.detect_snapshots()
self.send_snapshot_update()
self.saving_snapshot = False
return True
# snapshot starting
match = re.match(r'Snapshotting to (.*)\s*$', message)
if match:
self.saving_snapshot = True
return True
if level in ['error', 'critical']:
self.logger.error('%s: %s' % (self.name(), message))
self.exception = message
return True
return True
def preprocess_output_caffe(self, line):
"""
Takes line of output and parses it according to caffe's output format
Returns (timestamp, level, message) or (None, None, None)
"""
# NOTE: This must change when the logging format changes
# LMMDD HH:MM:SS.MICROS pid file:lineno] message
match = re.match(r'(\w)(\d{4} \S{8}).*]\s+(\S.*)$', line)
if match:
level = match.group(1)
# add the year because caffe omits it
timestr = '%s%s' % (time.strftime('%Y'), match.group(2))
message = match.group(3)
if level == 'I':
level = 'info'
elif level == 'W':
level = 'warning'
elif level == 'E':
level = 'error'
elif level == 'F': #FAIL
level = 'critical'
timestamp = time.mktime(time.strptime(timestr, '%Y%m%d %H:%M:%S'))
return (timestamp, level, message)
else:
#self.logger.warning('Unrecognized task output "%s"' % line)
return (None, None, None)
def new_iteration(self, it):
"""
Update current_iteration
"""
if self.current_iteration == it:
return
self.current_iteration = it
self.send_progress_update(self.iteration_to_epoch(it))
def send_snapshot_update(self):
"""
Sends socketio message about the snapshot list
"""
from digits.webapp import socketio
socketio.emit('task update',
{
'task': self.html_id(),
'update': 'snapshots',
'data': self.snapshot_list(),
},
namespace='/jobs',
room=self.job_id,
)
@override
def after_run(self):
super(CaffeTrainTask, self).after_run()
self.caffe_log.close()
@override
def after_runtime_error(self):
if os.path.exists(self.path(self.CAFFE_LOG)):
output = subprocess.check_output(['tail', '-n40', self.path(self.CAFFE_LOG)])
lines = []
for line in output.split('\n'):
# parse caffe header
timestamp, level, message = self.preprocess_output_caffe(line)
if message:
lines.append(message)
# return the last 20 lines
self.traceback = '\n'.join(lines[len(lines)-20:])
if 'DIGITS_MODE_TEST' in os.environ:
print output
### TrainTask overrides
@override
def detect_snapshots(self):
self.snapshots = []
snapshot_dir = os.path.join(self.job_dir, os.path.dirname(self.snapshot_prefix))
snapshots = []
solverstates = []
for filename in os.listdir(snapshot_dir):
# find models
match = re.match(r'%s_iter_(\d+)\.caffemodel' % os.path.basename(self.snapshot_prefix), filename)
if match:
iteration = int(match.group(1))
epoch = float(iteration) / (float(self.solver.max_iter)/self.train_epochs)
# assert epoch.is_integer(), '%s is not an integer' % epoch
epoch = round(epoch,3)
# if epoch is int
if epoch == math.ceil(epoch):
# print epoch,math.ceil(epoch),int(epoch)
epoch = int(epoch)
snapshots.append( (
os.path.join(snapshot_dir, filename),
epoch
)
)
# find solverstates
match = re.match(r'%s_iter_(\d+)\.solverstate' % os.path.basename(self.snapshot_prefix), filename)
if match:
solverstates.append( (
os.path.join(snapshot_dir, filename),
int(match.group(1))
)
)
# delete all but the most recent solverstate
for filename, iteration in sorted(solverstates, key=lambda tup: tup[1])[:-1]:
#print 'Removing "%s"' % filename
os.remove(filename)
self.snapshots = sorted(snapshots, key=lambda tup: tup[1])
return len(self.snapshots) > 0
@override
def est_next_snapshot(self):
if self.status != Status.RUN or self.current_iteration == 0:
return None
elapsed = time.time() - self.status_updates[-1][1]
next_snapshot_iteration = (1 + self.current_iteration//self.snapshot_interval) * self.snapshot_interval
return (next_snapshot_iteration - self.current_iteration) * elapsed // self.current_iteration
@override
def can_view_weights(self):
return False
@override
def can_infer_one(self):
if isinstance(self.dataset, dataset.ImageClassificationDatasetJob):
return True
return False
@override
def infer_one(self, data, snapshot_epoch=None, layers=None):
if isinstance(self.dataset, dataset.ImageClassificationDatasetJob):
return self.classify_one(data,
snapshot_epoch=snapshot_epoch,
layers=layers,
)
elif isinstance(self.dataset, dataset.GenericImageDatasetJob):
return self.infer_one_generic(data,
snapshot_epoch=snapshot_epoch,
layers=layers,
)
raise NotImplementedError()
def classify_one(self, image, snapshot_epoch=None, layers=None):
"""
Classify an image
Returns (predictions, visualizations)
predictions -- an array of [ (label, confidence), ...] for each label, sorted by confidence
visualizations -- a list of dicts for the specified layers
Returns (None, None) if something goes wrong
Arguments:
image -- a np.array
Keyword arguments:
snapshot_epoch -- which snapshot to use
layers -- which layer activation[s] and weight[s] to visualize
"""
labels = self.get_labels()
net = self.get_net(snapshot_epoch)
# process image
if image.ndim == 2:
image = image[:,:,np.newaxis]
preprocessed = self.get_transformer().preprocess(
'data', image)
# reshape net input (if necessary)
test_shape = (1,) + preprocessed.shape
if net.blobs['data'].data.shape != test_shape:
net.blobs['data'].reshape(*test_shape)
# run inference
net.blobs['data'].data[...] = preprocessed
output = net.forward()
scores = output[net.outputs[-1]].flatten()
indices = (-scores).argsort()
predictions = []
for i in indices:
predictions.append( (labels[i], scores[i]) )
visualizations = self.get_layer_visualizations(net, layers)
return (predictions, visualizations)
def infer_one_generic(self, image, snapshot_epoch=None, layers=None):
"""
Run inference on one image for a generic model
Returns (output, visualizations)
output -- an dict of string -> np.ndarray
visualizations -- a list of dicts for the specified layers
Returns (None, None) if something goes wrong
Arguments:
image -- an np.ndarray
Keyword arguments:
snapshot_epoch -- which snapshot to use
layers -- which layer activation[s] and weight[s] to visualize
"""
net = self.get_net(snapshot_epoch)
# process image
if image.ndim == 2:
image = image[:,:,np.newaxis]
preprocessed = self.get_transformer().preprocess(
'data', image)
# reshape net input (if necessary)
test_shape = (1,) + preprocessed.shape
if net.blobs['data'].data.shape != test_shape:
net.blobs['data'].reshape(*test_shape)
# run inference
net.blobs['data'].data[...] = preprocessed
output = net.forward()
visualizations = self.get_layer_visualizations(net, layers)
return (output, visualizations)
def get_layer_visualizations(self, net, layers='all'):
"""
Returns visualizations of various layers in the network
"""
# add visualizations
visualizations = []
if layers and layers != 'none':
if layers == 'all':
added_activations = []
for layer in self.network.layer:
print 'Computing visualizations for "%s" ...' % layer.name
for bottom in layer.bottom:
if bottom in net.blobs and bottom not in added_activations:
data = net.blobs[bottom].data[0]
vis = utils.image.get_layer_vis_square(data,
allow_heatmap=bool(bottom != 'data'))
mean, std, hist = self.get_layer_statistics(data)
visualizations.append(
{
'name': str(bottom),
'vis_type': 'Activation',
'image_html': utils.image.embed_image_html(vis),
'data_stats': {
'shape': data.shape,
'mean': mean,
'stddev': std,
'histogram': hist,
},
}
)
added_activations.append(bottom)
if layer.name in net.params:
data = net.params[layer.name][0].data
if layer.type not in ['InnerProduct']:
vis = utils.image.get_layer_vis_square(data)
else:
vis = None
mean, std, hist = self.get_layer_statistics(data)
params = net.params[layer.name]
weight_count = reduce(operator.mul, params[0].data.shape, 1)
if len(params) > 1:
bias_count = reduce(operator.mul, params[1].data.shape, 1)
else:
bias_count = 0
parameter_count = weight_count + bias_count
visualizations.append(
{
'name': str(layer.name),
'vis_type': 'Weights',
'layer_type': layer.type,
'param_count': parameter_count,
'image_html': utils.image.embed_image_html(vis),
'data_stats': {
'shape':data.shape,
'mean': mean,
'stddev': std,
'histogram': hist,
},
}
)
for top in layer.top:
if top in net.blobs and top not in added_activations:
data = net.blobs[top].data[0]
normalize = True
# don't normalize softmax layers
if layer.type == 'Softmax':
normalize = False
vis = utils.image.get_layer_vis_square(data,
normalize = normalize,
allow_heatmap = bool(top != 'data'))
mean, std, hist = self.get_layer_statistics(data)
visualizations.append(
{
'name': str(top),
'vis_type': 'Activation',
'image_html': utils.image.embed_image_html(vis),
'data_stats': {
'shape': data.shape,
'mean': mean,
'stddev': std,
'histogram': hist,
},
}
)
added_activations.append(top)
else:
raise NotImplementedError
return visualizations
def get_layer_statistics(self, data):
"""
Returns statistics for the given layer data:
(mean, standard deviation, histogram)
histogram -- [y, x, ticks]
Arguments:
data -- a np.ndarray
"""
# XXX These calculations can be super slow
mean = np.mean(data)
std = np.std(data)
y, x = np.histogram(data, bins=20)
y = list(y)
ticks = x[[0,len(x)/2,-1]]
x = [(x[i]+x[i+1])/2.0 for i in xrange(len(x)-1)]
ticks = list(ticks)
return (mean, std, [y, x, ticks])
@override
def can_infer_many(self):
if isinstance(self.dataset, dataset.ImageClassificationDatasetJob):
return True
return False
@override
def infer_many(self, data, snapshot_epoch=None):
if isinstance(self.dataset, dataset.ImageClassificationDatasetJob):
return self.classify_many(data, snapshot_epoch=snapshot_epoch)
elif isinstance(self.dataset, dataset.GenericImageDatasetJob):
return self.infer_many_generic(data, snapshot_epoch=snapshot_epoch)
raise NotImplementedError()
def classify_many(self, images, snapshot_epoch=None):
"""
Returns (labels, results):
labels -- an array of strings
results -- a 2D np array:
[
[image0_label0_confidence, image0_label1_confidence, ...],
[image1_label0_confidence, image1_label1_confidence, ...],
...
]
Arguments:
images -- a list of np.arrays
Keyword arguments:
snapshot_epoch -- which snapshot to use
"""
labels = self.get_labels()
net = self.get_net(snapshot_epoch)
caffe_images = []
for image in images:
if image.ndim == 2:
caffe_images.append(image[:,:,np.newaxis])
else:
caffe_images.append(image)
caffe_images = np.array(caffe_images)
data_shape = tuple(self.get_transformer().inputs['data'])[1:]
if self.batch_size:
data_shape = (self.batch_size,) + data_shape
# TODO: grab batch_size from the TEST phase in train_val network
else:
data_shape = (constants.DEFAULT_BATCH_SIZE,) + data_shape
scores = None
for chunk in [caffe_images[x:x+data_shape[0]] for x in xrange(0, len(caffe_images), data_shape[0])]:
new_shape = (len(chunk),) + data_shape[1:]
if net.blobs['data'].data.shape != new_shape:
net.blobs['data'].reshape(*new_shape)
for index, image in enumerate(chunk):
net.blobs['data'].data[index] = self.get_transformer().preprocess(
'data', image)
output = net.forward()[net.outputs[-1]]
if scores is None:
scores = np.copy(output)
else:
scores = np.vstack((scores, output))
print 'Processed %s/%s images' % (len(scores), len(caffe_images))
return (labels, scores)
def infer_many_generic(self, images, snapshot_epoch=None):
"""
Returns a list of np.ndarrays, one for each image
Arguments:
images -- a list of np.arrays
Keyword arguments:
snapshot_epoch -- which snapshot to use
"""
net = self.get_net(snapshot_epoch)
caffe_images = []
for image in images:
if image.ndim == 2:
caffe_images.append(image[:,:,np.newaxis])
else:
caffe_images.append(image)
caffe_images = np.array(caffe_images)
data_shape = tuple(self.get_transformer().inputs['data'])[1:]
if self.batch_size:
data_shape = (self.batch_size,) + data_shape
# TODO: grab batch_size from the TEST phase in train_val network
else:
data_shape = (constants.DEFAULT_BATCH_SIZE,) + data_shape
outputs = None
for chunk in [caffe_images[x:x+data_shape[0]] for x in xrange(0, len(caffe_images), data_shape[0])]:
new_shape = (len(chunk),) + data_shape[1:]
if net.blobs['data'].data.shape != new_shape:
net.blobs['data'].reshape(*new_shape)
for index, image in enumerate(chunk):
net.blobs['data'].data[index] = self.get_transformer().preprocess(
'data', image)
o = net.forward()
if outputs is None:
outputs = o
else:
for name,blob in o.iteritems():
outputs[name] = np.vstack((outputs[name], blob))
print 'Processed %s/%s images' % (len(outputs[outputs.keys()[0]]), len(caffe_images))
return outputs
def has_model(self):
"""
Returns True if there is a model that can be used
"""
return len(self.snapshots) > 0
def get_net(self, epoch=None):
"""
Returns an instance of caffe.Net
Keyword Arguments:
epoch -- which snapshot to load (default is -1 to load the most recently generated snapshot)
"""
if not self.has_model():
return False
file_to_load = None
if not epoch:
epoch = self.snapshots[-1][1]
file_to_load = self.snapshots[-1][0]
else:
for snapshot_file, snapshot_epoch in self.snapshots:
if snapshot_epoch == epoch:
file_to_load = snapshot_file
break
if file_to_load is None:
raise Exception('snapshot not found for epoch "%s"' % epoch)
# check if already loaded
if self.loaded_snapshot_file and self.loaded_snapshot_file == file_to_load \
and hasattr(self, '_caffe_net') and self._caffe_net is not None:
return self._caffe_net
if config_value('caffe_root')['cuda_enabled'] and\
config_value('gpu_list'):
caffe.set_mode_gpu()
# load a new model
self._caffe_net = caffe.Net(
self.path(self.deploy_file),
file_to_load,
caffe.TEST)
self.loaded_snapshot_epoch = epoch
self.loaded_snapshot_file = file_to_load
return self._caffe_net
def get_transformer(self):
"""
Returns an instance of caffe.io.Transformer
"""
# check if already loaded
if hasattr(self, '_transformer') and self._transformer is not None:
return self._transformer
data_shape = None
channel_swap = None
mean_pixel = None
mean_image = None
network = caffe_pb2.NetParameter()
with open(self.path(self.deploy_file)) as infile:
text_format.Merge(infile.read(), network)
if network.input_shape:
data_shape = network.input_shape[0].dim
else:
data_shape = network.input_dim[:4]
if isinstance(self.dataset, dataset.ImageClassificationDatasetJob):
if self.dataset.image_dims[2] == 3 and \
self.dataset.train_db_task().image_channel_order == 'BGR':
# XXX see issue #59
channel_swap = (2,1,0)
if self.use_mean == 'pixel':
mean_pixel = self.get_mean_pixel(self.dataset.path(self.dataset.train_db_task().mean_file))
elif self.use_mean == 'image':
mean_image = self.get_mean_image(self.dataset.path(self.dataset.train_db_task().mean_file), True)
elif isinstance(self.dataset, dataset.GenericImageDatasetJob):
task = self.dataset.analyze_db_tasks()[0]
if task.image_channels == 3:
# XXX see issue #59
channel_swap = (2,1,0)
if self.dataset.mean_file:
if self.use_mean == 'pixel':
mean_pixel = self.get_mean_pixel(self.dataset.path(self.dataset.mean_file))
elif self.use_mean == 'image':
mean_image = self.get_mean_image(self.dataset.path(self.dataset.mean_file), True)
t = caffe.io.Transformer(
inputs = {'data': tuple(data_shape)}
)
# transpose to (channels, height, width)
t.set_transpose('data', (2,0,1))
if channel_swap is not None:
# swap color channels
t.set_channel_swap('data', channel_swap)
# set mean
if self.use_mean == 'pixel' and mean_pixel is not None:
t.set_mean('data', mean_pixel)
elif self.use_mean == 'image' and mean_image is not None:
t.set_mean('data', mean_image)
#t.set_raw_scale('data', 255) # [0,255] range instead of [0,1]
self._transformer = t
return self._transformer
@override
def get_model_files(self):
"""
return paths to model files
"""
return {
"Solver": self.solver_file,
"Network (train/val)": self.train_val_file,
"Network (deploy)": self.deploy_file
}
@override
def get_network_desc(self):
"""
return text description of model
"""
return text_format.MessageToString(self.network)
|
import { Random } from 'meteor/random';
import { Messages, Rooms, Users } from '../../../models';
import { transformMappedData } from '../../lib/misc/transformMappedData';
export class AppMessagesConverter {
constructor(orch) {
this.orch = orch;
}
convertById(msgId) {
const msg = Messages.findOneById(msgId);
return this.convertMessage(msg);
}
convertMessage(msgObj) {
if (!msgObj) {
return undefined;
}
const map = {
id: '_id',
threadId: 'tmid',
reactions: 'reactions',
parseUrls: 'parseUrls',
text: 'msg',
createdAt: 'ts',
updatedAt: '_updatedAt',
editedAt: 'editedAt',
emoji: 'emoji',
avatarUrl: 'avatar',
alias: 'alias',
file: 'file',
customFields: 'customFields',
groupable: 'groupable',
token: 'token',
blocks: 'blocks',
room: (message) => {
const result = this.orch.getConverters().get('rooms').convertById(message.rid);
delete message.rid;
return result;
},
editor: (message) => {
const { editedBy } = message;
delete message.editedBy;
if (!editedBy) {
return undefined;
}
return this.orch.getConverters().get('users').convertById(editedBy._id);
},
attachments: (message) => {
const result = this._convertAttachmentsToApp(message.attachments);
delete message.attachments;
return result;
},
sender: (message) => {
if (!message.u || !message.u._id) {
return undefined;
}
let user = this.orch.getConverters().get('users').convertById(message.u._id);
// When the sender of the message is a Guest (livechat) and not a user
if (!user) {
user = this.orch.getConverters().get('users').convertToApp(message.u);
}
delete message.u;
return user;
},
};
return transformMappedData(msgObj, map);
}
convertAppMessage(message) {
if (!message || !message.room) {
return undefined;
}
const room = Rooms.findOneById(message.room.id);
if (!room) {
throw new Error('Invalid room provided on the message.');
}
let u;
if (message.sender && message.sender.id) {
const user = Users.findOneById(message.sender.id);
if (user) {
u = {
_id: user._id,
username: user.username,
name: user.name,
};
} else {
u = {
_id: message.sender.id,
username: message.sender.username,
name: message.sender.name,
};
}
}
let editedBy;
if (message.editor) {
const editor = Users.findOneById(message.editor.id);
editedBy = {
_id: editor._id,
username: editor.username,
};
}
const attachments = this._convertAppAttachments(message.attachments);
const newMessage = {
_id: message.id || Random.id(),
tmid: message.threadId,
rid: room._id,
u,
msg: message.text,
ts: message.createdAt || new Date(),
_updatedAt: message.updatedAt || new Date(),
editedBy,
editedAt: message.editedAt,
emoji: message.emoji,
avatar: message.avatarUrl,
alias: message.alias,
customFields: message.customFields,
groupable: message.groupable,
attachments,
reactions: message.reactions,
parseUrls: message.parseUrls,
blocks: message.blocks,
token: message.token,
};
return Object.assign(newMessage, message._unmappedProperties_);
}
_convertAppAttachments(attachments) {
if (typeof attachments === 'undefined' || !Array.isArray(attachments)) {
return undefined;
}
return attachments.map((attachment) => Object.assign({
collapsed: attachment.collapsed,
color: attachment.color,
text: attachment.text,
ts: attachment.timestamp ? attachment.timestamp.toJSON() : attachment.timestamp,
message_link: attachment.timestampLink,
thumb_url: attachment.thumbnailUrl,
author_name: attachment.author ? attachment.author.name : undefined,
author_link: attachment.author ? attachment.author.link : undefined,
author_icon: attachment.author ? attachment.author.icon : undefined,
title: attachment.title ? attachment.title.value : undefined,
title_link: attachment.title ? attachment.title.link : undefined,
title_link_download: attachment.title ? attachment.title.displayDownloadLink : undefined,
image_dimensions: attachment.imageDimensions,
image_preview: attachment.imagePreview,
image_url: attachment.imageUrl,
image_type: attachment.imageType,
image_size: attachment.imageSize,
audio_url: attachment.audioUrl,
audio_type: attachment.audioType,
audio_size: attachment.audioSize,
video_url: attachment.videoUrl,
video_type: attachment.videoType,
video_size: attachment.videoSize,
fields: attachment.fields,
button_alignment: attachment.actionButtonsAlignment,
actions: attachment.actions,
type: attachment.type,
description: attachment.description,
}, attachment._unmappedProperties_));
}
_convertAttachmentsToApp(attachments) {
if (typeof attachments === 'undefined' || !Array.isArray(attachments)) {
return undefined;
}
const map = {
collapsed: 'collapsed',
color: 'color',
text: 'text',
timestampLink: 'message_link',
thumbnailUrl: 'thumb_url',
imageDimensions: 'image_dimensions',
imagePreview: 'image_preview',
imageUrl: 'image_url',
imageType: 'image_type',
imageSize: 'image_size',
audioUrl: 'audio_url',
audioType: 'audio_type',
audioSize: 'audio_size',
videoUrl: 'video_url',
videoType: 'video_type',
videoSize: 'video_size',
fields: 'fields',
actionButtonsAlignment: 'button_alignment',
actions: 'actions',
type: 'type',
description: 'description',
author: (attachment) => {
const {
author_name: name,
author_link: link,
author_icon: icon,
} = attachment;
delete attachment.author_name;
delete attachment.author_link;
delete attachment.author_icon;
return { name, link, icon };
},
title: (attachment) => {
const {
title: value,
title_link: link,
title_link_download: displayDownloadLink,
} = attachment;
delete attachment.title;
delete attachment.title_link;
delete attachment.title_link_download;
return { value, link, displayDownloadLink };
},
timestamp: (attachment) => {
const result = new Date(attachment.ts);
delete attachment.ts;
return result;
},
};
return attachments.map((attachment) => transformMappedData(attachment, map));
}
}
|
'use strict'
import React, { Component, PropTypes } from 'react'
import ReactDOM, { render } from 'react-dom'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as actions from '../actions/actionCreators'
import immutable from 'immutable'
import cx from 'classname'
import R from 'ramda'
import moment from 'moment'
import { fetchWeek } from '../utils'
import { TimePicker, TimeFormatter } from '../components'
@connect()
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
week: fetchWeek.now()
}
}
onNext(e) {
this.setState({
week: fetchWeek.next(this.state.week)
})
}
onPrev(e) {
this.setState({
week: fetchWeek.prev(this.state.week)
})
}
onSelection(selected) {
this.setState({
selected: selected
})
}
render() {
const { week, selected } = this.state
const slices = 4
return (
<div>
<Header/>
<Content>
<TimePicker
week={week}
slices={slices}
onNext={this.onNext.bind(this)}
onPrev={this.onPrev.bind(this)}
onSelection={this.onSelection.bind(this)}/>
<TimeFormatter
selected={selected}
slices={slices}/>
</Content>
<Footer/>
</div>
)
}
}
const Header = () => (
<div className='cal-Header'>
<div className='cal-Header-title'>
<h1 className='cal-Header-title-text'>Times I'm free</h1>
</div>
<div className='cal-Header-subtitle'>
<h3 className='cal-Header-subtitle-text'>
Select times you're free, get text to copy + paste anywhere
</h3>
</div>
</div>
)
const Content = ({ children }) => (
<div className='cal-Content'>
{children}
</div>
)
const Footer = () => (
<div></div>
)
|
import numpy as np
import skimage.io
from scipy.ndimage import zoom
from skimage.transform import resize
try:
# Python3 will most likely not be able to load protobuf
from caffe.proto import caffe_pb2
except:
import sys
if sys.version_info >= (3, 0):
print("Failed to include caffe_pb2, things might go wrong!")
else:
raise
# proto / datum / ndarray conversion
def blobproto_to_array(blob, return_diff=False):
"""
Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff.
"""
# Read the data into an array
if return_diff:
data = np.array(blob.diff)
else:
data = np.array(blob.data)
# Reshape the array
if blob.HasField('num') or blob.HasField('channels') or blob.HasField('height') or blob.HasField('width'):
# Use legacy 4D shape
return data.reshape(blob.num, blob.channels, blob.height, blob.width)
else:
return data.reshape(blob.shape.dim)
def array_to_blobproto(arr, diff=None):
"""Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check.
"""
blob = caffe_pb2.BlobProto()
blob.shape.dim.extend(arr.shape)
blob.data.extend(arr.astype(float).flat)
if diff is not None:
blob.diff.extend(diff.astype(float).flat)
return blob
def arraylist_to_blobprotovector_str(arraylist):
"""Converts a list of arrays to a serialized blobprotovec, which could be
then passed to a network for processing.
"""
vec = caffe_pb2.BlobProtoVector()
vec.blobs.extend([array_to_blobproto(arr) for arr in arraylist])
return vec.SerializeToString()
def blobprotovector_str_to_arraylist(str):
"""Converts a serialized blobprotovec to a list of arrays.
"""
vec = caffe_pb2.BlobProtoVector()
vec.ParseFromString(str)
return [blobproto_to_array(blob) for blob in vec.blobs]
def array_to_datum(arr, label=None):
"""Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format.
"""
if arr.ndim != 3:
raise ValueError('Incorrect array shape.')
datum = caffe_pb2.Datum()
datum.channels, datum.height, datum.width = arr.shape
if arr.dtype == np.uint8:
datum.data = arr.tostring()
else:
datum.float_data.extend(arr.astype(float).flat)
if label is not None:
datum.label = label
return datum
def datum_to_array(datum):
"""Converts a datum to an array. Note that the label is not returned,
as one can easily get it by calling datum.label.
"""
if len(datum.data):
return np.fromstring(datum.data, dtype=np.uint8).reshape(
datum.channels, datum.height, datum.width)
else:
return np.array(datum.float_data).astype(float).reshape(
datum.channels, datum.height, datum.width)
# Pre-processing
class Transformer:
"""
Transform input for feeding into a Net.
Note: this is mostly for illustrative purposes and it is likely better
to define your own input preprocessing routine for your needs.
Parameters
----------
net : a Net for which the input should be prepared
"""
def __init__(self, inputs):
self.inputs = inputs
self.transpose = {}
self.channel_swap = {}
self.raw_scale = {}
self.mean = {}
self.input_scale = {}
def __check_input(self, in_):
if in_ not in self.inputs:
raise Exception('{} is not one of the net inputs: {}'.format(
in_, self.inputs))
def preprocess(self, in_, data):
"""
Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net
"""
self.__check_input(in_)
caffe_in = data.astype(np.float32, copy=False)
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
in_dims = self.inputs[in_][2:]
if caffe_in.shape[:2] != in_dims:
caffe_in = resize_image(caffe_in, in_dims)
if transpose is not None:
caffe_in = caffe_in.transpose(transpose)
if channel_swap is not None:
caffe_in = caffe_in[channel_swap, :, :]
if raw_scale is not None:
caffe_in *= raw_scale
if mean is not None:
caffe_in -= mean
if input_scale is not None:
caffe_in *= input_scale
return caffe_in
def deprocess(self, in_, data):
"""
Invert Caffe formatting; see preprocess().
"""
self.__check_input(in_)
decaf_in = data.copy().squeeze()
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
if input_scale is not None:
decaf_in /= input_scale
if mean is not None:
decaf_in += mean
if raw_scale is not None:
decaf_in /= raw_scale
if channel_swap is not None:
decaf_in = decaf_in[np.argsort(channel_swap), :, :]
if transpose is not None:
decaf_in = decaf_in.transpose(np.argsort(transpose))
return decaf_in
def set_transpose(self, in_, order):
"""
Set the order of dimensions, e.g. to convert OpenCV's HxWxC images
into CxHxW.
Parameters
----------
in_ : which input to assign this dimension order
order : the order to transpose the dimensions
for example (2,0,1) changes HxWxC into CxHxW and (1,2,0) reverts
"""
self.__check_input(in_)
if len(order) != len(self.inputs[in_]) - 1:
raise Exception('Transpose order needs to have the same number of '
'dimensions as the input.')
self.transpose[in_] = order
def set_channel_swap(self, in_, order):
"""
Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model.
N.B. this assumes the channels are the first dimension AFTER transpose.
Parameters
----------
in_ : which input to assign this channel order
order : the order to take the channels.
(2,1,0) maps RGB to BGR for example.
"""
self.__check_input(in_)
if len(order) != self.inputs[in_][1]:
raise Exception('Channel swap needs to have the same number of '
'dimensions as the input channels.')
self.channel_swap[in_] = order
def set_raw_scale(self, in_, scale):
"""
Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.raw_scale[in_] = scale
def set_mean(self, in_, mean):
"""
Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable)
"""
self.__check_input(in_)
ms = mean.shape
if mean.ndim == 1:
# broadcast channels
if ms[0] != self.inputs[in_][1]:
raise ValueError('Mean channels incompatible with input.')
mean = mean[:, np.newaxis, np.newaxis]
else:
# elementwise mean
if len(ms) == 2:
ms = (1,) + ms
if len(ms) != 3:
raise ValueError('Mean shape invalid')
if ms != self.inputs[in_][1:]:
in_shape = self.inputs[in_][1:]
m_min, m_max = mean.min(), mean.max()
normal_mean = (mean - m_min) / (m_max - m_min)
mean = resize_image(normal_mean.transpose((1, 2, 0)),
in_shape[1:]).transpose((2, 0, 1)) * \
(m_max - m_min) + m_min
self.mean[in_] = mean
def set_input_scale(self, in_, scale):
"""
Set the scale of preprocessed inputs s.t. the blob = blob * scale.
N.B. input_scale is done AFTER mean subtraction and other preprocessing
while raw_scale is done BEFORE.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.input_scale[in_] = scale
# Image IO
def load_image(filename, color=True):
"""
Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale.
"""
img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
if img.ndim == 2:
img = img[:, :, np.newaxis]
if color:
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img
def resize_image(im, new_dims, interp_order=1):
"""
Resize an image array with interpolation.
Parameters
----------
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
interp_order : interpolation order, default is linear.
Returns
-------
im : resized ndarray with shape (new_dims[0], new_dims[1], K)
"""
if im.shape[-1] == 1 or im.shape[-1] == 3:
im_min, im_max = im.min(), im.max()
if im_max > im_min:
# skimage is fast but only understands {1,3} channel images
# in [0, 1].
im_std = (im - im_min) / (im_max - im_min)
resized_std = resize(im_std, new_dims, order=interp_order, mode='constant')
resized_im = resized_std * (im_max - im_min) + im_min
else:
# the image is a constant -- avoid divide by 0
ret = np.empty((new_dims[0], new_dims[1], im.shape[-1]),
dtype=np.float32)
ret.fill(im_min)
return ret
else:
# ndimage interpolates anything but more slowly.
scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2]))
resized_im = zoom(im, scale + (1,), order=interp_order)
return resized_im.astype(np.float32)
def oversample(images, crop_dims):
"""
Crop images into the four corners, center, and their mirrored versions.
Parameters
----------
image : iterable of (H x W x K) ndarrays
crop_dims : (height, width) tuple for the crops.
Returns
-------
crops : (10*N x H x W x K) ndarray of crops for number of inputs N.
"""
# Dimensions and center.
im_shape = np.array(images[0].shape)
crop_dims = np.array(crop_dims)
im_center = im_shape[:2] / 2.0
# Make crop coordinates
h_indices = (0, im_shape[0] - crop_dims[0])
w_indices = (0, im_shape[1] - crop_dims[1])
crops_ix = np.empty((5, 4), dtype=int)
curr = 0
for i in h_indices:
for j in w_indices:
crops_ix[curr] = (i, j, i + crop_dims[0], j + crop_dims[1])
curr += 1
crops_ix[4] = np.tile(im_center, (1, 2)) + np.concatenate([
-crop_dims / 2.0,
crop_dims / 2.0
])
crops_ix = np.tile(crops_ix, (2, 1))
# Extract crops
crops = np.empty((10 * len(images), crop_dims[0], crop_dims[1],
im_shape[-1]), dtype=np.float32)
ix = 0
for im in images:
for crop in crops_ix:
crops[ix] = im[crop[0]:crop[2], crop[1]:crop[3], :]
ix += 1
crops[ix - 5:ix] = crops[ix - 5:ix, :, ::-1, :] # flip for mirrors
return crops
|
# Copyright (c) 2014, Roger Duran
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the \"Software\"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Command-line wrapper to run commands and add rules to new windows
"""
import argparse
import atexit
import subprocess
from libqtile import ipc
from libqtile.command import graph
def run_cmd(opts) -> None:
if opts.socket is None:
socket = ipc.find_sockfile()
else:
socket = opts.socket
client = ipc.Client(socket)
root = graph.CommandGraphRoot()
cmd = [opts.cmd]
if opts.args:
cmd.extend(opts.args)
proc = subprocess.Popen(cmd)
match_args = {"net_wm_pid": proc.pid}
rule_args = {
"float": opts.float,
"intrusive": opts.intrusive,
"group": opts.group,
"break_on_match": not opts.dont_break,
}
graph_cmd = root.call("add_rule")
_, rule_id = client.send((root.selectors, graph_cmd.name, (match_args, rule_args), {}))
def remove_rule() -> None:
cmd = root.call("remove_rule")
client.send((root.selectors, cmd.name, (rule_id,), {}))
atexit.register(remove_rule)
proc.wait()
def add_subcommand(subparsers, parents):
parser = subparsers.add_parser(
"run-cmd", parents=parents, help="A wrapper around the command graph"
)
parser.add_argument("-s", "--socket", help="Use specified communication socket.")
parser.add_argument(
"-i", "--intrusive", action="store_true", help="If the new window should be intrusive."
)
parser.add_argument(
"-f", "--float", action="store_true", help="If the new window should be float."
)
parser.add_argument(
"-b",
"--dont-break",
action="store_true",
help="Do not break on match (keep applying rules).",
)
parser.add_argument("-g", "--group", help="Set the window group.")
parser.add_argument("cmd", help="Command to execute."),
parser.add_argument(
"args",
nargs=argparse.REMAINDER,
metavar="[args ...]",
help="Optional arguments to pass to command.",
)
parser.set_defaults(func=run_cmd)
|
'use strict';
var vue = require('vue');
var Ripple = require('primevue/ripple');
var Dropdown = require('primevue/dropdown');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var Ripple__default = /*#__PURE__*/_interopDefaultLegacy(Ripple);
var Dropdown__default = /*#__PURE__*/_interopDefaultLegacy(Dropdown);
var script = {
name: 'CurrentPageReport',
inheritAttrs: false,
props: {
pageCount: {
type: Number,
default: 0
},
page: {
type: Number,
default: 0
},
first: {
type: Number,
default: 0
},
rows: {
type: Number,
default: 0
},
totalRecords: {
type: Number,
default: 0
},
template: {
type: String,
default: '({currentPage} of {totalPages})'
}
},
computed: {
text() {
let text = this.template
.replace("{currentPage}", this.page + 1)
.replace("{totalPages}", this.pageCount)
.replace("{first}", this.first + 1)
.replace("{last}", Math.min(this.first + this.rows, this.totalRecords))
.replace("{rows}", this.rows)
.replace("{totalRecords}", this.totalRecords);
return text;
}
}
};
const _hoisted_1 = { class: "p-paginator-current" };
function render(_ctx, _cache, $props, $setup, $data, $options) {
return (vue.openBlock(), vue.createBlock("span", _hoisted_1, vue.toDisplayString($options.text), 1))
}
script.render = render;
var script$1 = {
name: 'FirstPageLink',
computed: {
containerClass() {
return ['p-paginator-first p-paginator-element p-link', {
'p-disabled': this.$attrs.disabled
}];
}
},
directives: {
'ripple': Ripple__default['default']
}
};
const _hoisted_1$1 = /*#__PURE__*/vue.createVNode("span", { class: "p-paginator-icon pi pi-angle-double-left" }, null, -1);
function render$1(_ctx, _cache, $props, $setup, $data, $options) {
const _directive_ripple = vue.resolveDirective("ripple");
return vue.withDirectives((vue.openBlock(), vue.createBlock("button", {
class: $options.containerClass,
type: "button"
}, [
_hoisted_1$1
], 2)), [
[_directive_ripple]
])
}
script$1.render = render$1;
var script$2 = {
name: 'LastPageLink',
computed: {
containerClass() {
return ['p-paginator-last p-paginator-element p-link', {
'p-disabled': this.$attrs.disabled
}];
}
},
directives: {
'ripple': Ripple__default['default']
}
};
const _hoisted_1$2 = /*#__PURE__*/vue.createVNode("span", { class: "p-paginator-icon pi pi-angle-double-right" }, null, -1);
function render$2(_ctx, _cache, $props, $setup, $data, $options) {
const _directive_ripple = vue.resolveDirective("ripple");
return vue.withDirectives((vue.openBlock(), vue.createBlock("button", {
class: $options.containerClass,
type: "button"
}, [
_hoisted_1$2
], 2)), [
[_directive_ripple]
])
}
script$2.render = render$2;
var script$3 = {
name: 'NextPageLink',
computed: {
containerClass() {
return ['p-paginator-next p-paginator-element p-link', {
'p-disabled': this.$attrs.disabled
}];
}
},
directives: {
'ripple': Ripple__default['default']
}
};
const _hoisted_1$3 = /*#__PURE__*/vue.createVNode("span", { class: "p-paginator-icon pi pi-angle-right" }, null, -1);
function render$3(_ctx, _cache, $props, $setup, $data, $options) {
const _directive_ripple = vue.resolveDirective("ripple");
return vue.withDirectives((vue.openBlock(), vue.createBlock("button", {
class: $options.containerClass,
type: "button"
}, [
_hoisted_1$3
], 2)), [
[_directive_ripple]
])
}
script$3.render = render$3;
var script$4 = {
name: 'PageLinks',
inheritAttrs: false,
emits: ['click'],
props: {
value: Array,
page: Number
},
methods: {
onPageLinkClick(event, pageLink) {
this.$emit('click', {
originalEvent: event,
value: pageLink
});
}
},
directives: {
'ripple': Ripple__default['default']
}
};
const _hoisted_1$4 = { class: "p-paginator-pages" };
function render$4(_ctx, _cache, $props, $setup, $data, $options) {
const _directive_ripple = vue.resolveDirective("ripple");
return (vue.openBlock(), vue.createBlock("span", _hoisted_1$4, [
(vue.openBlock(true), vue.createBlock(vue.Fragment, null, vue.renderList($props.value, (pageLink) => {
return vue.withDirectives((vue.openBlock(), vue.createBlock("button", {
key: pageLink,
class: ['p-paginator-page p-paginator-element p-link', {'p-highlight': ((pageLink - 1) === $props.page)}],
type: "button",
onClick: $event => ($options.onPageLinkClick($event, pageLink))
}, [
vue.createTextVNode(vue.toDisplayString(pageLink), 1)
], 10, ["onClick"])), [
[_directive_ripple]
])
}), 128))
]))
}
script$4.render = render$4;
var script$5 = {
name: 'PrevPageLink',
computed: {
containerClass() {
return ['p-paginator-prev p-paginator-element p-link', {
'p-disabled': this.$attrs.disabled
}];
}
},
directives: {
'ripple': Ripple__default['default']
}
};
const _hoisted_1$5 = /*#__PURE__*/vue.createVNode("span", { class: "p-paginator-icon pi pi-angle-left" }, null, -1);
function render$5(_ctx, _cache, $props, $setup, $data, $options) {
const _directive_ripple = vue.resolveDirective("ripple");
return vue.withDirectives((vue.openBlock(), vue.createBlock("button", {
class: $options.containerClass,
type: "button"
}, [
_hoisted_1$5
], 2)), [
[_directive_ripple]
])
}
script$5.render = render$5;
var script$6 = {
name: 'RowsPerPageDropdown',
inheritAttrs: false,
emits: ['rows-change'],
props: {
options: Array,
rows: Number
},
methods: {
onChange(value) {
this.$emit('rows-change', value);
}
},
computed: {
rowsOptions() {
let opts = [];
if (this.options) {
for(let i= 0; i < this.options.length; i++) {
opts.push({label: String(this.options[i]), value: this.options[i]});
}
}
return opts;
}
},
components: {
'RPPDropdown': Dropdown__default['default']
}
};
function render$6(_ctx, _cache, $props, $setup, $data, $options) {
const _component_RPPDropdown = vue.resolveComponent("RPPDropdown");
return (vue.openBlock(), vue.createBlock(_component_RPPDropdown, {
modelValue: $props.rows,
options: $options.rowsOptions,
optionLabel: "label",
optionValue: "value",
"onUpdate:modelValue": _cache[1] || (_cache[1] = $event => ($options.onChange($event))),
class: "p-paginator-rpp-options"
}, null, 8, ["modelValue", "options"]))
}
script$6.render = render$6;
var script$7 = {
name: 'JumpToPageDropdown',
inheritAttrs: false,
emits: ['page-change'],
props: {
page: Number,
pageCount: Number
},
methods: {
onChange(value) {
this.$emit('page-change', value);
}
},
computed: {
pageOptions() {
let opts = [];
for(let i= 0; i < this.pageCount; i++) {
opts.push({label: String(i+1), value: i});
}
return opts;
}
},
components: {
'JTPDropdown': Dropdown__default['default']
}
};
function render$7(_ctx, _cache, $props, $setup, $data, $options) {
const _component_JTPDropdown = vue.resolveComponent("JTPDropdown");
return (vue.openBlock(), vue.createBlock(_component_JTPDropdown, {
modelValue: $props.page,
options: $options.pageOptions,
optionLabel: "label",
optionValue: "value",
"onUpdate:modelValue": _cache[1] || (_cache[1] = $event => ($options.onChange($event))),
class: "p-paginator-page-options"
}, null, 8, ["modelValue", "options"]))
}
script$7.render = render$7;
var script$8 = {
name: 'Paginator',
emits: ['update:first', 'update:rows', 'page'],
props: {
totalRecords: {
type: Number,
default: 0
},
rows: {
type: Number,
default: 0
},
first: {
type: Number,
default: 0
},
pageLinkSize: {
type: Number,
default: 5
},
rowsPerPageOptions: {
type: Array,
default: null
},
template: {
type: String,
default: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown'
},
currentPageReportTemplate: {
type: null,
default: '({currentPage} of {totalPages})'
},
alwaysShow: {
type: Boolean,
default: true
}
},
data() {
return {
d_first: this.first,
d_rows: this.rows
}
},
watch: {
first(newValue) {
this.d_first = newValue;
},
rows(newValue) {
this.d_rows = newValue;
},
totalRecords(newValue) {
if (this.page > 0 && newValue && (this.d_first >= newValue)) {
this.changePage(this.pageCount - 1);
}
}
},
methods: {
changePage(p) {
const pc = this.pageCount;
if (p >= 0 && p < pc) {
this.d_first = this.d_rows * p;
const state = {
page: p,
first: this.d_first,
rows: this.d_rows,
pageCount: pc
};
this.$emit('update:first', this.d_first);
this.$emit('update:rows', this.d_rows);
this.$emit('page', state);
}
},
changePageToFirst(event) {
if(!this.isFirstPage) {
this.changePage(0);
}
event.preventDefault();
},
changePageToPrev(event) {
this.changePage(this.page - 1);
event.preventDefault();
},
changePageLink(event) {
this.changePage(event.value - 1);
event.originalEvent.preventDefault();
},
changePageToNext(event) {
this.changePage(this.page + 1);
event.preventDefault();
},
changePageToLast(event) {
if(!this.isLastPage) {
this.changePage(this.pageCount - 1);
}
event.preventDefault();
},
onRowChange(value) {
this.d_rows = value;
this.changePage(this.page);
}
},
computed: {
templateItems() {
let keys = [];
this.template.split(' ').map((value) => {
keys.push(value.trim());
});
return keys;
},
page() {
return Math.floor(this.d_first / this.d_rows);
},
pageCount() {
return Math.ceil(this.totalRecords / this.d_rows) || 1;
},
isFirstPage() {
return this.page === 0;
},
isLastPage() {
return this.page === this.pageCount - 1;
},
calculatePageLinkBoundaries() {
const numberOfPages = this.pageCount;
const visiblePages = Math.min(this.pageLinkSize, numberOfPages);
//calculate range, keep current in middle if necessary
let start = Math.max(0, Math.ceil(this.page - ((visiblePages) / 2)));
let end = Math.min(numberOfPages - 1, start + visiblePages - 1);
//check when approaching to last page
const delta = this.pageLinkSize - (end - start + 1);
start = Math.max(0, start - delta);
return [start, end];
},
pageLinks() {
let pageLinks = [];
let boundaries = this.calculatePageLinkBoundaries;
let start = boundaries[0];
let end = boundaries[1];
for(var i = start; i <= end; i++) {
pageLinks.push(i + 1);
}
return pageLinks;
},
currentState() {
return {
page: this.page,
first: this.d_first,
rows: this.d_rows
}
}
},
components: {
'CurrentPageReport': script,
'FirstPageLink': script$1,
'LastPageLink': script$2,
'NextPageLink': script$3,
'PageLinks': script$4,
'PrevPageLink': script$5,
'RowsPerPageDropdown': script$6,
'JumpToPageDropdown': script$7
}
};
const _hoisted_1$6 = {
key: 0,
class: "p-paginator p-component"
};
const _hoisted_2 = {
key: 0,
class: "p-paginator-left-content"
};
const _hoisted_3 = {
key: 1,
class: "p-paginator-right-content"
};
function render$8(_ctx, _cache, $props, $setup, $data, $options) {
const _component_FirstPageLink = vue.resolveComponent("FirstPageLink");
const _component_PrevPageLink = vue.resolveComponent("PrevPageLink");
const _component_NextPageLink = vue.resolveComponent("NextPageLink");
const _component_LastPageLink = vue.resolveComponent("LastPageLink");
const _component_PageLinks = vue.resolveComponent("PageLinks");
const _component_CurrentPageReport = vue.resolveComponent("CurrentPageReport");
const _component_RowsPerPageDropdown = vue.resolveComponent("RowsPerPageDropdown");
const _component_JumpToPageDropdown = vue.resolveComponent("JumpToPageDropdown");
return ($props.alwaysShow ? true : ($options.pageLinks && $options.pageLinks.length > 1))
? (vue.openBlock(), vue.createBlock("div", _hoisted_1$6, [
(_ctx.$slots.left)
? (vue.openBlock(), vue.createBlock("div", _hoisted_2, [
vue.renderSlot(_ctx.$slots, "left", { state: $options.currentState })
]))
: vue.createCommentVNode("", true),
(vue.openBlock(true), vue.createBlock(vue.Fragment, null, vue.renderList($options.templateItems, (item) => {
return (vue.openBlock(), vue.createBlock(vue.Fragment, { key: item }, [
(item === 'FirstPageLink')
? (vue.openBlock(), vue.createBlock(_component_FirstPageLink, {
key: 0,
onClick: _cache[1] || (_cache[1] = $event => ($options.changePageToFirst($event))),
disabled: $options.isFirstPage
}, null, 8, ["disabled"]))
: (item === 'PrevPageLink')
? (vue.openBlock(), vue.createBlock(_component_PrevPageLink, {
key: 1,
onClick: _cache[2] || (_cache[2] = $event => ($options.changePageToPrev($event))),
disabled: $options.isFirstPage
}, null, 8, ["disabled"]))
: (item === 'NextPageLink')
? (vue.openBlock(), vue.createBlock(_component_NextPageLink, {
key: 2,
onClick: _cache[3] || (_cache[3] = $event => ($options.changePageToNext($event))),
disabled: $options.isLastPage
}, null, 8, ["disabled"]))
: (item === 'LastPageLink')
? (vue.openBlock(), vue.createBlock(_component_LastPageLink, {
key: 3,
onClick: _cache[4] || (_cache[4] = $event => ($options.changePageToLast($event))),
disabled: $options.isLastPage
}, null, 8, ["disabled"]))
: (item === 'PageLinks')
? (vue.openBlock(), vue.createBlock(_component_PageLinks, {
key: 4,
value: $options.pageLinks,
page: $options.page,
onClick: _cache[5] || (_cache[5] = $event => ($options.changePageLink($event)))
}, null, 8, ["value", "page"]))
: (item === 'CurrentPageReport')
? (vue.openBlock(), vue.createBlock(_component_CurrentPageReport, {
key: 5,
template: $props.currentPageReportTemplate,
page: $options.page,
pageCount: $options.pageCount,
first: $data.d_first,
rows: $data.d_rows,
totalRecords: $props.totalRecords
}, null, 8, ["template", "page", "pageCount", "first", "rows", "totalRecords"]))
: (item === 'RowsPerPageDropdown' && $props.rowsPerPageOptions)
? (vue.openBlock(), vue.createBlock(_component_RowsPerPageDropdown, {
key: 6,
rows: $data.d_rows,
options: $props.rowsPerPageOptions,
onRowsChange: _cache[6] || (_cache[6] = $event => ($options.onRowChange($event)))
}, null, 8, ["rows", "options"]))
: (item === 'JumpToPageDropdown')
? (vue.openBlock(), vue.createBlock(_component_JumpToPageDropdown, {
key: 7,
page: $options.page,
pageCount: $options.pageCount,
onPageChange: _cache[7] || (_cache[7] = $event => ($options.changePage($event)))
}, null, 8, ["page", "pageCount"]))
: vue.createCommentVNode("", true)
], 64))
}), 128)),
(_ctx.$slots.right)
? (vue.openBlock(), vue.createBlock("div", _hoisted_3, [
vue.renderSlot(_ctx.$slots, "right", { state: $options.currentState })
]))
: vue.createCommentVNode("", true)
]))
: vue.createCommentVNode("", true)
}
function styleInject(css, ref) {
if ( ref === void 0 ) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') { return; }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var css_248z = "\n.p-paginator {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n -webkit-box-pack: center;\n -ms-flex-pack: center;\n justify-content: center;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n}\n.p-paginator-left-content {\n\tmargin-right: auto;\n}\n.p-paginator-right-content {\n\tmargin-left: auto;\n}\n.p-paginator-page,\n.p-paginator-next,\n.p-paginator-last,\n.p-paginator-first,\n.p-paginator-prev,\n.p-paginator-current {\n cursor: pointer;\n display: -webkit-inline-box;\n display: -ms-inline-flexbox;\n display: inline-flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n -webkit-box-pack: center;\n -ms-flex-pack: center;\n justify-content: center;\n line-height: 1;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n overflow: hidden;\n position: relative;\n}\n.p-paginator-element:focus {\n z-index: 1;\n position: relative;\n}\n";
styleInject(css_248z);
script$8.render = render$8;
module.exports = script$8;
|
from elasticsearch import Elasticsearch
es = Elasticsearch('http://localhost:9200')
from math import sqrt
keepwords = open('keepwords.txt').read()
keepwords = keepwords.split('\n')
def scoredFingerprint(terms):
fp = {}
for term, value in terms.items():
if value[1] < 100 or term in keepwords:
fp[term] = (1.0) #float(value['term_freq']) / float(value['doc_freq'])
else:
print("Ommitting %s" % term)
return fp
def scoredTvs(tvs, sampleEvery=1):
i = 0
for docId, tv in tvs:
if (i % sampleEvery == 0):
yield (docId, scoredFingerprint(tv))
i += 1
def allCorpusDocs(index='stackexchange', doc_type='post'):
query = {
"sort": ["_doc"],
"size": 500
}
resp = es.search(index=index, doc_type=doc_type, scroll='1m', body=query)
i = 500
while len(resp['hits']['hits']) > 0:
for doc in resp['hits']['hits']:
yield doc['_id']
print("Retrieved %s ids" % i)
i += 500
break
scrollId = resp['_scroll_id']
resp = es.scroll(scroll_id=scrollId, scroll='1m')
def justTfandDf(terms):
tfAndDf = {}
for term, value in terms.items():
tfAndDf[term] = (value['term_freq'], value['doc_freq'])
return tfAndDf
def termVectors(docIds, index='stackexchange', doc_type='post', field='Body.bigramed'):
tvs = es.mtermvectors(ids=docIds, index=index, doc_type=doc_type, fields=field, term_statistics=True)
for tv in tvs['docs']:
try:
yield (tv['_id'], justTfandDf(tv['term_vectors'][field]['terms']))
except KeyError:
pass
def groupEveryN(l, n=10):
for i in range(0, len(l), n):
yield l[i:i+n]
def allTermVectors(docIds, field='Body.bigramed'):
i = n = 100
for docIdGroup in groupEveryN(docIds, n=n):
for tv in termVectors(docIds=docIdGroup, field=field):
yield tv
print("Fetched %s termvectors" % i)
i += n
def say(a_list):
print(" ".join(a_list))
tdc = None
def buildStackexchange(field='Body.bigramed', numTopics=50, sampleEvery=1):
import pickleCache
docIds = tvs = None
try:
docIds = pickleCache.fetch('docIds')
except KeyError:
docIds = [docId for docId in allCorpusDocs()]
pickleCache.save('docIds')
print("Fetching %s Term Vectors" % len(docIds))
from lsi import TermDocCollection
try:
tvs = pickleCache.fetch(field + '.tws')
except KeyError:
tvs = [tv for tv in allTermVectors(docIds, field=field)]
pickleCache.save(field + '.tws', tvs)
tdc = TermDocCollection(scoredTvs(tvs, sampleEvery=sampleEvery), numTopics=numTopics)
print(tdc.getTermvector('11336'))
blurred = tdc.getBlurredTerms('11336')
print(blurred[1][:10])
return tdc
if __name__ == "__main__":
from sys import argv
buildStackexchange(argv[1], 100)
print("DEMO AUTOGEN SYNONYMS FOR DOCUMENTS")
print("\n**star wars document**")
|
/**
* DevExtreme (ui/tree_list/ui.tree_list.filter_row.js)
* Version: 18.2.3
* Build date: Wed Nov 07 2018
*
* Copyright (c) 2012 - 2018 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
var core = require("./ui.tree_list.core"),
filterRowModule = require("../grid_core/ui.grid_core.filter_row");
core.registerModule("filterRow", filterRowModule);
|
var class_microsoft_1_1_bot_1_1_connector_1_1_signin_card =
[
[ "SigninCard", "dc/d03/class_microsoft_1_1_bot_1_1_connector_1_1_signin_card.html#adab54026b945dbe3b14a49d2f0761317", null ],
[ "SigninCard", "dc/d03/class_microsoft_1_1_bot_1_1_connector_1_1_signin_card.html#af683c37a7e850e5e2b2f947684f4128e", null ],
[ "Create", "dc/d03/class_microsoft_1_1_bot_1_1_connector_1_1_signin_card.html#a0fa6a7fe0b557407fbb9f71546ac903f", null ],
[ "ContentType", "dc/d03/class_microsoft_1_1_bot_1_1_connector_1_1_signin_card.html#a18613603602cd6eb725a6d97cca2c29c", null ],
[ "Buttons", "dc/d03/class_microsoft_1_1_bot_1_1_connector_1_1_signin_card.html#a541836721d3c49d5632728b5bd0e72d8", null ],
[ "Text", "dc/d03/class_microsoft_1_1_bot_1_1_connector_1_1_signin_card.html#ae03035f447d1e96deaba0b1ae89f3794", null ]
];
|
#ifndef END_MATCH_H
#define END_MATCH_H
#include <stdbool.h>
// forward declaration
struct EndMatch;
typedef struct EndMatch EndMatch;
#include "../../common/io/outputStream.h"
#include "../../common/timer/cenTimer.h"
#include "../../robot/config/robotConfig.h"
/** We take 1 seconds to be sure that it will be ok. */
#define MATCH_DURATION 98
/** When the last Action Time must be done */
#define MATCH_LAST_ACTION_TIME MATCH_DURATION - 3
// Forward declaration
struct EndMatch;
typedef struct EndMatch EndMatch;
/**
* Type of function to do just before the end of the match
*/
typedef bool EndMatchBeforeEndFunction(EndMatch* endMatch);
/**
* All elements to manage the end of the match
*/
struct EndMatch {
/** To get the configuration. */
RobotConfig* robotConfig;
/** The match duration. */
int matchDurationInSecond;
/** Current Time In Second. */
int currentTimeInSecond;
/** Avoid that it does not take any instruction at the end. */
bool doNotEnd;
/** The timer struct to detect the end of the match. */
Timer* endMatchDetectorDeviceTimer;
/** If we have shown that the match was ended. */
bool endOfMatchNotified;
/** The score which must be shown. */
unsigned int scoreToShow;
/** If we show the score at the end. */
bool showScoreAtTheEndOfMatch;
/** What we must do some seconds before the end of the match */
EndMatchBeforeEndFunction* endMatchBeforeEndFunction;
/** If we have done the action before the end of the match */
bool actionBeforeEndOfMatchDone;
};
/**
* Initializes the end Match structure.
*/
void initEndMatch(EndMatch* endMatch,
RobotConfig* robotConfig,
unsigned int matchDurationInSecond,
EndMatchBeforeEndFunction* endMatchBeforeEndFunction);
/**
* Start the match.
*/
void markStartMatch(EndMatch* endMatch);
/**
* Reset the match.
*/
void resetStartMatch(EndMatch* endMatch);
/**
* Show the remaining time (before clear the screen).
* @param endMatch
* @param outputStream
*/
void showRemainingTime(EndMatch* endMatch, OutputStream* outputStream);
/**
* Show to an output Stream the result of the match.
* @return true if we have shown the end of the match
*/
void showEndAndScore(EndMatch* endMatch, OutputStream* outputStream);
/**
* Show to an output Stream the result of the match, but only if needed (if endMatch is not finished and not already shown)
* @return true if we have shown the end of the match
*/
bool showEndAndScoreIfNeeded(EndMatch* endMatch, OutputStream* outputStream);
/**
* Returns how much time was passed.
*/
int getCurrentTimeInSecond(EndMatch* endMatch);
/**
* Returns how much time in seconds are remaining
*/
unsigned int matchEndGetRemainingTime(EndMatch* endMatch);
/**
* Return true if this is the end of the match.
*/
bool isMatchFinished(EndMatch* endMatch);
/**
* Returns true if this is just before the end of the match.
*/
bool isMatchJustBeforeTheEnd(EndMatch* endMatch);
/**
* Do the action before the end of the match if we expect it.
* @param endMatch
*/
bool doActionBeforeEndOfMatch(EndMatch* endMatch, OutputStream* outputStream);
#endif
|
"""This script creates a simple static plot of data from the DtssHost via a DtsClient."""
import os
import sys
import logging
import socket
import shyft.time_series as st
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
from bokeh.plotting import figure, ColumnDataSource
from visual.utils import bokeh_time_from_timestamp, get_xy
from weather.data_sources.netatmo.domain import NetatmoDomain
from weather.data_sources.netatmo.repository import NetatmoEncryptedEnvVarConfig
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s",
handlers=[
logging.StreamHandler()
])
env_pass = sys.argv[1]
env_salt = sys.argv[2]
config = NetatmoEncryptedEnvVarConfig(
username_var='NETATMO_USER',
password_var='NETATMO_PASS',
client_id_var='NETATMO_ID',
client_secret_var='NETATMO_SECRET',
password=env_pass,
salt=env_salt,
)
# Get measurements form domain:
domain = NetatmoDomain(
username=config.username,
password=config.password,
client_id=config.client_id,
client_secret=config.client_secret
)
client = st.DtsClient(f'{os.environ["DTSS_SERVER"]}:{os.environ["DTSS_PORT_NUM"]}')
cal = st.Calendar('Europe/Oslo')
def dashboard(doc):
now_source = ColumnDataSource({'temp': [], 'time': [], 'color': []})
period = st.UtcPeriod(st.utctime_now() - st.Calendar.DAY, st.utctime_now())
fig = figure(
title='Show current outdoor temperature!',
x_axis_type='datetime',
sizing_mode='scale_both',
# y_range=[15, 35],
)
fig.circle(source=now_source, x='time', y='temp', color='color', size=10)
# fig.x_range = Range1d(bokeh_time_from_timestamp(cal, period.start), bokeh_time_from_timestamp(cal, period.end))
def update():
# Update dashboard data.
period = st.UtcPeriod(st.utctime_now() - st.Calendar.DAY, st.utctime_now())
data = client.evaluate(st.TsVector(
[
domain.get_measurement(
station_name='Eftasåsen',
module_name='Ute',
data_type='Temperature'
).time_series
]),
period)
time, temp = get_xy(cal, data[0])
new = {'temp': [temp[-1]],
'time': [bokeh_time_from_timestamp(cal, st.utctime_now())],
'color': ['blue']
}
now_source.stream(new, 100)
# fig.x_range = Range1d(bokeh_time_from_timestamp(cal, period.start), bokeh_time_from_timestamp(cal, period.end))
update()
doc.add_periodic_callback(update, 1000)
doc.title = "Now with live updating!"
doc.add_root(fig)
apps = {'/test': Application(FunctionHandler(dashboard))}
port = 5000
server = Server(apps,
port=port,
# address=socket.gethostbyname(socket.gethostname()),
# host=f'localhost:{port}',
allow_websocket_origin=[
f'localhost:{port}', # Localhost by name
f'{socket.gethostbyname(socket.gethostname())}:{port}' # Localhost by IP
])
server.io_loop.start()
|
# coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class ShowMessagesResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'messages': 'list[ShowMessagesRespMessages]',
'messages_count': 'int',
'offsets_count': 'int',
'offset': 'int'
}
attribute_map = {
'messages': 'messages',
'messages_count': 'messages_count',
'offsets_count': 'offsets_count',
'offset': 'offset'
}
def __init__(self, messages=None, messages_count=None, offsets_count=None, offset=None):
"""ShowMessagesResponse - a model defined in huaweicloud sdk"""
super(ShowMessagesResponse, self).__init__()
self._messages = None
self._messages_count = None
self._offsets_count = None
self._offset = None
self.discriminator = None
if messages is not None:
self.messages = messages
if messages_count is not None:
self.messages_count = messages_count
if offsets_count is not None:
self.offsets_count = offsets_count
if offset is not None:
self.offset = offset
@property
def messages(self):
"""Gets the messages of this ShowMessagesResponse.
消息列表。
:return: The messages of this ShowMessagesResponse.
:rtype: list[ShowMessagesRespMessages]
"""
return self._messages
@messages.setter
def messages(self, messages):
"""Sets the messages of this ShowMessagesResponse.
消息列表。
:param messages: The messages of this ShowMessagesResponse.
:type: list[ShowMessagesRespMessages]
"""
self._messages = messages
@property
def messages_count(self):
"""Gets the messages_count of this ShowMessagesResponse.
消息总数。
:return: The messages_count of this ShowMessagesResponse.
:rtype: int
"""
return self._messages_count
@messages_count.setter
def messages_count(self, messages_count):
"""Sets the messages_count of this ShowMessagesResponse.
消息总数。
:param messages_count: The messages_count of this ShowMessagesResponse.
:type: int
"""
self._messages_count = messages_count
@property
def offsets_count(self):
"""Gets the offsets_count of this ShowMessagesResponse.
总页数。
:return: The offsets_count of this ShowMessagesResponse.
:rtype: int
"""
return self._offsets_count
@offsets_count.setter
def offsets_count(self, offsets_count):
"""Sets the offsets_count of this ShowMessagesResponse.
总页数。
:param offsets_count: The offsets_count of this ShowMessagesResponse.
:type: int
"""
self._offsets_count = offsets_count
@property
def offset(self):
"""Gets the offset of this ShowMessagesResponse.
当前页数。
:return: The offset of this ShowMessagesResponse.
:rtype: int
"""
return self._offset
@offset.setter
def offset(self, offset):
"""Sets the offset of this ShowMessagesResponse.
当前页数。
:param offset: The offset of this ShowMessagesResponse.
:type: int
"""
self._offset = offset
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ShowMessagesResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
# coding: utf-8
"""
Catalog API
The Catalog API allows users to search for and locate an eBay catalog product that is a direct match for the product that they wish to sell. Listing against an eBay catalog product helps insure that all listings (based off of that catalog product) have complete and accurate information. In addition to helping to create high-quality listings, another benefit to the seller of using catalog information to create listings is that much of the details of the listing will be prefilled, including the listing title, the listing description, the item specifics, and a stock image for the product (if available). Sellers will not have to enter item specifics themselves, and the overall listing process is a lot faster and easier. # noqa: E501
OpenAPI spec version: v1_beta.5.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class ErrorParameter(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'str',
'value': 'str'
}
attribute_map = {
'name': 'name',
'value': 'value'
}
def __init__(self, name=None, value=None): # noqa: E501
"""ErrorParameter - a model defined in Swagger""" # noqa: E501
self._name = None
self._value = None
self.discriminator = None
if name is not None:
self.name = name
if value is not None:
self.value = value
@property
def name(self):
"""Gets the name of this ErrorParameter. # noqa: E501
The object of the error. # noqa: E501
:return: The name of this ErrorParameter. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this ErrorParameter.
The object of the error. # noqa: E501
:param name: The name of this ErrorParameter. # noqa: E501
:type: str
"""
self._name = name
@property
def value(self):
"""Gets the value of this ErrorParameter. # noqa: E501
The value of the object. # noqa: E501
:return: The value of this ErrorParameter. # noqa: E501
:rtype: str
"""
return self._value
@value.setter
def value(self, value):
"""Sets the value of this ErrorParameter.
The value of the object. # noqa: E501
:param value: The value of this ErrorParameter. # noqa: E501
:type: str
"""
self._value = value
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(ErrorParameter, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ErrorParameter):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, g, request, abort
from dataviva.apps.general.views import get_locale
from dataviva.api.secex.services import Product as ProductService
from dataviva.api.secex.services import ProductTradePartners as ProductTradePartnersService
from dataviva.api.secex.services import ProductMunicipalities as ProductMunicipalitiesService
from dataviva.api.secex.services import ProductLocations as ProductLocationsService
from dataviva.api.attrs.models import Bra, Hs
mod = Blueprint('product', __name__,
template_folder='templates',
url_prefix='/<lang_code>/product',
static_folder='static')
@mod.before_request
def before_request():
g.page_type = 'category'
@mod.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.locale = values.pop('lang_code')
@mod.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', get_locale())
def location_depth(bra_id):
locations = {
1: "region", #todo
3: "state",
5: "mesoregion",
7: "microregion",
9: "municipality"
}
return locations[len(bra_id)]
def handle_region_bra_id(bra_id):
return {
"1": "1",
"2": "2",
"3": "5",
"4": "3",
"5": "4"
}[bra_id]
def location_service(depth, location):
if depth == 'region':
return handle_region_bra_id(location.id)
if depth == 'mesoregion':
return str(location.id_ibge)[:2] + str(location.id_ibge)[-2:]
if depth == 'microregion':
return str(location.id_ibge)[:2] + str(location.id_ibge)[-3:]
else:
return location.id_ibge
@mod.route('/<product_id>/graphs/<tab>', methods=['POST'])
def graphs(product_id, tab):
product = Hs.query.filter_by(id=product_id).first_or_404()
location = Bra.query.filter_by(id=request.args.get('bra_id')).first()
bra_id = request.args.get('bra_id')
if not bra_id:
depth = None
id_ibge = None
else:
depth = location_depth(bra_id)
id_ibge = location_service(depth, location)
return render_template('product/graphs-'+tab+'.html', product=product, location=location, graph=None, id_ibge=id_ibge)
@mod.route('/<product_id>', defaults={'tab': 'general'})
@mod.route('/<product_id>/<tab>')
def index(product_id, tab):
product = Hs.query.filter_by(id=product_id).first_or_404()
location = Bra.query.filter_by(id=request.args.get('bra_id')).first()
is_municipality = location and len(location.id) == 9
menu = request.args.get('menu')
url = request.args.get('url')
bra_id = request.args.get('bra_id')
bra_id = bra_id if bra_id != 'all' else None
if not bra_id:
depth = None
id_ibge = None
else:
depth = location_depth(bra_id)
id_ibge = location_service(depth, location)
if location:
location_id = location.id
else:
location_id = None
header = {}
body = {}
graph = {}
if menu:
graph['menu'] = menu
if url:
url_prefix = menu.split('-')[-1] + '/' if menu and menu.startswith('new-api-') else 'embed/'
graph['url'] = url_prefix + url
tabs = {
'general': [],
'opportunities': [
'economic-opportunities-rings',
'new-api-economic-opportunities-rings'
],
'trade-partner': [
'trade-balance-product-line',
'new-api-trade-balance-product-line',
'exports-destination-tree_map',
'new-api-exports-destination-tree_map',
'new-api-exports-destination-line',
'new-api-exports-port-line',
'new-api-exports-port-bar',
'new-api-exports-port-tree_map',
'new-api-exports-destination-stacked',
'exports-destination-line',
'exports-destination-stacked',
'imports-origin-tree_map',
'new-api-imports-origin-tree_map',
'new-api-imports-port-line',
'new-api-imports-port-bar',
'new-api-imports-port-tree_map',
'new-api-imports-origin-stacked',
'new-api-imports-origin-line',
'imports-origin-line',
'imports-origin-stacked',
],
}
if not is_municipality:
tabs['trade-partner'] += [
'exports-municipality-tree_map',
'new-api-exports-municipality-tree_map',
'exports-municipality-geo_map',
'new-api-exports-municipality-geo_map',
'exports-municipality-stacked',
'new-api-exports-municipality-stacked',
'imports-municipality-tree_map',
'new-api-imports-municipality-tree_map',
'imports-municipality-geo_map',
'new-api-imports-municipality-geo_map',
'imports-municipality-stacked',
'new-api-imports-municipality-stacked'
]
trade_partners_service = ProductTradePartnersService(
product_id=product.id, bra_id=location_id)
municipalities_service = ProductMunicipalitiesService(
product_id=product.id, bra_id=location_id)
if len(product.id) == 6:
product_service = ProductService(product_id=product.id)
header['pci'] = product_service.product_complexity()
if location:
product_service = ProductLocationsService(
product_id=product.id, bra_id=location_id)
if is_municipality:
body[
'municipality_name_export'] = municipalities_service.municipality_with_more_exports()
body[
'municipality_state_export'] = municipalities_service.municipality_with_more_exports_state()
body[
'municipality_export_value'] = municipalities_service.highest_export_value()
body[
'municipality_name_import'] = municipalities_service.municipality_with_more_imports()
body[
'municipality_state_import'] = municipalities_service.municipality_with_more_imports_state()
body[
'municipality_import_value'] = municipalities_service.highest_import_value()
else:
product_service = ProductService(product_id=product.id)
body[
'municipality_name_export'] = municipalities_service.municipality_with_more_exports()
body[
'municipality_state_export'] = municipalities_service.municipality_with_more_exports_state()
body[
'municipality_export_value'] = municipalities_service.highest_export_value()
body[
'municipality_name_import'] = municipalities_service.municipality_with_more_imports()
body[
'municipality_state_import'] = municipalities_service.municipality_with_more_imports_state()
body[
'municipality_import_value'] = municipalities_service.highest_import_value()
body['export_value_growth_in_five_years'] = product_service.export_value_growth_in_five_years()
header['year'] = product_service.year()
header['export_value'] = product_service.total_exported()
header['export_net_weight'] = product_service.unity_weight_export_price()
header['import_value'] = product_service.total_imported()
# Get rankings vars, code should be refactored
from dataviva.api.secex.models import Ymp, Ymbp
from dataviva import db
from sqlalchemy.sql.expression import func, desc
if location:
secex_query_export = Ymbp.query.filter(
Ymbp.year == 2017,
Ymbp.hs_id_len == len(product.id),
Ymbp.bra_id == location_id,
Ymbp.month == 0).order_by(Ymbp.export_val.desc())
secex_export = secex_query_export.all()
secex_query_import = Ymbp.query.filter(
Ymbp.year == 2017,
Ymbp.hs_id_len == len(product_id),
Ymbp.bra_id == location_id,
Ymbp.month == 0).order_by(Ymbp.import_val.desc())
secex_import = secex_query_import.all()
else:
max_year_query = db.session.query(
func.max(Ymp.year)).filter(Ymp.hs_id == product.id, Ymp.month == 12)
secex_query_export = Ymp.query.filter(
Ymp.year == max_year_query,
Ymp.hs_id_len == len(product.id),
Ymp.month == 0).order_by(Ymp.export_val.desc())
secex_export = secex_query_export.all()
secex_query_import = Ymp.query.filter(
Ymp.year == max_year_query,
Ymp.hs_id_len == len(product_id),
Ymp.month == 0).order_by(Ymp.import_val.desc())
secex_import = secex_query_import.all()
for ranking, product_ranking in enumerate(secex_export):
if secex_export[ranking].hs_id == product_id:
header['export_value_ranking'] = ranking + 1
break
for ranking, product_ranking in enumerate(secex_import):
if secex_import[ranking].hs_id == product_id:
header['import_value_ranking'] = ranking + 1
break
if tab not in tabs:
abort(404)
if menu and menu not in tabs[tab]:
abort(404)
if header['export_value'] is None and header['import_value'] is None:
abort(404)
else:
return render_template('product/index.html', header=header, body=body, product=product, location=location, is_municipality=is_municipality, tab=tab, graph=graph, id_ibge=id_ibge)
|
var searchData=
[
['o_5faccmode_4075',['O_ACCMODE',['../posix_8h.html#a4dc4d45e07d2abc899bcaf04b2846a87',1,'posix.h']]],
['o_5fappend_4076',['O_APPEND',['../posix_8h.html#ae036f789407d21f07b211552d67b3214',1,'posix.h']]],
['o_5fbinary_4077',['O_BINARY',['../posix_8h.html#a36fa9b2e726512bc17a7a6d3e39002be',1,'posix.h']]],
['o_5fcreat_4078',['O_CREAT',['../posix_8h.html#a1cf6b1de1fffedaa1d26b189e9a8d2cc',1,'posix.h']]],
['o_5fexcl_4079',['O_EXCL',['../posix_8h.html#a9f5acfe79fafe14b6694447bd0e9f10b',1,'posix.h']]],
['o_5fnoctty_4080',['O_NOCTTY',['../posix_8h.html#a2e375ab32c7ef4581b026be28e4cc116',1,'posix.h']]],
['o_5fnonblock_4081',['O_NONBLOCK',['../posix_8h.html#a39d33ce33804efd4d52606d59071c6d8',1,'posix.h']]],
['o_5frdonly_4082',['O_RDONLY',['../posix_8h.html#a7a68c9ffaac7dbcd652225dd7c06a54b',1,'posix.h']]],
['o_5frdwr_4083',['O_RDWR',['../posix_8h.html#abb0586253488ee61072b73557eeb873b',1,'posix.h']]],
['o_5ftext_4084',['O_TEXT',['../posix_8h.html#a9abb6d01b83e0bc5a6e2adeceb7dffd7',1,'posix.h']]],
['o_5ftrunc_4085',['O_TRUNC',['../posix_8h.html#ad1d67e453fb3031f40f8cd3403773813',1,'posix.h']]],
['o_5fwronly_4086',['O_WRONLY',['../posix_8h.html#a11b644a8526139c4cc1850dac1271ced',1,'posix.h']]]
];
|